Nov 17, 202612 min read

How to Add Redis to a Go net/http App

Store server-side sessions in Redis from a standard library Go API, with idle and absolute timeouts, logout everywhere and net/http middleware, using Encore locally and on ElastiCache or Memorystore, or go-redis and ElastiCache by hand.

Illustration for How to Add Redis to a Go net/http App

A Go service built on http.ServeMux keeps sessions in memory until there is a second replica, and then a user who signs in on one instance looks signed out on the next. Redis is the usual fix, and the work is mostly around it: a Redis on every laptop, an ElastiCache or Memorystore cluster per environment with TLS and an auth token, and a network path to a cache that only answers inside the VPC.

This guide adds Redis-backed sessions to a net/http API, with hashed tokens, an idle timeout that slides forward, a hard lifetime and a "log out everywhere" button. It starts with Encore, which declares the cache in Go next to the ServeMux and runs it locally and in your own AWS or GCP account, then shows the middleware with go-redis and ElastiCache.

Redis options for a net/http app at a glance

Encorego-redis + ElastiCacheSCS + goredisstore
Cache declared inGo code (cache.NewCluster)Terraform or the AWS consoleTerraform or the AWS console
Local RedisIn-memory Redis from encore runDocker Compose or a local installDocker Compose or a local install
Session formatTyped struct keyspace you designJSON you encode yourselfManaged by the library
Expiry per keyDefaultExpiry on the keyspaceTTL argument on each writeIdleTimeout and Lifetime settings
Production cacheElastiCache on AWS, Memorystore on GCP, in your accountElastiCache you provisionElastiCache you provision

How do you add Redis to net/http with Encore?

Encore

Encore works alongside a standard library app, so the ServeMux, the middleware and the cookies stay plain net/http, and the Redis behind them is a typed Go declaration in the same file. The mux is mounted in one raw endpoint with a fallback route, and the caching API gives each kind of data its own keyspace with a key pattern and an expiry.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create sessions-api --example=hello-world$ cd sessions-api && mkdir web

In the service below, sessions maps the SHA-256 of a cookie value to the session for 30 minutes, and every write resets that expiry, which is what makes the idle timeout slide. userSessions is a Redis set of a user's session hashes, so "log out everywhere" can find and delete all of them. The cluster uses NoEviction, since a session that Redis drops under memory pressure signs a user out for no visible reason:

// web/web.go package web import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "net/http" "time" "encore.dev/storage/cache" ) const ( idleTimeout = 30 * time.Minute // a session ends after 30 idle minutes maxLifetime = 12 * time.Hour // and never lives longer than 12 hours cookieName = "sid" ) // Sessions must not disappear under memory pressure, so the cluster // rejects writes when full instead of evicting keys. var cluster = cache.NewCluster("sessions", cache.ClusterConfig{ EvictionPolicy: cache.NoEviction, }) type Session struct { UserID string `json:"user_id"` CreatedAt time.Time `json:"created_at"` LastSeen time.Time `json:"last_seen"` } // Keyed by the SHA-256 of the cookie value, so a copy of Redis // does not contain usable session tokens. Every write resets the expiry. var sessions = cache.NewStructKeyspace[string, Session](cluster, cache.KeyspaceConfig{ KeyPattern: "session/:key", DefaultExpiry: cache.ExpireIn(idleTimeout), }) // The session hashes that belong to each user, for "log out everywhere". var userSessions = cache.NewSetKeyspace[string, string](cluster, cache.KeyspaceConfig{ KeyPattern: "user-sessions/:key", DefaultExpiry: cache.ExpireIn(maxLifetime), }) //encore:service type Service struct { mux *http.ServeMux } func initService() (*Service, error) { mux := http.NewServeMux() mux.HandleFunc("POST /login", login) mux.Handle("GET /me", requireSession(http.HandlerFunc(me))) mux.Handle("POST /logout", requireSession(http.HandlerFunc(logout))) mux.Handle("POST /logout-all", requireSession(http.HandlerFunc(logoutAll))) return &Service{mux: mux}, nil } // Fallback hands every request that no Encore endpoint matches to the ServeMux. // //encore:api public raw path=/!fallback func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) { s.mux.ServeHTTP(w, req) } func login(w http.ResponseWriter, r *http.Request) { var in struct { Email string `json:"email"` Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } userID, err := authenticate(r.Context(), in.Email, in.Password) if err != nil { http.Error(w, "wrong email or password", http.StatusUnauthorized) return } raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { http.Error(w, "could not start session", http.StatusInternalServerError) return } token := base64.RawURLEncoding.EncodeToString(raw) key := hashToken(token) now := time.Now() // SetIfNotExists is SET NX, so a colliding token can never take over a session. if err := sessions.SetIfNotExists(r.Context(), key, Session{UserID: userID, CreatedAt: now, LastSeen: now}); err != nil { http.Error(w, "could not start session", http.StatusInternalServerError) return } if _, err := userSessions.Add(r.Context(), userID, key); err != nil { http.Error(w, "could not start session", http.StatusInternalServerError) return } http.SetCookie(w, &http.Cookie{ Name: cookieName, Value: token, Path: "/", MaxAge: int(maxLifetime.Seconds()), HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, }) w.WriteHeader(http.StatusNoContent) } type ctxKey struct{} type current struct { Key string Session Session } // requireSession is ordinary net/http middleware: it loads the session, // enforces both timeouts and slides the idle expiry forward. func requireSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := r.Cookie(cookieName) if err != nil { http.Error(w, "not signed in", http.StatusUnauthorized) return } key := hashToken(c.Value) s, err := sessions.Get(r.Context(), key) if errors.Is(err, cache.Miss) { http.Error(w, "session expired", http.StatusUnauthorized) return } else if err != nil { http.Error(w, "session lookup failed", http.StatusServiceUnavailable) return } now := time.Now() if now.Sub(s.CreatedAt) > maxLifetime { _, _ = sessions.Delete(r.Context(), key) http.Error(w, "session expired", http.StatusUnauthorized) return } // Refresh at most once a minute. Replace is SET XX, so a session // deleted by a concurrent logout is not written back. if now.Sub(s.LastSeen) > time.Minute { s.LastSeen = now if err := sessions.Replace(r.Context(), key, s); errors.Is(err, cache.Miss) { http.Error(w, "session expired", http.StatusUnauthorized) return } else if err != nil { http.Error(w, "session lookup failed", http.StatusServiceUnavailable) return } } ctx := context.WithValue(r.Context(), ctxKey{}, current{Key: key, Session: s}) next.ServeHTTP(w, r.WithContext(ctx)) }) } func me(w http.ResponseWriter, r *http.Request) { cur := r.Context().Value(ctxKey{}).(current) w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]string{"user_id": cur.Session.UserID}) } func logout(w http.ResponseWriter, r *http.Request) { cur := r.Context().Value(ctxKey{}).(current) if _, err := sessions.Delete(r.Context(), cur.Key); err != nil { http.Error(w, "could not end session", http.StatusServiceUnavailable) return } _, _ = userSessions.Remove(r.Context(), cur.Session.UserID, cur.Key) clearCookie(w) w.WriteHeader(http.StatusNoContent) } func logoutAll(w http.ResponseWriter, r *http.Request) { cur := r.Context().Value(ctxKey{}).(current) keys, err := userSessions.Items(r.Context(), cur.Session.UserID) if err != nil && !errors.Is(err, cache.Miss) { http.Error(w, "could not end sessions", http.StatusServiceUnavailable) return } if len(keys) > 0 { if _, err := sessions.Delete(r.Context(), keys...); err != nil { http.Error(w, "could not end sessions", http.StatusServiceUnavailable) return } } _, _ = userSessions.Delete(r.Context(), cur.Session.UserID) clearCookie(w) w.WriteHeader(http.StatusNoContent) } func clearCookie(w http.ResponseWriter) { http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true}) } func hashToken(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } // authenticate checks the credentials against your user store and returns // the user's ID. Replace it with a database lookup and a password hash // comparison such as bcrypt.CompareHashAndPassword. func authenticate(ctx context.Context, email, password string) (string, error) { return "", errors.New("authenticate: connect your user store") }

The flow was run with encore test against Encore's in-memory Redis: a valid cookie on GET /me returned 200 and moved LastSeen forward, a session created 13 hours earlier returned 401 despite a fresh idle timer, /logout made the same cookie return 401, and /logout-all ended a second session of the same user. Replace maps to SET ... XX, and on a missing key it returns an error matching cache.Miss, which is what stops a refresh from bringing back a session that a concurrent logout deleted.

Locally, encore run uses an in-memory Redis that keeps a small number of keys (currently 100, per the docs) and purges at random past that, so a long local session can end early, which does not happen against the NoEviction cluster in the cloud. On deploy, Encore provisions ElastiCache on AWS or Memorystore on GCP in your own account and wires the connection into the service.

Best fit: standard library Go APIs that keep sessions, limits or other short-lived state in Redis and want the same cache on a laptop and in their own AWS or GCP account.

go-redis and Amazon ElastiCache

The hand-built version uses go-redis with the same idea: a hashed key, a JSON value and a refresh with SET XX and a TTL that only succeeds while the key still exists. The middleware has the same func(http.Handler) http.Handler shape:

package main import ( "crypto/sha256" "crypto/tls" "encoding/hex" "encoding/json" "errors" "log" "net/http" "os" "time" "github.com/redis/go-redis/v9" ) const idleTimeout = 30 * time.Minute type Session struct { UserID string `json:"user_id"` CreatedAt time.Time `json:"created_at"` LastSeen time.Time `json:"last_seen"` } func main() { rdb := redis.NewClient(&redis.Options{ Addr: os.Getenv("REDIS_ADDR"), // ElastiCache primary endpoint:6379 Password: os.Getenv("REDIS_AUTH_TOKEN"), TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}, }) mux := http.NewServeMux() mux.Handle("GET /me", requireSession(rdb, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("signed in\n")) }))) srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second} log.Fatal(srv.ListenAndServe()) } func requireSession(rdb *redis.Client, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := r.Cookie("sid") if err != nil { http.Error(w, "not signed in", http.StatusUnauthorized) return } sum := sha256.Sum256([]byte(c.Value)) key := "session:" + hex.EncodeToString(sum[:]) raw, err := rdb.Get(r.Context(), key).Bytes() if errors.Is(err, redis.Nil) { http.Error(w, "session expired", http.StatusUnauthorized) return } else if err != nil { http.Error(w, "session lookup failed", http.StatusServiceUnavailable) return } var s Session if err := json.Unmarshal(raw, &s); err != nil { http.Error(w, "session lookup failed", http.StatusServiceUnavailable) return } if time.Since(s.LastSeen) > time.Minute { s.LastSeen = time.Now() b, _ := json.Marshal(s) // SET ... XX EX: refresh only if a logout has not deleted the key. if ok, err := rdb.SetXX(r.Context(), key, b, idleTimeout).Result(); err != nil || !ok { http.Error(w, "session expired", http.StatusUnauthorized) return } } next.ServeHTTP(w, r) }) }

This version leaves out the absolute lifetime and the per-user set, which work the same way with CreatedAt in the value and SADD, SMEMBERS and DEL on a user-sessions:<id> key. Locally, the TLS config has to be switched off for a plain Redis container. A common pattern is to wrap redis.NewClient and set TLSConfig only when an environment variable says so. In AWS you create a replication group in private subnets with a subnet group and a security group that allows port 6379 from the app, turn on in-transit encryption and an auth token, set the parameter group's maxmemory-policy to noeviction for session data, and inject the token from Secrets Manager in every environment.

A small wrapper around redis.NewClient that sets TLSConfig only when REDIS_TLS=1 keeps one codebase for both:

func newRedisClient() *redis.Client { opts := &redis.Options{ Addr: os.Getenv("REDIS_ADDR"), Password: os.Getenv("REDIS_AUTH_TOKEN"), } if os.Getenv("REDIS_TLS") == "1" { opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } return redis.NewClient(opts) }

A compact Terraform shape for the cache itself looks like this:

resource "aws_elasticache_replication_group" "sessions" { replication_group_id = "http-sessions" description = "Session store" engine = "valkey" engine_version = "8.0" node_type = "cache.t4g.small" num_cache_clusters = 2 port = 6379 subnet_group_name = aws_elasticache_subnet_group.sessions.name security_group_ids = [aws_security_group.redis.id] at_rest_encryption_enabled = true transit_encryption_enabled = true automatic_failover_enabled = true }

Do not pass the ElastiCache auth token through a Terraform variable, which stores it in state. Set the token outside Terraform, for example with the AWS CLI, keep it in Secrets Manager, and inject REDIS_AUTH_TOKEN into the task from that secret, with REDIS_ADDR set to the primary endpoint and REDIS_TLS=1 in every AWS environment. The Redis security group should allow 6379 only from the API security group, not from the internet. For local development, run a Redis or Valkey container on 6379 without TLS, point REDIS_ADDR at localhost:6379, and leave REDIS_TLS unset:

docker run --rm -d --name sessions-redis -p 6379:6379 redis:7 export REDIS_ADDR=127.0.0.1:6379 # REDIS_TLS is left unset, so newRedisClient skips TLSConfig go run .

Against ElastiCache, set REDIS_TLS=1 and inject REDIS_AUTH_TOKEN from Secrets Manager. A session store should also set the parameter group's maxmemory-policy to noeviction, as above, so Redis does not drop a session under memory pressure.

Best fit: teams that already manage ElastiCache in Terraform and want direct control of every Redis command and client option.

SCS with goredisstore

SCS is a session manager written for net/http, and its goredisstore package keeps the data in Redis through a go-redis client. Wrapping the mux in sessionManager.LoadAndSave(mux) loads and saves the session on each request, IdleTimeout and Lifetime cover both timeouts, and RenewToken issues a new token at login, which the OWASP session guidance recommends after any privilege change:

package main import ( "encoding/json" "log" "net/http" "os" "time" "github.com/alexedwards/scs/v2" "github.com/alexedwards/scs/v2/goredisstore" "github.com/redis/go-redis/v9" ) func main() { rdb := redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDR")}) sessionManager := scs.New() sessionManager.Store = goredisstore.New(rdb) sessionManager.IdleTimeout = 30 * time.Minute sessionManager.Lifetime = 12 * time.Hour sessionManager.Cookie.Secure = true sessionManager.Cookie.HttpOnly = true sessionManager.Cookie.SameSite = http.SameSiteLaxMode mux := http.NewServeMux() mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 1<<20) var in struct { Username string `json:"username"` Password string `json:"password"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { http.Error(w, "invalid JSON body", http.StatusBadRequest) return } userID, ok := authenticate(in.Username, in.Password) if !ok { http.Error(w, "invalid credentials", http.StatusUnauthorized) return } if err := sessionManager.RenewToken(r.Context()); err != nil { http.Error(w, "could not start session", http.StatusInternalServerError) return } sessionManager.Put(r.Context(), "user_id", userID) w.WriteHeader(http.StatusNoContent) }) mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) { userID := sessionManager.GetString(r.Context(), "user_id") if userID == "" { http.Error(w, "not signed in", http.StatusUnauthorized) return } w.Write([]byte(userID + "\n")) }) srv := &http.Server{ Addr: ":8080", Handler: sessionManager.LoadAndSave(mux), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } func authenticate(username, password string) (string, bool) { expected := os.Getenv("DEMO_PASSWORD") if expected == "" || username != "demo" || password != expected { return "", false } return "user-1", true }

To log a user out everywhere, Iterate walks every stored session and destroys the ones with a matching user ID, which reads the whole store on each call, so a per-user set of tokens is cheaper once there are many sessions. The ElastiCache setup is the same as the go-redis route, including the TLS wrapper and the security group rules above.

Best fit: apps that want session handling as a library with sensible defaults and do not need custom session records.

How to choose

Pick Encore when the net/http app needs Redis for sessions or other shared state and you want it declared in code, running locally and provisioned as ElastiCache or Memorystore in your own account. Pick go-redis with ElastiCache when the cache already lives in Terraform and you want the full command set. SCS fits teams that want a ready-made session manager and are fine running Redis themselves.

Frequently asked questions

How do I add Redis to a Go net/http server?

Create one Redis client at startup, for example redis.NewClient from go-redis, and use it from handlers and middleware with r.Context(). Middleware in net/http is a func(http.Handler) http.Handler, so a session check wraps the handlers that need it when you register them on the ServeMux.

How do I add Redis to a net/http app with Encore?

Declare a cluster with cache.NewCluster and typed keyspaces such as cache.NewStructKeyspace and cache.NewSetKeyspace, build the http.ServeMux in initService, and forward requests to it from a raw endpoint with path=/!fallback. encore run provides an in-memory Redis locally, and deploys get ElastiCache on AWS or Memorystore on GCP in your own account.

How do I implement a sliding session timeout in Redis?

Store the session with an expiry equal to the idle timeout and write it again with a fresh expiry when the user is active, at most once a minute to limit writes. Use SET with XX for the refresh so a session that a logout has already deleted is not written back, and keep the creation time in the value to enforce an absolute lifetime.

Should I store the raw session token in Redis?

Store a SHA-256 hash of the token as the key and keep the raw value only in the cookie. Anyone who reads a Redis snapshot then sees hashes that cannot be replayed as cookies, while the server can still look a session up by hashing the cookie it receives.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders