What you'll learn: By the end of this lesson you will be able to say what makes a service stateless, name the three places a request's state can live (instance memory, a shared store, the client), explain what session affinity buys and what it hides, and choose a design for a cart. A Spring Boot lab starts two real instances and shows each design losing or keeping a cart when requests alternate and when an instance is replaced.
A waiter who keeps your order in her head serves you well until her shift ends. The next waiter has to ask again, and if you wave at a different waiter in the meantime, she has no idea what you ordered. A paper slip fixes this: the order is written down where any waiter can read it. Stateless services are the paper slip.
Scaling basics says that adding instances behind a load balancer only works if any instance can answer any request. This lesson is about what that condition means and the three ways to meet it.
Verified on 2026-12-01 against the Twelve-Factor App, Spring Boot, Spring Session and Spring Security documentation, the Kubernetes Service documentation, the AWS Application Load Balancer documentation, RFC 6265 and RFC 2104. The lab ran on Spring Boot 4.1.2 with the Java 25 language level; its numbers and output come from that run.
The core idea
A service is stateless when any instance can serve any request, because everything the request needs either arrives with it or sits somewhere every instance can reach. The Twelve-Factor App puts it this way: processes "are stateless and share-nothing", and "any data that needs to persist must be stored in a stateful backing service, typically a database". Memory is allowed only as "a brief, single-transaction cache". State does not disappear; it moves out of the instance.
The payoff is practical. A stateless instance can be added, removed, restarted or replaced at any moment without a user noticing, and the balancer can send each request wherever it likes. A stateful instance is a place users are attached to.
Three illustrations run through the lesson:
- Minimal example: two instances with a cart in each one's memory (lab scenario 1).
- Realistic example: ShopStream's cart at the stage where it gets several app servers.
- Failure example: a "fixed" design that still loses carts when an instance is replaced (lab scenario 2).
Where state hides
State is easy to leave behind in an instance without noticing. Common places: the HttpSession, a map of "recent items" in a singleton, a file written to local disk, a counter that implements a rate limit, a timer that fires a reminder, an open WebSocket. The test is simple: if this instance vanished now, would a user notice, and would any other instance know what to do? If the answer is yes to the first and no to the second, the state lives in the wrong place.
The three places state can live
Figure 1. Where the cart can sit. How to read this: design 1 keeps it inside each instance (a session), design 2 keeps it in a store all instances reach, design 3 keeps it in the browser's cookie so no server holds it. Only design 1 ties the user to an instance.
| 1. Instance memory | 2. Shared store | 3. Client-held, signed | |
|---|---|---|---|
| What the browser sends | A session id | A cart id | The cart itself plus a signature |
| Who holds the truth | One instance | The store | The browser |
| Any instance can serve | No | Yes | Yes |
| Instance replaced | Its sessions are lost | Nothing lost | Nothing lost |
| Extra cost per request | None | A network call | Cookie size, a signature check |
| Revoke or change from the server | Yes (delete the session) | Yes (delete the entry) | Hard: the server holds nothing |
Session affinity: a cache, not a guarantee
If sessions live in memory, one fix is to send each user to the same instance every time. That is session affinity or sticky sessions. AWS describes it for Application Load Balancers as binding a user's session to a specific target so all requests in the session go there; the balancer sets a cookie (AWSALB) that encodes the chosen target, and requests carrying it bypass the routing algorithm. Kubernetes offers a cruder form: setting a Service's sessionAffinity to ClientIP sends connections from one client IP to the same Pod. The default is None, and the stickiness window defaults to 10,800 seconds (3 hours).
Affinity does not make a service stateless. The AWS page says if the cookie refers to a target that was deregistered or is unhealthy, the balancer picks a new target. The state on the old one is gone either way. It also warns that when the number of targets grows considerably, load can distribute unequally because of stickiness. The Twelve-Factor App is blunt: "Sticky sessions are a violation of twelve-factor and should never be used or relied upon."
The useful stance is to treat affinity as a performance hint (warm local caches, fewer cache misses) that the system must not depend on for correctness.
Figure 2. What the lab shows in scenario 1. How to read this: each instance only recognises session ids it issued, so an unknown id gets a new session. The browser's single cookie is overwritten each time, and no request sees the earlier items.
Build it
The lab is examples/spring-labs/labs/stateless-services (Spring Boot 4.1.2). It is a model, so here is what it is and is not.
- What it is. One cart service started as two separate Spring application contexts in one JVM, each with its own embedded Tomcat on its own loopback port. A browser class with a cookie jar sends requests through a two-line balancer (round robin, or always the same instance). "Replacing" an instance closes its context and starts a new one.
- What it is not. There is no real load balancer, no network between instances, no Docker and no Redis. The "shared store" is an in-memory map in the test JVM, with predictable counter ids to keep output stable; real ids must be unguessable. Nothing here shows what an Application Load Balancer or a Kubernetes Service does; those claims come from their documentation.
The controller is the same in all three designs and only the CartStore differs. Design 1 stores the cart in the session:
public void write(HttpServletRequest request, HttpServletResponse response, List<String> items) {
request.getSession(true).setAttribute("cart", new ArrayList<>(items));
}
Design 3 signs the cart with HMAC-SHA256 and puts the result in a cookie:
byte[] payload = String.join(",", items).getBytes(StandardCharsets.UTF_8);
String token = B64.encodeToString(payload) + "." + B64.encodeToString(sign(payload));
response.addHeader("Set-Cookie", "cart=" + token + "; Path=/; HttpOnly; SameSite=Lax");
RFC 2104 describes HMAC as a mechanism for message authentication using cryptographic hash functions with a secret shared key. The lab's key is a placeholder, not a secret; a real service reads its key from a secret store.
Expected output, captured from a real run (Spring Boot 4.1.2, two instances A and B on loopback ports, in-memory store):
1. Cart in the HttpSession, round-robin routing across A and B
POST /cart/items?item=milk -> 200 {"instance":"A","items":["milk"]}
POST /cart/items?item=bread -> 200 {"instance":"B","items":["bread"]}
POST /cart/items?item=eggs -> 200 {"instance":"A","items":["eggs"]}
GET /cart -> 200 {"instance":"B","items":[]}
sessions created: A=2 B=1
2. Cart in the HttpSession, sticky routing (this browser always goes to A)
POST /cart/items?item=milk -> 200 {"instance":"A","items":["milk"]}
POST /cart/items?item=bread -> 200 {"instance":"A","items":["milk","bread"]}
POST /cart/items?item=eggs -> 200 {"instance":"A","items":["milk","bread","eggs"]}
GET /cart -> 200 {"instance":"A","items":["milk","bread","eggs"]}
-- instance A is replaced by a fresh process (a deploy, a crash, a scale-in) --
GET /cart -> 200 {"instance":"A","items":[]}
POST /cart/items?item=rice -> 200 {"instance":"A","items":["rice"]}
sessions created by the new A: 1
3. Cart in a shared store (an in-memory map standing in for Redis), round robin
POST /cart/items?item=milk -> 200 {"instance":"A","items":["milk"]}
POST /cart/items?item=bread -> 200 {"instance":"B","items":["milk","bread"]}
POST /cart/items?item=eggs -> 200 {"instance":"A","items":["milk","bread","eggs"]}
GET /cart -> 200 {"instance":"B","items":["milk","bread","eggs"]}
the browser holds: cart_id=c1
-- instance A is replaced by a fresh process --
GET /cart -> 200 {"instance":"A","items":["milk","bread","eggs"]}
store calls so far: 4 reads, 3 writes
4. Cart in a signed cookie, round robin, no server-side cart at all
POST /cart/items?item=milk -> 200 {"instance":"A","items":["milk"]}
cookie after request 1 is 50 characters
POST /cart/items?item=bread -> 200 {"instance":"B","items":["milk","bread"]}
POST /cart/items?item=eggs -> 200 {"instance":"A","items":["milk","bread","eggs"]}
cookie after request 3 is 64 characters
anyone holding the cookie can decode its payload: milk,bread,eggs
GET /cart -> 200 {"instance":"B","items":["milk","bread","eggs"]}
-- instance A is replaced by a fresh process --
GET /cart -> 200 {"instance":"A","items":["milk","bread","eggs"]}
-- the browser sends back the copy of the cookie saved after request 1 --
GET /cart -> 200 {"instance":"B","items":["milk"]}
-- the payload is edited to add saffron, the old signature is kept --
GET /cart -> 400 {"instance":"A","error":"cart cookie rejected"}
How to read it:
- Scenario 1 (minimal example). Round robin with in-memory sessions loses the cart on every request: the final view on B shows
[], and the instances created three sessions between them for one shopper. Same code, same shopper; only the routing changed. - Scenario 2 (failure example). Sticky routing fixes the symptom (the cart is whole at the fourth request). Replacing instance A empties it. In this lab, with Spring Boot's embedded Tomcat at default settings, a fresh process starts with no sessions.
- Scenario 3. With the cart in a shared store any instance serves any request, and the replacement is invisible. The price is visible too: four reads and three writes for five requests, each a network call in a real deployment.
- Scenario 4. The signed cookie also survives the replacement and needs no store, but note three things. The payload is readable (signed, not encrypted). A saved old cookie is still accepted: the server cannot tell it is stale (
["milk"]comes back), because it holds nothing to compare with. And editing the payload while keeping the old signature is rejected with 400.
Run it from examples/spring-labs: ./gradlew :labs:stateless-services:test. The tests assert each claim and compare the report with golden/stateless-services.txt.
Choosing: where should this state live?
the request?"} -->|no| M["Request-local memory"] Q1 -->|yes| Q2{"Small, harmless to read,
fine if it cannot be revoked?"} Q2 -->|yes| T["Signed client token"] Q2 -->|no| S["Shared store with an expiry"]
Figure 3. A decision for each piece of state. How to read this: the further down, the more infrastructure you run. A signed token costs no store but gives up revocation and secrecy; a shared store gives both back and adds a dependency.
A signed cookie is the pattern behind many tokens; JWT structure and pitfalls covers its failure modes. Two limits come straight from the sources. RFC 6265 says user agents should support at least 4096 bytes per cookie, so a cart that grows will not fit, and that cookies "by default" give no confidentiality or integrity against network attackers, so use HTTPS. In Spring Security, SessionCreationPolicy.STATELESS stops the framework from creating an HttpSession to persist authentication; it re-authenticates on each request, as HTTP Basic does. For a shared store, Spring Session replaces the HttpSession and keeps the data in an external store; Spring Boot auto-configures Redis and JDBC for servlet applications, with spring.session.timeout setting expiry. The lab used neither.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| In-memory session, no affinity | Simplest code | Breaks with more than one instance | You run a single instance and always will |
| In-memory session with affinity | Works behind a balancer, warm caches | Lost on replacement, uneven load, scaling out does not rebalance | Instances are replaced often (deploys, autoscaling) |
| Shared store | Any instance serves any request, server can revoke | A dependency on every request, new failure mode | The store is slower than the work it saves |
| Signed client token | No server state | Size limits, no revocation, readable payload | The data is secret or must change from the server |
In practice: the ShopStream cart gets a second app server
This is a realistic scenario, not a case history.
This is an educational scenario on ShopStream, the course's grocery marketplace. Numbers are the shared illustrative ones.
The situation
At Stage 2 the browsing load is about 2,300 requests per second at peak (illustrative: 2,000,000 daily users times 20 page views, peak five times average). One app server cannot carry it, so the team adds a second and a balancer. Shoppers report carts that empty or show other items after a deploy.
Starting architecture
The cart lives in each app server's HttpSession. The balancer routes round robin, as in lab scenario 1.
Options considered
| Option | Behaviour | Cost | Risk |
|---|---|---|---|
| A. Turn on sticky routing | Cart stays on one server | One setting | Deploys empty carts (lab scenario 2); uneven load |
| B. Cart in a shared store with an expiry | Any server serves any request | A store to run and monitor | Store outage affects every request |
| C. Signed cookie | No store | Cookie size limits; carts cannot be revoked | Large carts do not fit |
The decision
Option B, because carts are changed from the server (a coupon removed, an out-of-stock item dropped) and can grow. Sticky routing stays off. Each request reads the cart by id and writes it back; the session holds nothing else.
Figure 4. Architecture after this change. How to read this: both app servers are interchangeable and hold no cart. The new box, the cart store, is also the new dependency: it is the one thing every cart request now waits on.
Rollout and verification
Ship the store-backed cart behind a flag, serving both for a day by reading the old session if no store entry exists. Test with the lab's method: two instances, alternating requests, then replace one. Evidence: cart-empty reports after deploys (expected to fall to zero), store latency, and the ratio of requests that touch the cart. At the illustrative peak above, each request that touches the cart is one store read.
The 2 a.m. failure
The store slows down and every cart request waits on it, so the app servers fill with threads blocked on the store. Alert: p99 latency on all routes. First checks: store latency and connection counts, then whether pages that need no cart are also slow. Mitigation: shorter store timeouts, serve the page without the cart and say it is unavailable, and fail readiness only if the store is truly required (see health checks). Follow-up: add a cart-free path for browsing and test it as an experiment (see graceful degradation).
Architect's notes
- Ask "what if this instance vanished now?" of every field in memory.
- Treat affinity as an optimisation. Correctness must not depend on it.
- Name the new dependency. A shared store makes the cart a reason for the whole service to be slow or down.
- Keep what you put in a cookie small, signed and over HTTPS.
Common mistakes
- Using sticky sessions to avoid designing state. It works until the first deploy.
- Putting a large or secret value in a signed cookie. Signed is not encrypted.
- Predictable ids in a shared store. Lab ids are counters only for stable output.
- Forgetting other state: local files, in-memory counters and timers.
- No expiry on shared state. Abandoned carts accumulate.
Key takeaways
- Stateless means any instance can serve any request; the state moves, it does not disappear.
- State can live in instance memory, a shared store or the client; only instance memory ties users to an instance.
- Session affinity is a performance hint; replacement and failure still lose in-memory state.
- A signed client token needs no store but cannot be revoked and its payload is readable.
- A shared store gives revocation and size, and adds a dependency to every request.
- Test statelessness by alternating requests across instances and replacing one.
Practice exercises
Exercise 1 (30 min). List the state in a service you know that lives in an instance. For each item, say which of the three designs would hold it.
Exercise 2 (45 min). In the lab, add an item removal endpoint and predict what each scenario returns before running it.
Exercise 3 (30 min). Decide what should happen to a signed cart cookie when a coupon expires. How would the server detect that it is stale?
Related reading
- Scaling Basics: why more instances need stateless ones.
- Load Balancing: how requests reach an instance.
- Auto Scaling: instances come and go.
- Distributed Caches: Redis and Memcached: a shared store in depth.
- JWT Structure and Pitfalls: the signed token pattern.