AI Agent Sticky Session 2026
Sticky sessions for AI agents: externalizing state to Redis, nginx ip_hash and cookie stickiness, SSE settings, and rolling deploy pitfalls.
📜 Table of Contents
📖 Keep reading
Sticky Sessions for AI Agents: Keeping Context Across Instances
Three instances behind a load balancer. The first message lands on instance 1, the second on instance 2, and instance 2 has no idea what was said before. Users blame the model; the actual bug is where state lives.
Two separate problems get conflated: pinning a connection to an instance, and keeping session data out of process memory.
Two kinds of stickiness
- Connection stickiness: the load balancer pins a user to one instance. Solves "context is in process memory".
- Externalized state: session data in Redis or a database. Solves "instances can die".
Only the first means context is lost on restart or scale-in. Only the second means streaming responses break on connection migration. Production usually needs both, with externalized state as the primary mechanism.
Options
| Approach | How | Pros | Cons | Use when |
|---|---|---|---|---|
| Redis session store | shared state | stateless instances, free scaling | extra round trip, concurrent writes | most production systems |
| Sticky routing | ip_hash or cookie | quick, local cache hits | session lost on failure, load skew | local KV cache, resident GPU |
| Client-held state | encrypted cookie/JWT | zero server storage | size limits, hard to revoke | short stateless flows |
Redis details
Store more than a message array: messages, a version counter, a summary for older turns, and a TTL.
import json, redis
r = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)
def load_session(sid):
raw = r.get(f"sess:{sid}")
return json.loads(raw) if raw else {"messages": [], "ver": 0, "summary": ""}
def save_session(sid, sess, ttl=21600):
sess["ver"] += 1
r.set(f"sess:{sid}", json.dumps(sess, ensure_ascii=False), ex=ttl)
Three pitfalls: unbounded growth (cap turns, summarize older history with a cheap model), lost updates on concurrent writes (optimistic locking with a version field, or block duplicate submits), and TTL that fights user expectations.
nginx stickiness
upstream agent_backend {
ip_hash;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
keepalive 64;
}
ip_hash breaks down behind corporate NAT and carrier-grade NAT, where hundreds of users share one egress IP, and on mobile networks that change IP frequently. Cookie stickiness (sticky cookie srv_id expires=1h;) is steadier but requires OpenResty or a build with the sticky module; stock open source nginx does not include it.
For streaming, set proxy_buffering off and raise proxy_read_timeout past your longest tool run, otherwise responses cut off mid-answer.
Client-held state
Encrypted JWT or cookie keeps servers stateless, but cookies cap around 4KB, revocation is impossible before expiry, and key rotation invalidates everything. Fine for single-turn tools, wrong for long conversations.
When stickiness actually pays
If the agent caches prompt prefixes or KV cache inside the instance, stickiness reduces cost directly, since prefix cache hits are billed at a fraction of normal input price (check each vendor's current pricing). If the instance only holds chat history, externalize it and skip stickiness.
Rolling deploys
Remove traffic first, then wait for running tasks, then terminate: terminationGracePeriodSeconds: 120 plus a preStop sleep of about 20 seconds so the load balancer drops the instance before shutdown begins.
FAQ
Redis plus ip_hash? Unnecessary; ip_hash only helps local cache hit rate.
Encrypt sessions? Yes when personal data is involved, with keys in a KMS rather than config files.
Concurrent writes? Order messages by a server-side monotonic sequence, not arrival time.
Device switching? Bind sessions to user ID, not device ID.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.