Users get logged out every few clicks after you add a second server behind a load balancer. Here is why it happens in Go, why sticky sessions are a trap, and the Redis fix.
You add a second server before a big sale. Traffic is fine, CPU is fine, nothing crashes. But support tickets start coming in: "I keep getting logged out." Users log in, click once, and they are back on the login page. Click again, and they are logged in. Then out again.
With one server, this never happened.
The short answer: your app keeps sessions in the memory of each server. When the load balancer sends the next request to a different server, that server has never seen the session, so it says 401. The fix is to keep sessions in one shared place, like Redis, that every server can read.
This post shows the bug in real Go code, the numbers from a load test, two "fixes" that look right but are not, and the real fix.
The code that works fine on one server
This is a small Go shop API. It has two endpoints: POST /login creates a session, and GET /me tells you who is logged in. The sessions live in a map:
// Sessions are kept in a map in this process's memory, so only the replica
// that handled the login recognizes the session cookie afterwards.
var (
sessionsMu sync.Mutex
sessions = map[string]string{} // token -> username
)
func handleLogin(w http.ResponseWriter, r *http.Request) {
// ... read the username from the body ...
token := fmt.Sprintf("%d-%s", time.Now().UnixNano(), body.Username)
sessionsMu.Lock()
sessions[token] = body.Username
sessionsMu.Unlock()
http.SetCookie(w, &http.Cookie{Name: "session", Value: token, Path: "/", MaxAge: 86400})
}
func handleMe(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session")
// ...
sessionsMu.Lock()
username, ok := sessions[cookie.Value]
sessionsMu.Unlock()
if !ok {
log.Printf("GET /me 401: session not found")
http.Error(w, "not logged in", http.StatusUnauthorized)
return
}
// ...
}
There is nothing wrong with this code on one server. The mutex is there, the cookie is set, the lookup is correct. Tests pass. Code review passes. That is why this bug is so easy to ship.
What happens with three servers
Now run three copies of the same app behind a load balancer that uses round-robin. Round-robin means request 1 goes to server 1, request 2 goes to server 2, request 3 goes to server 3, then back to server 1.
I ran exactly this: three replicas and a round-robin proxy in front. Log in once, then call /me six times with the same cookie:
$ curl -c jar -X POST localhost:8080/login -d '{"username":"maya"}'
{"username":"maya"}
$ curl -b jar localhost:8080/me # 401 not logged in
$ curl -b jar localhost:8080/me # 401 not logged in
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 401 not logged in
$ curl -b jar localhost:8080/me # 401 not logged in
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
One request in three works. That is the server that handled the login. It is the only one with the token in its map. The other two log this:
shop listening on :18081 (replica 1)
GET /me 401: session not found
GET /me 401: session not found
The cookie is fine. The browser sends it every time. The problem is that the session data is in one server's memory, and the cookie is only a key to look it up.
How bad is it under load?
I ran a k6 load test against it: 20 new users per second, each logs in and then makes 20 /me calls. Here is what k6 reported:
checks_succeeded...: 33.33% 2807 out of 8421
checks_failed......: 66.66% 5614 out of 8421
✓ login returns 200
✗ session still valid
http_req_failed................: 66.66% 5614 out of 8421
Two out of three requests fail. With three servers, a user's session is on one of them, so the chance that the next request lands on the right one is one in three. Add a fourth server and it gets worse.
Look at what does *not* show up: no crash, no high CPU, no memory alarm, no error in the login handler. All three servers are "healthy". Your health checks will stay green the whole time.
Fix #1 that looks right: sticky sessions
The first thing most people (and most AI assistants) suggest is sticky sessions. You tell the load balancer: "always send this user to the same server". Every load balancer supports it. AWS ALB, nginx, HAProxy, Kubernetes ingress. You flip one setting and the logouts stop.
So why is it a trap?
- A server restart logs out everyone on it. You deploy a new version, the server restarts, its map is empty. A third of your users are logged out. You will deploy many times a day.
- A crash or autoscaling does the same. If the autoscaler removes a server at night, all its users lose their session.
- Load gets uneven. A server that picked up many heavy users stays busy while the others sit idle, because users can't move.
- The bug is still there. You only made it rarer. Now it shows up during deploys, which is the worst time to debug it.
Sticky sessions hide the symptom. They do not fix the cause: the session lives in one place that can disappear.
Fix #2 that looks right: make the cookie last longer
Another common suggestion is "the session is expiring, so raise MaxAge" or "retry the request when you get 401". Neither helps. The cookie is not expiring; it is arriving at a server that has never heard of it. A longer cookie is a longer key to a lock that is not there.
The real fix: one session store for all servers
Move the sessions out of the process and into Redis. Every server reads and writes the same place, so it does not matter which one gets the request.
With go-redis the change is small:
import "github.com/redis/go-redis/v9"
const sessionTTL = 24 * time.Hour
cache := redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDR")})
On login, write the session to Redis instead of the map. Give it a TTL that matches the cookie, so old sessions clean themselves up:
token := fmt.Sprintf("%d-%s", time.Now().UnixNano(), body.Username)
// Sessions live in Redis, so every replica recognizes the cookie.
if err := cache.Set(ctx, "sess:"+token, body.Username, sessionTTL).Err(); err != nil {
log.Printf("store session: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{Name: "session", Value: token, Path: "/", MaxAge: 86400})
On every request, read it back from Redis:
username, err := cache.Get(ctx, "sess:"+cookie.Value).Result()
if err != nil {
http.Error(w, "not logged in", http.StatusUnauthorized)
return
}
That is the whole fix. The map and the mutex are gone. Now the same six curl calls:
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ curl -b jar localhost:8080/me # 200 {"username":"maya"}
$ redis-cli keys 'sess:*'
sess:1795457480640543881-maya
And the same k6 load test:
checks_succeeded...: 100.00% 8400 out of 8400
checks_failed......: 0.00% 0 out of 8400
✓ login returns 200
✓ session still valid
http_req_failed................: 0.00% 0 out of 8400
Zero failures. The p95 latency went from 0.31 ms to 0.42 ms on my laptop, because each request now makes one Redis call. That is a very small price.
You can now restart any server, deploy, or scale from 3 to 30 servers, and nobody gets logged out.
Before you ship it: four more things
The fix above solves the logout bug. For a real production app, also check these:
- Use a random session token. The example builds the token from the time and the username, which someone could guess. Use
crypto/rand, for example rand.Text() in Go 1.24 and newer.
- Set safe cookie flags. Add
HttpOnly: true, Secure: true and SameSite: http.SameSiteLaxMode to the cookie.
- Decide what happens when Redis is down. Right now every request returns 401, so all users look logged out. Return a 503 instead, so the problem is clear in your logs and dashboards, and run Redis with a replica.
- Keep the TTL and
MaxAge in step. If Redis forgets the session before the cookie expires, users get logged out early.
Common questions
Are sticky sessions always bad?
No. They are useful for things like WebSocket connections or a local cache that is fine to lose. They are bad as the *only* place a login lives, because servers restart and scale down.
Can I use JWT instead of Redis?
Yes. With a signed token like a JWT, the user's data is inside the cookie, so no server needs to remember anything. The trade-off is logout: you can't easily cancel a token before it expires. Many teams use short-lived JWTs plus a refresh token stored in a database. For a simple app, Redis sessions are easier to get right.
Can I store sessions in Postgres instead?
Yes, any store every server can reach works. Redis is common because it is fast and has built-in expiry (TTL). A sessions table in Postgres is fine for a small app, but you need to clean up old rows yourself.
Why didn't my tests catch this?
Because tests usually run one copy of the app. The bug only exists when there are two or more servers and a load balancer between them. You need a test that runs several replicas and checks that a login on one is accepted by the others, like the k6 test above.
Fix it yourself
Reading about a bug is not the same as finding it. The logout-after-scaleout stack gives you this exact shop: three replicas, a round-robin proxy, Redis, live traffic, and users being logged out. You get a terminal, an editor and the logs, in Go, Node.js, Python or Rust. When you think it is fixed, a k6 load test checks that no login is lost, so sticky sessions or a longer cookie will not pass.
You can browse stacks without an account. To run labs you sign in with your email or Google account. BustedStack uses your email address to
sign you in, and your name and profile picture to show your account and pre-fill certificates. We never access your Gmail, contacts or Drive,
sell your data or run ad trackers.
This site needs JavaScript to run labs.