Session persistence
medium 25 minSession persistence, also called sticky sessions or affinity, makes a load balancer send the same client to the same server.
See it run
Send requests with no tie, with a cookie, by address and by header, then lose a server.
Operations
No persistence
Round robin ignores who is asking. A second request lands on a server without the session.
Step 1 of 3
Log in
Client A logs in on Server 1, which keeps the session in memory.
Step 1: Log in
def route(request): return next(round_robin)def show_basket(server, client): return server.sessions.get(client) # maybe None- Recognises by
- Nothing
- Survives a server loss
- No local session
Round robin is the right rule for servers that keep no state.
In the real world
The same session persistence doing real jobs. Pick one and step through it.
Two old servers are full, and a third is added. Old ties do not move.
Step 1 of 3
Two busy servers
- Server 1
- 90%
- Server 2
- 90%
- Server 3
- 0%
Servers 1 and 2 hold all sessions.
Step 1: Two busy servers
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Believing stickiness protects data
criticalThe tie only chooses a server. When that server stops, local sessions are gone.
Wrongserver.sessions[sid] = basketRightstore.set(sid, basket, ttl=1800)Using the first forwarded address
criticalThe client can write anything there. Take the address from the right, after proxies you trust.
Wrongip = header.split(",")[0]Rightip = rightmost_untrusted(header, peer)Saving a position instead of a name
majorRemoving a server shifts every position after it, and clients go to the wrong place.
Wrongties[client] = servers.index(s)Rightties[client] = s.nameCalling modulo a consistent hash
majorGoing from 3 to 4 servers moves about 75% of clients.
Wrongservers[h(ip) % len(servers)]Rightmax(servers, key=lambda s: h(ip, s.name))
Interview tips
How to explain it
- Same client, same server, for a while.
- Like a hairdresser who remembers your haircut.
Pick a key
- Browser: cookie.
- App without cookies: header.
- Raw TCP: address or flow.
Plan for failure
- New tie to a healthy server.
- Local sessions are lost.
- Do not move people back.
Better default
- Stateless servers with a replicated store.
- Use stickiness for speed, not for correctness.