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 in some language and know what a load balancer does. Later chapters cover where to store session state. This one covers how to recognize it.
Session state defined
HTTP treats each request on its own. Real applications still need to connect requests: a user logs in once, then adds items to a cart, then pays. Session state is the data a server keeps about one client's ongoing interaction so that later requests can build on earlier ones.
Typical examples:
- The identity of the logged-in user.
- The contents of an unsaved shopping cart.
- Progress through a multi-step form.
- A CSRF token (a random value that proves a form post came from your own page).
- The
stateandnoncevalues of an in-progress OAuth login. - A one-time "flash" message to show after a redirect.
What is not session state
Many things a service holds in memory look like session state but are not.
- Persistent business data. Orders, accounts and invoices belong in a database. They outlive any session and are shared across users and devices.
- Shared caches. A cached product catalog is the same for every client and can be rebuilt at any time.
- Configuration. Settings loaded at startup are the same on every instance.
- Request data. Headers, query strings and bodies arrive with each request. They need no storage.
A rough test is to ask three questions about a piece of data:
- Is it specific to one client's current interaction?
- Is it needed on a later request, and not already in that request or in the database?
- Would losing it break only that client's current flow, not other users?
If all three answers are yes, it is session state.
Where session state hides
Session state is easy to create by accident. Any variable that remembers something per client between requests counts. The most common form is a module-level dictionary:
from collections import defaultdict
class Instance:
"""One running copy of the service, with its own memory."""
def __init__(self, name: str):
self.name = name
self.carts = defaultdict(list) # session state, local to this process
def add_to_cart(self, client_id: str, item: str) -> list:
self.carts[client_id].append(item)
return self.carts[client_id]
a = Instance("A")
b = Instance("B")
print(a.add_to_cart("u1", "book")) # ['book']
print(b.add_to_cart("u1", "pen")) # ['pen'] (the book is missing)On one instance, this code works. Behind a load balancer, the second request may reach instance B, which has never seen this client. The cart seems to vanish. A restart or deploy of instance A would also destroy the cart. Because the state lives inside the process, the service is not stateless.
Identifier and data
A session has two parts, and keeping them apart makes later design choices clearer.
- The session identifier is a random value that names the session. The client sends it with each request, usually in a cookie.
- The session data is what the server associates with that identifier.
The next chapters compare the places to put the data. The identifier always travels with the client.
Classifying common data
| Data | Lifetime | Session state? | Better home |
|---|---|---|---|
| Logged-in user ID | Until logout or expiry | Yes | Session store or signed token |
| Anonymous cart | Hours to days | Yes | Session store |
| Cart of a logged-in user | Across devices and visits | No | Database keyed by user |
| User profile | Permanent | No | Database, loaded by user ID |
| Product catalog cache | Minutes | No | Shared cache |
| CSRF token | Per session or form | Yes | Session store or token |
Common errors
- Copying instead of referencing. Storing a full profile object in the session means it goes stale when the profile changes. Store the user ID and load the profile when you need it.
- Over-keeping. Large objects in a session slow every request and use up memory. Keep only what the next request needs.
- Mislabeling durable data. A cart that should survive logout is not session state. Losing it on session expiry is a bug.
- Storing secrets. Passwords and raw payment details do not belong in session data, especially if the data is later sent to the client.
Exercise
A service keeps a Python dictionary mapping each logged-in user ID to that user's profile, loaded at login, and reads it on every request. Is this session state? What could go wrong with two instances, and what would you change?
Show answer
Yes, it is per-client data kept in process memory between requests, so it is session state, even though it was loaded from the database. With two instances, only the one that handled the login has the entry, so requests sent to the other instance fail or force a new login. The copies also go stale when the profile changes. Keep only the user ID in the session, and load the profile from the database, or from a shared cache, on each request.