Stateless application servers
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite now runs on two servers behind a load balancer. Meena adds a phone to her cart, then earbuds, and her cart shows only one of them. No error is logged. Where did the other item go?
Your turn: where did the item go?
ShopLite runs two copies of the app behind a load balancer that sends requests in turn. Think before you read on:
- Meena adds a phone, then earbuds. Where is each item stored, and what does she see when she opens her cart?
- Where could the carts live so that any server can answer? Name two places.
- What else on a server might quietly hold data that the other servers cannot see?
Stateful vs stateless: where the cart lives
A stateless server keeps no user data in its own memory between requests. Everything a request needs comes with the request or from a store that every server can reach.
State is data that must survive from one request to the next, such as who is logged in or what is in the cart. The diagram shows two places it can live.
Stateful: [LB] --> [app-1: carts in memory] [app-2: carts in memory] (two different carts)Stateless: [LB] --> [app-1] [app-2] --> [shared store: carts] (one cart)A stateful server keeps state in its own memory, for example a Map field or an HTTP session. A stateless server keeps it somewhere every server can reach: a database, a shared cache such as Redis, or a signed token the client sends each time.
With one server, both work. With two servers behind a load balancer, the next request may land on the other server, which has never seen this user.
Simulation: carts lost when the balancer switches
A stateful server keeps user data, such as carts or sessions, in its own memory. A request that lands on a different server cannot see that data.
The load balancer sends requests to servers in turn. Meena adds a phone through app-1 and then earbuds through app-2, each into its own server's map.
Example 1 · Two stateful servers: one cart becomes two
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class StatefulServer { final String name; private final Map<String, List<String>> carts = new HashMap<>(); // state inside the server
StatefulServer(String name) { this.name = name; }
String addToCart(String user, String item) { carts.computeIfAbsent(user, u -> new ArrayList<>()).add(item); return name + ": added " + item; }
String showCart(String user) { return name + ": cart = " + carts.getOrDefault(user, List.of()); }}
public class LostCartDemo { public static void main(String[] args) { List<StatefulServer> servers = List.of(new StatefulServer("app-1"), new StatefulServer("app-2")); int next = 0;
// The load balancer sends each request to the next server in turn System.out.println(servers.get(next++ % 2).addToCart("meena", "Redmi Note 13 5G")); System.out.println(servers.get(next++ % 2).addToCart("meena", "boAt Airdopes 141")); System.out.println(servers.get(next++ % 2).showCart("meena")); System.out.println(servers.get(next++ % 2).showCart("meena")); }}app-1: added Redmi Note 13 5G app-2: added boAt Airdopes 141 app-1: cart = [Redmi Note 13 5G] app-2: cart = [boAt Airdopes 141]
What this code does
- Each
StatefulServerhas its owncartsmap. The round-robin balancer sends the two adds to different servers, so each holds half the cart. - The last two lines show the same user getting a different cart depending on which server answers. No exception is thrown; the data is simply split.
When she opens her cart she sees only one item, and which one depends on the server she reaches. Nothing crashed and no error was logged.
This is why per-server state is dangerous: it fails quietly, only under load balancing, often only in production.
Predict the output
Where did the item go?
Each server keeps its own cart map. Pick what the two servers print.
The balancer sends the first request to app-1 and the next one to app-2. What is printed?
The fix, part 1: a shared store
A shared store is a database or cache, such as MySQL or Redis, that every server reads and writes, so state no longer lives in any one server.
Move the carts out of the servers. In the example, one CartStore object passed to both servers plays the shared store.
Example 2 · The fix: both servers use one CartStore
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
// Stands in for Redis or a carts table: one store that every server usesclass CartStore { private final Map<String, List<String>> carts = new ConcurrentHashMap<>();
void add(String user, String item) { carts.computeIfAbsent(user, u -> new ArrayList<>()).add(item); }
List<String> get(String user) { return carts.getOrDefault(user, List.of()); }}
class StatelessServer { final String name; private final CartStore store; // no user data in the server object itself
StatelessServer(String name, CartStore store) { this.name = name; this.store = store; }
String addToCart(String user, String item) { store.add(user, item); return name + ": added " + item; }
String showCart(String user) { return name + ": cart = " + store.get(user); }}
public class SharedCartDemo { public static void main(String[] args) { CartStore store = new CartStore(); List<StatelessServer> servers = List.of(new StatelessServer("app-1", store), new StatelessServer("app-2", store)); int next = 0;
System.out.println(servers.get(next++ % 2).addToCart("meena", "Redmi Note 13 5G")); System.out.println(servers.get(next++ % 2).addToCart("meena", "boAt Airdopes 141")); System.out.println(servers.get(next++ % 2).showCart("meena")); System.out.println(servers.get(next++ % 2).showCart("meena")); }}app-1: added Redmi Note 13 5G app-2: added boAt Airdopes 141 app-1: cart = [Redmi Note 13 5G, boAt Airdopes 141] app-2: cart = [Redmi Note 13 5G, boAt Airdopes 141]
What this code does
- The servers now hold only a reference to the shared
CartStore, which stands in for Redis or a carts table. Whichever server answers, it reads the same cart. - The server classes have no user data of their own: that is what "stateless" means in practice.
In production the shared store is a carts table in MySQL or keys in Redis. Both servers now show the same cart, whichever one answers.
Order of execution
Move state out of the server
Tap the steps in the order a team would take them.
The fix, part 2: signed tokens
A signed token is a small piece of text that holds the user id and role plus a signature made with a secret every server has. Any server can check it without asking anyone.
Login state can travel with each request. The server signs the user id and role; any other server can verify the signature, and a forged token fails.
Example 3 · A signed token any server can verify
import java.nio.charset.StandardCharsets;import java.util.Base64;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
// A tiny signed token, the idea behind a JWT: data + a signature made with a shared secret.// Real apps use a JWT library (Section 17); this only shows why any server can check it.class TokenSigner { private final byte[] secret;
TokenSigner(String secret) { this.secret = secret.getBytes(StandardCharsets.UTF_8); }
private String sign(String data) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret, "HmacSHA256")); byte[] sig = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getUrlEncoder().withoutPadding().encodeToString(sig); }
String issue(String data) throws Exception { return data + "." + sign(data); }
String verify(String token) throws Exception { int dot = token.lastIndexOf('.'); String data = token.substring(0, dot); return sign(data).equals(token.substring(dot + 1)) ? data : null; }}
public class SignedTokenDemo { public static void main(String[] args) throws Exception { String secret = "shared-secret-from-config"; TokenSigner loginServer = new TokenSigner(secret); TokenSigner otherServer = new TokenSigner(secret);
String token = loginServer.issue("user=7;role=CUSTOMER"); System.out.println("app-1 issued: " + token.substring(0, token.indexOf('.')) + ".<signature>"); System.out.println("app-2 verified: " + otherServer.verify(token));
String forged = token.replace("user=7", "user=1"); System.out.println("forged token: " + otherServer.verify(forged)); }}app-1 issued: user=7;role=CUSTOMER.<signature> app-2 verified: user=7;role=CUSTOMER forged token: null
What this code does
- app-1 signs
user=7;role=CUSTOMERwith HMAC-SHA256 using the shared secret. app-2 recomputes the signature with the same secret and accepts the token without any shared session store. - Changing
user=7touser=1breaks the signature, so the forged token is rejected. Real apps use a JWT library (Section 17); this shows only the core idea.
This is the idea behind the JWTs ShopLite uses from Section 17. The secret must stay private on every server, because anyone who has it can sign tokens.
Predict the output
Can app-2 trust the token?
Both servers have the same secret. Pick what is printed.
app-1 issues a token. app-2 verifies it, and then a forged copy. What is printed?
Why stateless servers can be added, removed and restarted
When no server holds unique data, all servers are interchangeable. The example adds a third server and restarts one while two customers keep shopping.
Example 4 · Adding, restarting and removing servers without losing data
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
class Server { final String name; private final Map<String, Integer> cartCounts;
Server(String name, Map<String, Integer> sharedStore) { this.name = name; this.cartCounts = sharedStore; }
String add(String user) { int n = cartCounts.merge(user, 1, Integer::sum); return name + " -> " + user + " has " + n + " item(s)"; }}
public class ScaleAndRestartDemo { static Map<String, Integer> store = new ConcurrentHashMap<>(); static List<Server> pool = new ArrayList<>(); static int next = 0;
static void request(String user) { System.out.println(" " + pool.get(next++ % pool.size()).add(user)); }
public static void main(String[] args) { pool.add(new Server("app-1", store)); pool.add(new Server("app-2", store)); System.out.println("2 servers:"); request("meena"); request("ravi");
pool.add(new Server("app-3", store)); // sale starts: add a server System.out.println("Scaled out to 3 servers:"); request("meena"); request("ravi"); request("meena");
pool.set(0, new Server("app-1 (restarted)", store)); // deploy a new version of app-1 pool.remove(2); // sale over: remove app-3 System.out.println("app-1 restarted, app-3 removed:"); next = 0; request("meena"); request("ravi"); }}2 servers: app-1 -> meena has 1 item(s) app-2 -> ravi has 1 item(s) Scaled out to 3 servers: app-3 -> meena has 2 item(s) app-1 -> ravi has 2 item(s) app-2 -> meena has 3 item(s) app-1 restarted, app-3 removed: app-1 (restarted) -> meena has 4 item(s) app-2 -> ravi has 3 item(s)
What this code does
- A third server joins mid-sale and immediately sees the counts made by the other two, because all of them use the same store.
- Restarting app-1 and removing app-3 loses nothing: Meena's count continues at 4. With per-server state, both actions would have lost carts.
Add three servers for a sale and remove them afterwards; deploy a new version by restarting servers one by one; let a crashed server die. Customers keep their carts and logins because none of it lived on the server.
This is the condition for horizontal scaling and for the load balancer stage from the growth lesson. A team should be able to say "any request can go to any server" and mean it.
What still has state, and how to handle it
A job lock lets only one server run a scheduled job at a time: the first server to take the lock runs the job, and the others skip it.
Some state hides where it is easy to forget. The example runs an 11 PM job on three servers, first without and then with a lock.
Example 5 · A scheduled job on three servers, with and without a lock
import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
public class JobLockDemo { // Stands in for a locks table or a Redis key shared by all servers static Map<String, String> locks = new ConcurrentHashMap<>(); static int emailsSent = 0;
static void nightlyJobWithoutLock(String server) { emailsSent++; System.out.println(" " + server + ": sent daily sales email"); }
static void nightlyJobWithLock(String server, String date) { String key = "daily-sales-email:" + date; if (locks.putIfAbsent(key, server) == null) { // only the first server wins emailsSent++; System.out.println(" " + server + ": got the lock, sent daily sales email"); } else { System.out.println(" " + server + ": skipped, " + locks.get(key) + " already ran it"); } }
public static void main(String[] args) { List<String> servers = List.of("app-1", "app-2", "app-3");
System.out.println("Every server runs the 11 PM job:"); for (String s : servers) { nightlyJobWithoutLock(s); } System.out.println("Emails sent: " + emailsSent);
emailsSent = 0; System.out.println("With a shared lock:"); for (String s : servers) { nightlyJobWithLock(s, "2026-10-16"); } System.out.println("Emails sent: " + emailsSent); }}Every server runs the 11 PM job: app-1: sent daily sales email app-2: sent daily sales email app-3: sent daily sales email Emails sent: 3 With a shared lock: app-1: got the lock, sent daily sales email app-2: skipped, app-1 already ran it app-3: skipped, app-1 already ran it Emails sent: 1
What this code does
- Without coordination every server runs the 11 PM job, so the admin gets three identical emails.
putIfAbsenton a shared map lets only the first server take the lock for that date. A locks table or Redis key does the same across real servers.
Four places to check:
- Uploaded files saved to the server's disk vanish with the server: store them in object storage (such as Amazon S3) and keep only the key in the database.
- Local caches (a
Mapof products in memory) differ per server: fine for data that may be a little old; use a shared cache when all servers must agree. - Scheduled jobs (
@Scheduledat 11 PM) run on every server: take a shared lock first, for example with a locks table or a library such as ShedLock. - WebSocket connections are tied to one server: keep messages in a shared store or broker so any server can deliver them.
Find the bug
Find the hidden state
Each snippet works on one server and breaks on three. Tap the wrong line.
Login sessions.
Round 1 of 3Next step
Check your understanding
10 quick questions