AlgoViz

Session persistence

medium 25 min

Session 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

Our systemClient AClient BClient CLoad balancerround robinServer 1session AServer 2Server 3

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

Our systemClient AClient BClient CLoad balancercookieServer 11000 sessionsServer 21000 sessionsServer 3not started
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

    critical

    The tie only chooses a server. When that server stops, local sessions are gone.

    Wrong
    server.sessions[sid] = basket
    Right
    store.set(sid, basket, ttl=1800)
  • Using the first forwarded address

    critical

    The client can write anything there. Take the address from the right, after proxies you trust.

    Wrong
    ip = header.split(",")[0]
    Right
    ip = rightmost_untrusted(header, peer)
  • Saving a position instead of a name

    major

    Removing a server shifts every position after it, and clients go to the wrong place.

    Wrong
    ties[client] = servers.index(s)
    Right
    ties[client] = s.name
  • Calling modulo a consistent hash

    major

    Going from 3 to 4 servers moves about 75% of clients.

    Wrong
    servers[h(ip) % len(servers)]
    Right
    max(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.