Sub topic 2
What counts as session state
This chapter assumes you know the basics of HTTP requests, responses, headers and cookies. It also assumes you have built a web service or API in some language and know roughly what a load balancer does. The previous chapter defined a stateless service as one where any instance can handle any request. This chapter asks which data stands in the way of that, so you can decide what to move out of your instances and what to leave alone.
What a session is
HTTP is stateless at the protocol level. Each request stands alone, and the server has no built-in memory of earlier requests from the same client. Applications add that memory themselves by grouping a series of requests from one client into a session.
Session state is the data your application keeps between requests so that it can treat a series of requests as one continuing interaction. The server needs it to answer the next request correctly, and it describes the interaction, not the wider world.
A request that arrives without its session state cannot be handled as the client expects. The user would look logged out, the cart would be empty, or the checkout step would have lost its place.
A working test
Three questions help you decide whether a piece of data is session state.
- Is it scoped to one client interaction? Session state belongs to one browser, device or login, not to the whole system.
- Is it needed on later requests? If the server uses it only while handling the current request, it is request-scoped data, not session state.
- Can it be discarded when the interaction ends? Session state is usually disposable. If losing the data would be a business loss, it belongs in a database.
Data that passes all three is session state. Data that fails the third question is usually durable application data that happens to be associated with a user.
Typical session state
| Data | Why it is session state | Typical lifetime |
|---|---|---|
| Authenticated user ID | Lets later requests know who is calling | Minutes to hours, often with sliding expiry |
| Roles or permissions, cached at login | Avoids a lookup on each request | Same as the login |
| Anonymous shopping cart | Tied to a browser before any account exists | Hours to days |
| Multi-step form or wizard progress | Holds partial answers between pages | Minutes |
| CSRF token | Must match between the page load and the later form post | Same as the session |
| One-time flash message, such as "Saved." | Set on one request and shown on the next | One request |
| OAuth `state` and PKCE verifier | Links the redirect back to the request that began it | Minutes |
| Locale or UI preferences chosen this visit | Affects later responses but is not worth storing permanently | Session or longer |
Authentication data is the most common case, but it is not the only one. Applications often start with "the session holds the user ID" and later add the cart, the wizard step and a CSRF token. The session then grows into a general-purpose bag of data, which matters when you choose where to keep it, as later chapters show.
What is not session state
Several things look like session state but follow different rules.
Durable business data
An order that a user has placed, a saved profile, a document or a payment record is not session state. It must survive logouts, deploys and outages, and other users or background jobs may need it. It belongs in a database, and the session at most holds a reference such as an order ID.
A shopping cart is a borderline case. An anonymous cart is reasonably session state. A cart that must follow a user across devices, or that marketing wants to analyze, is durable data keyed by user ID. The decision depends on your requirements, not on the data's shape.
Shared caches
A cache of product details or rendered pages is not tied to one user. It is shared across requests and can be rebuilt from its source. It can also live in each instance's memory without breaking correctness, although it may waste memory or serve stale data. Caches are a performance concern. Session state is a correctness concern.
Request-scoped data
Parsed headers, the request body, a database transaction and a trace ID live only while the server handles one request. They are state in the general sense, but nobody needs them afterward, so they cause no scaling problem.
Configuration
Feature flags, connection strings and limits are the same for every user and are read at startup or refreshed from a config service. They are not per-user and do not change as a result of user actions.
Session state versus application state
Application state is data that outlives any single interaction and matters to the business. Session state is data about the interaction itself. The table below shows how they differ.
| Property | Session state | Application state |
|---|---|---|
| Scope | One client interaction | The whole system or one user's account |
| Loss impact | User signs in again or restarts a step | Data loss, support tickets, possible legal exposure |
| Typical store | Cache or key-value store with TTL | Relational or document database |
| Expiry | Expected and often required | Rare, and driven by policy |
| Read and write rate | Usually every request | Only when the feature needs it |
The "loss impact" row is the most useful for design. If losing the data would only annoy someone, session storage is fine. If it would cost money or trust, store it durably.
How session state hides inside instances
The common failure is not a deliberate decision to store sessions on one server. It is a harmless-looking in-memory structure that holds session data without anyone noticing. The following example simulates two instances behind a load balancer. Each instance keeps sessions in a local dictionary.
class Instance:
def __init__(self, name: str):
self.name = name
self.sessions = {} # lives in this process only
def login(self, session_id: str, user_id: str) -> str:
self.sessions[session_id] = {"user_id": user_id, "cart": []}
return f"{self.name}: 200 logged in as {user_id}"
def add_to_cart(self, session_id: str, item: str) -> str:
session = self.sessions.get(session_id)
if session is None:
return f"{self.name}: 401 not logged in"
session["cart"].append(item)
return f"{self.name}: 200 cart={session['cart']}"
a = Instance("app-1")
b = Instance("app-2")
print(a.login("abc123", "42"))
print(a.add_to_cart("abc123", "book")) # same instance: works
print(b.add_to_cart("abc123", "pen")) # other instance: session unknownRunning it prints:
app-1: 200 logged in as 42
app-1: 200 cart=['book']
app-2: 401 not logged inThe code has no bug in the usual sense. With one instance it works every time. It fails only when a second request lands on a different instance, which happens only after you scale out, restart an instance, or deploy a new version. That is why the problem often appears in production first.
Look for these patterns when you review a service:
- Module-level dictionaries or lists keyed by user or session ID.
- Framework features that default to in-process session storage, such as a "memory" session backend meant for development.
- Objects held in a singleton, for example a per-user rate limiter or a wizard object stored in a map.
- Files written to the instance's local disk and read back on a later request, such as a half-finished upload.
- Websocket or long-polling connections that carry per-user state in the connection handler.
Edge cases worth knowing
Anonymous sessions
Sessions do not require a login. A visitor with an anonymous cart already has session state, usually identified by a cookie set on the first visit. When that visitor logs in, you typically merge the anonymous session into the authenticated one. Plan for that merge, because it decides whether the session ID changes. Chapter 8 covers why changing the ID at login matters.
Size and sensitivity
Session state tends to get big because adding one more field is easy. Size matters because it decides which storage options remain viable. A cookie holds around 4 KB per browser limits, and everything in it is sent on every request. A server-side store handles larger data but pays for it in memory and network traffic.
Sensitivity matters too. Data you would not want a user to read or edit, such as an internal risk score or an "is_admin" flag taken from another system, needs different handling from a display preference. Keep this in mind when you reach client-side tokens.
Derived data
Some session fields can be recomputed from other sources. A cached copy of the user's roles is derived from the permissions database. You can drop it and reload it on demand. If a field can always be rebuilt, losing it costs a lookup, not the session. Marking such fields as derived makes the store failure modes in a later chapter easier to reason about.
Long-running interactions
A checkout that spans several screens, or an upload that takes ten minutes, stretches the session across a long time. Such flows often need a longer lifetime than the login does. Decide whether the flow's state lives in the session or in a durable "draft" record keyed by an ID. A draft survives logouts and restarts, and the session only points to it.
Concurrent requests
A single browser can send several requests at once, such as multiple tabs or parallel API calls. If two requests read the session, change different fields and write back the whole object, the second write can erase the first. Be aware of this when the session holds more than a user ID. Writing only the fields you change, or using atomic operations in the store, avoids it.
Common errors
- Treating the session as a database. If data must survive a store restart, it is not session state. Keep orders, payments and profile edits in durable storage.
- Storing whole objects. Putting a full user record in the session means it goes stale when the record changes elsewhere. Store the ID and load the rest when needed.
- Forgetting about expiry. Session state without a lifetime accumulates forever and leaves stale logins valid.
- Assuming a single instance. Code that works in local development with one process can still hide in-memory session state.
- Mixing session and cache. A shared cache can be rebuilt. Session state cannot always be. Keep them separate so each can have its own failure behavior.
A decision flow
The diagram below combines the three questions from earlier with the exclusions in this chapter. It tells you whether a piece of data needs a session-state strategy or something else.
The last branch matters in practice. Even when the data is durable, the session often still holds the ID that points to it, so you keep a small session and a durable record.
Summary
Session state is per-client data that your server needs across requests and can afford to lose. Authentication data, anonymous carts, wizard progress and CSRF tokens all qualify. Orders, profiles, shared caches, configuration and request-scoped data do not. Instances often hold session data by accident, in module-level dictionaries, singletons or local files, and the problem shows up only after the second instance starts. The next chapters cover why statelessness helps scaling and which places can hold this data.
Exercise
A service stores these items in memory on each instance: (1) the logged-in user's ID, (2) a cached list of product categories loaded from the database every hour, (3) answers a user has entered on page 2 of a 4-page application form, (4) completed orders awaiting export. Classify each as session state, shared cache, or durable application data, and say which ones block adding a second instance.
Show answer
(1) Session state. (2) Shared cache. It can be rebuilt, so each instance may keep its own copy without breaking correctness. (3) Session state, because it is per-user, needed on later requests and acceptable to lose, although a long form may be better kept as a durable draft. (4) Durable application data, because losing a completed order is a business loss. Items 1 and 3 block a second instance because a request landing on another instance would not find them, and item 4 blocks it because the data would be lost on restart and invisible to other instances. Item 2 does not block anything.
Exercise
The two-instance example printed "app-2: 401 not logged in". Without changing where sessions are stored, name two situations other than adding a new instance in which the same failure can occur in production.
Show answer
A restart or crash of the instance that holds the session empties its in-memory dictionary, so the user's next request fails even on a single instance. A rolling deploy replaces instances with new processes, and the new ones start with empty session dictionaries. A load balancer that moves a client to another healthy instance after a health check failure also causes it.