Stateless vs stateful

You just logged in, so why does the next page throw you out? See where the session lives once there are two servers, then try four fixes: memory, sticky sessions, Redis and a signed token.

Level: BasicWatch: 13 steps · ~1 minuteSwitch servers off, log outRecall: 3 questions · 8 cardsCompare 4 places for the loginTypeScript · nginx · redis-cli

What you'll take away

  • Explain why a session in one server's memory logs you out once a second server joins
  • Know why sticky sessions only buy time: when the server dies, its sessions go too
  • Move sessions into Redis or a signed token, so any server can answer anyone
  • Pick Redis or a JWT: one trip per request, or a token you can't take back early

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
Session in memoryround robin
you · logged out
load balancer · round robin
server A · memory
server B · not yet
log in → …
Step 1 / 13 · step by step
0OK 200
0Logged out for no reason
0Trips to Redis
–Old one after log out

The picture: you on the plaza, a load balancer, servers A and B, and Redis down the street. Your login is drawn where it lives: a tile on a server's roof (its memory), on Redis's roof, or a gold token beside your phone. The moving light is a request. All the numbers come from a model on this page, not from real servers.

Step 4 · Every option at once, on one clock

Compare them all: Stateless vs stateful

The same story in every tile: log in, two pages, A dies, two more pages, log out, then someone tries the old cookie / token. Watch which one logs you out, which one asks Redis, and which one lets the old one through.

0.0 s (simulated)
Session in memoryround robindropped 0 · Redis 0 · old one –

Use it when One server, or sessions you can afford to lose

Skip it when More than one server: the next request lands on one that has never seen you

A model: two servers, round robin, one user. The numbers count this one story. Press any tile to see it large above, with when it fits.

Where does your login live?

WayEvery requestA server diesLog out now
memoryHas to come back to the same serverLogged outYes, if it lands on the same server
stickyThe load balancer sends it back for youEveryone pinned to it is logged outYes
RedisOne trip to RedisNobody noticesYes: delete the key
token (JWT)Check the signature, ask nobodyNobody noticesNo, not until it expires

Stateless doesn't mean no state

The state is still there. It just moves out of the server's memory, into a shared store or into a token the browser carries. Then every server looks the same, and you can add, remove or switch off any of them without logging anyone out.

A cookie is how something travels; a session id or a token is what travels. A session cookie holds only an id, and the data stays on the server. A JWT carries the data itself, with a signature, and can travel in a cookie or in the Authorization header.

So which one?

A normal web app that must log people out at once: sessions in Redis, simple and plain. Several services that must trust the same identity: short-lived tokens with a refresh token. Sticky sessions are a stopgap while you can't move sessions out of memory yet.

In real code

memory.ts
// Sessions kept in each server's memory, two servers behind a load balancer: the login that vanishes.
// Run: node memory.ts   (Node 23.6+; on Node 22: node --experimental-strip-types memory.ts)
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";

/** One app server: POST /login sets a cookie, GET /me answers only if THIS process remembers the session. */
async function appServer(name: string): Promise<{ url: string; server: Server }> {
  const sessions = new Map<string, string>(); // lives in this process, and dies with it
  const server = createServer((req, res) => {
    const sid = /sid=([\w-]+)/.exec(req.headers.cookie ?? "")?.[1];
    if (req.method === "POST" && req.url === "/login") {
      const id = randomUUID();
      sessions.set(id, "mai");
      return res.writeHead(200, { "Set-Cookie": `sid=${id}; HttpOnly; Secure; SameSite=Lax` }).end(name);
    }
    if (req.url === "/me" && sid && sessions.has(sid)) return res.writeHead(200).end(name);
    res.writeHead(401).end(name);
  });
  await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
  return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, server };
}

let a = await appServer("A");
const b = await appServer("B");
const call = async (s: { url: string }, path: string, cookie = "") => {
  const r = await fetch(s.url + path, { method: path === "/login" ? "POST" : "GET", headers: { cookie } });
  return { status: r.status, by: await r.text(), cookie: (r.headers.get("set-cookie") ?? "").split(";")[0] };
};

// Round robin: login on A, the next request lands on B.
const login = await call(a, "/login");
const rr = [await call(b, "/me", login.cookie), await call(a, "/me", login.cookie)];
// Sticky: always A … until A restarts with empty memory.
const sticky = [await call(a, "/me", login.cookie)];
a.server.close();
a = await appServer("A");
sticky.push(await call(a, "/me", login.cookie));

a.server.close();
b.server.close();
assert.deepEqual(rr.map((r) => `${r.by}${r.status}`), ["B401", "A200"]);
assert.deepEqual(sticky.map((r) => `${r.by}${r.status}`), ["A200", "A401"]);
console.log(`round robin: login on A → B 401 → A 200 · sticky: A 200 → A restarts → A 401`);
Run: node memory.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: round robin: login on A → B 401 → A 200 · sticky: A 200 → A restarts → A 401

Two real servers on 127.0.0.1, each keeping sessions in its own Map. Log in on A, ask B: 401. Sticky works until A restarts with empty memory.

Common questions

What's the difference between stateless and stateful?

A stateful server keeps something between requests in its own memory, like your session, so you have to come back to it. A stateless one keeps nothing: each request brings or fetches what it needs, so any server can answer it.

Does stateless mean there's no state at all?

The state is all still there. It just moves out of the server's memory, into a shared store or a token the browser carries, so every server looks the same and you can add, remove or switch off any of them without logging anyone out.

Do sticky sessions solve it?

They buy time. The load balancer keeps sending you back to the same server, and when that server dies or is removed, everyone pinned to it is logged out. Load piles up unevenly too.

Sessions in Redis or a JWT?

Redis costs one trip per request, but deleting the key logs someone out at once. A JWT lets any server check the signature by itself, but you can't take it back before it expires. A normal web app: Redis. Several services trusting one identity: short-lived tokens.

Read: so which one?

Why can't I log a JWT out right away?

The server doesn't keep the token; it only checks the signature, so whoever holds a copy can use it until it expires. Keep tokens short-lived with a refresh token, or keep a list of revoked ones, which is a lookup again.

Are a cookie and a token the same thing?

No. A cookie is how something travels; a session id or a token is what travels. A session cookie holds only an id and the data stays on the server. A JWT carries the data itself, signed, in a cookie or the Authorization header.

What does moving sessions to Redis cost?

Every request makes one trip to Redis, and Redis becomes one more system to look after, with replicas and backups, or the day it goes down no server can check anyone's session.

Next lesson

Load balancingLevel: Basic

With sessions out of the servers, see how a load balancer spreads people over many of them and skips a dead one.