Modal Sticky Sessions: Serverless Routing with Affinity
The best AI tools 2026 increasingly ship stateful experiences: voice agents that hold a conversation, coding agents that keep context across turns, speech-to-text models that maintain decoder state across an audio stream, and multiplayer games that need a persistent world. All of these have one requirement in common — a user must come back to the same process on every request for the length of a session. On October 20, 2026, Modal shipped Sticky Sessions, a feature that makes exactly this guarantee on serverless infrastructure. In this article I’ll explain what Sticky Sessions are, how they work under the hood, and when they’re the right tool versus the alternatives.
What Sticky Sessions are
Sticky Sessions are a routing feature on Modal that pins every request in a session to the same container for the session’s lifetime. They’re built on top of Modal Servers, the low-latency HTTP serving layer Modal introduced earlier. The pitch is simple: you get autoscaling serverless compute and strong affinity between a client and a specific container — two properties that have historically been at odds with each other.
To use them, you decorate a Modal Server class with @modal.sessioned() and start sessions through the SDK or the HTTP API. Here’s the core pattern from Modal’s own documentation:
@app.server()
@modal.sessioned()
class Server:
@modal.enter()
def start(self):
subprocess.Popen(["python", "-m", "http.server", "8000"])
@app.local_entrypoint()
def main():
session = Server.sessions.start(idle_timeout=600)
headers = {"Modal-Authorization": f"Bearer {session.token}"}
print(requests.get(Server.get_url(), headers=headers).text)
The session.token is the key detail. Once a client has a session token, it sends that token on every request — either as a Modal-Authorization header or, for browsers, as a cookie — and Modal routes those requests to the same container every time. A session can also be explicitly terminated by calling Server.sessions.terminate(token).
Why best-effort affinity wasn’t enough
Modal has supported WebSockets for a while through Web Functions. But a WebSocket connection there is tied to a Function input, not a container. If the connection drops and the client reconnects, a new input is created — and that new input can land on a completely different container. For a voice agent mid-conversation, that means the model loses its dialog state and the user starts over. Not acceptable.
Modal Servers already offered a softer form of affinity before Sticky Sessions. Requests that shared a Modal-Affinity-Routing-Key header were routed to the same container on a best-effort basis. The problem with best-effort is baked into the name: the container could be scaled down or replaced at any moment, silently routing future requests to a different container. Best-effort is fine for caching a warm model in memory, but it’s not a guarantee you can build stateful logic on.
Before Sticky Sessions, the common workaround for stateful apps was max_containers=1. That forces every request onto a single container — which does give you stickiness, but by giving up scaling entirely. You get affinity by sacrificing the entire point of serverless. Sticky Sessions exist to close that gap: keep the affinity, keep the scaling.
How Sticky Sessions work under the hood
Sticky Sessions rest on the infrastructure Modal built for Modal Servers. At the center is an in-house stateless proxy that Modal calls fprs, which provides low-latency routing and load balancing using in-memory cached routing state reconciled from durable storage. Servers already gave Modal a way to route HTTP traffic to a container, manage container lifecycles, and scale the fleet on demand.
The sticky-session layer adds three capabilities that request-level routing didn’t provide. The first is fixed routing — every request in a session reaches the same container, full stop. The second is session lifecycle management — sessions can be created, tracked, and terminated explicitly rather than living only as an implicit side effect of a connection. The third is a session-aware scaling model, where the infrastructure knows which containers are pinned to active sessions and scales the fleet without evicting a live session out from under a user.
The practical effect is that Modal can autoscale the rest of the fleet while a session’s container stays put. A voice agent holding a conversation keeps its state in memory, while other sessions spin up and down independently. That’s the serverless dream — pay for what you use, scale with demand — but without losing continuity.
How browser authentication works
For web clients, Modal handles the token flow automatically, and the mechanics are worth understanding because they get security right. On the first visit, a browser authenticates via a query parameter: ?modal_session_token=.... The server responds with a 307 Temporary Redirect that strips the token out of the URL and sets a cookie named __Host-modal-session-token with the Secure, HttpOnly, and SameSite=Lax flags set. The browser follows the redirect automatically and is left holding the cookie, and every request after that first hop carries the token in the cookie — no query parameter or header needed again.
That exchange closes a common hole. Putting a session token in a URL means it leaks into access logs, browser history, and Referer headers, where it can be exfiltrated. By immediately swapping the query-parameter token for an HttpOnly cookie, Modal keeps the token out of JavaScript’s reach — which defends against XSS — and out of the URL, which defends against log leakage. If you’re building a non-browser client instead, the same token goes in the Modal-Authorization header, and you should treat it as a credential rather than a routing hint.
AI agent framework comparison: how session affinity works elsewhere
Sticky sessions are not a new idea. Load balancers have supported them for decades. What’s interesting is how rarely they exist on modern serverless platforms, where the whole abstraction is built around stateless, interchangeable requests. A quick comparison across the landscape makes Modal’s positioning clear.
| Platform | Session affinity model | Autoscaling with state | Native stateful sessions |
|---|---|---|---|
| Modal Sticky Sessions | Strong, token-based | Yes | Yes |
| Modal (best-effort key) | Best-effort | Yes, but can evict | No |
| Azure Container Apps | Sticky sessions config | Yes (replica affinity) | Partial |
| Traditional LB (Nginx/ALB) | Cookie-based stickiness | Manual | No |
| Standard FaaS (Lambda-style) | None | No | No |
Azure Container Apps has had a session-affinity setting for a while, and it’s the closest mainstream analog — route all requests from a client to the same replica. Traditional load balancers like Nginx or AWS ALB do the same with cookie-based stickiness. What’s different about Modal’s version is that it’s a first-class concept on serverless: you get the session semantics and the autoscaling, without manually managing a load balancer or pinning replicas yourself.
For AI agents specifically, this matters because a coding agent or voice agent keeps a large amount of context in memory — the conversation, the codebase index, the model’s KV cache. Stateless serverless forces you to serialize that state to external storage on every turn, which adds latency and complexity. Native sticky sessions let you keep it in the process where it’s fast.
Who should use Sticky Sessions
Sticky Sessions are the right tool when your workload has real per-session state that’s expensive to reconstruct. The clearest cases:
- Voice and chat agents that hold a conversation and need dialog state plus model context across turns.
- Streaming speech-to-text or transcription where a decoder holds state for an ongoing audio stream.
- Stateful web UIs like Gradio or Streamlit apps, where every request must reach the process holding the user’s state.
- Multiplayer or interactive games where a client must return to the same world state on reconnect.
- Coding agents that keep a codebase index or long context in memory rather than reloading it per turn.
The common thread is that reconstructing state from cold storage on every request is either too slow, too expensive, or both. If your request is genuinely stateless — a pure HTTP API that reads from a database and returns JSON — Sticky Sessions buy you nothing and you should skip them.
Who should NOT use Sticky Sessions
Just as important is knowing when not to reach for them. If your state already lives in external storage — a Postgres database, a Redis cache, an object store — then you don’t need process-level affinity at all, and adding sticky sessions just couples you to a specific container for no benefit. If your workload is embarrassingly parallel and stateless, stickiness only limits how evenly the load balancer can spread traffic. And if your session state can be cheaply rehydrated on every request, the complexity of managing session tokens isn’t worth it.
There’s also an operational caution. Sticky sessions can create hot spots: if one session pins a container that stays idle most of the time, you may pay for that container’s idle capacity. Modal’s idle_timeout parameter lets you bound this — a session that goes quiet for longer than the timeout can be reclaimed — but you need to tune it to your actual session lengths rather than leaving it at the default.
Limitations and caveats
A few honest caveats. First, sticky sessions solve routing, not durability. If the pinned container crashes, the session state dies with it. Sticky Sessions make it less likely you’ll lose state to a routine scale-down, but they are not a substitute for check-pointing or persisting critical state — for anything you can’t afford to lose, write it somewhere durable.
Second, session tokens are credentials. The token in the Modal-Authorization header or the __Host-modal-session-token cookie is what tells the proxy where to route — and more importantly, it’s what authorizes access to that session. Modal’s browser flow sets the cookie with Secure, HttpOnly, and SameSite=Lax flags, which is the right default, but if you’re building a client, treat the token as a secret and never log it or embed it in a URL that could leak.
Third, this is a new feature as of late October 2026, so the operational patterns — how to handle token expiry, how to balance session lifetime against idle cost, how to debug a “stuck” session — are still being worked out by early adopters. The primitives are clean; the folklore isn’t written yet.
The bottom line
Modal’s Sticky Sessions fill a real gap that’s been a quiet source of pain for anyone building stateful AI applications on serverless. Before this, you had to choose between the scaling of serverless and the continuity of a persistent process — max_containers=1 was the tell that the platform had no answer for the middle ground. Now the two properties coexist, and the API is small enough to adopt in an afternoon.
If you’re building voice agents, coding agents, or any real-time AI tool where state must survive across requests, Sticky Sessions are worth a serious look. The guarantee — same session, same container, for the whole lifetime — is exactly the guarantee those workloads have been missing.