Book 7 · Volume VII — Resilience, Scalability & Distributed Data · Topic 1.2
Stateless Architecture
Session externalization
9 min readStage 3 · Systems8 interview questions
Written byMaheshFounder · Senior Technical Architect
Chapter
Chapter 1 — Scalability Architecture
Prerequisites
Topic 1.1
You will be able to
Explain what makes a service stateless, identify hidden state in Java applications, externalize sessions with Spring Session or tokens, relocate files, locks and connection state, remove sticky sessions safely, and verify statelessness by killing instances under load
A stateless service keeps no client-specific or request-spanning state in its own memory or disk between requests: every request carries, or can fetch, everything needed to process it. Session externalization moves session data — login, cart, preferences, workflow progress — out of the instance into a shared store (Redis, DynamoDB) or into the client (signed tokens), so any instance can serve any request.
Figure 1 — Session externalization (TOC)
TOC concept
Definition
Session externalization
Relocating per-user conversational state from instance memory to an external, shared and durable store — or into signed client tokens — with defined expiry and security, so instances become interchangeable and can be added, removed or replaced without user impact
Table 1 — The TOC concept
2Why It Exists
Horizontal scaling, autoscaling, rolling deploys, Spot instances and self-healing all assume an instance can vanish at any moment. In-memory sessions turn each of those events into logged-out users and lost carts.
The cost of hidden state grows with every automation added to the platform. On a fixed pair of servers, sessions in memory are mostly harmless; on Kubernetes with an HPA, rolling deployments several times a day and Spot capacity, pods are created and destroyed constantly, and each event drops whatever those pods held. Stateful instances also force sticky routing, which spreads load unevenly and makes newly added pods almost useless during a traffic spike, exactly when they are needed. Externalizing state turns the instance into a replaceable unit, so scaling and recovery become routine operations rather than risky events. It also simplifies incident response, because a misbehaving pod can be killed immediately without asking which users are attached to it.
@Configuration@EnableRedisIndexedHttpSession(maxInactiveIntervalInSeconds = 1800)class SessionConfig {}@GetMapping("/cart")Cart cart(HttpSession session) { // HttpSession now lives in Redisreturn (Cart) Optional.ofNullable(session.getAttribute("cart")).orElse(Cart.empty());}
Option
How
Trade-off
Server-side store (Redis)
Session id cookie → Redis
Revocable, small cookie; Redis dependency
Client token (JWT)
Signed claims in header/cookie
No lookup; hard to revoke, size limits
Hybrid
JWT for identity + Redis/DynamoDB for cart
Common in APIs
Database
JDBC session table
Simple; slower, DB load
Table 2 — Where sessions can live
JAVA
// Stateless API authentication: JWT validated on every request, no server session@BeanSecurityFilterChain api(HttpSecurity http) throws Exception {return http .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) .authorizeHttpRequests(a -> a.anyRequest().authenticated()) .build();}
Figure 4 — Where each kind of state goes
Session data at ShopNow
Size
Store
TTL
Authenticated user id, roles
< 1 KB
JWT (API) / Redis (web)
15 min access, 30 d refresh
Cart
2–8 KB
Redis hash per customer
30 days
Checkout progress
1 KB
Redis session
30 min
Recently viewed
1 KB
Redis list
7 days
Uploaded return photos
MBs
S3 (presigned)
90 days
Table 3 — What moved where
Session store option
Latency
Durability
Notes
ElastiCache Redis
< 1 ms
Replica + AOF optional
Default for web sessions
DynamoDB
single-digit ms
Multi-AZ durable
Carts needing durability, global tables
PostgreSQL (JDBC)
few ms
Durable
Simple; adds DB load
Signed cookie/JWT
0 (no lookup)
Client-held
Size and revocation limits
Table 4 — Session store comparison
4How It Works Internally — Hidden State in Java Services
Hidden state
Symptom
Fix
Static maps / in-memory caches used as truth
Different answers per pod
External store; caches only as optimisation
Local file uploads
File "missing" on other pod
S3 (multipart, presigned URLs)
@Scheduled jobs
Run N times with N pods
ShedLock / leader election
In-memory rate limits
Limits multiply by pod count
Redis / gateway limits
WebSocket sessions
Messages miss users on other pods
Pub/sub fan-out (Redis, Kafka)
In-flight requests at shutdown
Errors on deploy
Graceful shutdown + drain
Table 5 — Finding hidden state
YAML
# Graceful shutdown so instances can be removed safelyserver: shutdown: gracefulspring: lifecycle: timeout-per-shutdown-phase: 25s# Kubernetes: preStop sleep lets the ALB deregister before the JVM stopslifecycle: preStop: { exec: { command: ["sh", "-c", "sleep 10"] } }terminationGracePeriodSeconds: 40
4ADeep Dive — Removing Sticky Sessions
Figure 5 — Making a stateful app stateless
Figure 6 — Users logged out during scale-in (illustrative)
JAVA
// Chaos check: kill a random checkout pod every 60 s; assert no session loss@Testvoid sessionsSurvivePodKills() {// login, add to cart, checkoutvar users = loadGenerator.startUsers(500, Duration.ofMinutes(10)); scheduler.scheduleAtFixedRate( () -> kube.deleteRandomPod("app=checkout"), 60, 60, SECONDS);var result = users.awaitCompletion(); assertThat(result.loggedOutUnexpectedly()).isZero(); assertThat(result.cartsLost()).isZero(); assertThat(result.errorRate()).isLessThan(0.001); // retries absorb kills}
Migration step
Verification
1. Add Spring Session (Redis), keep stickiness
Sessions visible in Redis
2. Move files to S3, lock scheduled jobs
No local writes (read-only root FS)
3. Disable ALB stickiness
Even load across pods
4. Enable HPA scale-in
No logout spikes
5. Run chaos test in CI/staging
Zero lost sessions
Table 6 — Rollout plan
Sticky sessions (ALB stickiness)
Consequence
Uneven load
New pods get little traffic
Scale-in/deploy logs users out
Unless sessions are also external
Hot-spot pods
One pod holds heavy users
Masks hidden state
Bugs appear later
Table 7 — Why to avoid stickiness
Figure 7 — Stateless service rules
5APIs / Features / Syntax
Need
Tooling
HTTP sessions
Spring Session Data Redis / JDBC
Tokens
Spring Security OAuth2 Resource Server (JWT)
Files
AWS SDK S3, presigned URLs
Singleton jobs
ShedLock, Kubernetes leases
Shutdown
server.shutdown=graceful, preStop
Table 8 — Toolkit
6Practical Examples
6.1 Sale-day logouts
During a sale, HPA scaled checkout in after the first wave and 3,200 users lost carts stored in pod memory. Moving carts to Redis (Spring Session) and disabling ALB stickiness removed logouts and evened pod load.
6.2 Duplicate emails
A @Scheduled reminder job sent each email three times after scaling to three pods. ShedLock with a PostgreSQL lock table fixed it.
Almost all of these problems come from state that is still tied to one instance, or moved out carelessly. In-memory sessions with sticky routing work until the first scale-in or deployment, then log users out in bulk. Local file storage and unlocked @Scheduled jobs behave correctly with one pod and fail only after scaling. Two mistakes appear after externalization: Java-serialized session objects break when a class changes during a rolling upgrade, because old and new pods cannot read each other's data, and long-lived JWTs cannot be revoked when a user logs out or a token leaks. Without graceful shutdown, every deployment drops in-flight requests. The chaos test in this note catches most of these before customers do.
8Performance & Production Considerations
Aspect
Guideline
Session store
HA Redis, small sessions
Tokens
Short-lived, refreshable
Files
Object storage
Jobs
Distributed locks
Shutdown
Drain before stop
Table 27 — Operational guidelines
9Architecture & Design Considerations
Make disposability a design requirement.
Put state in purpose-built stores.
Remove stickiness after externalizing.
Verify statelessness with chaos tests.
10Interview Questions & Answers
Q1L1 · BasicConcept
What is a stateless service?
A stateless service keeps no client-specific or request-spanning state in its own memory or local disk between requests. Every request carries, or can fetch, everything needed to process it, so any instance can serve any request and instances are interchangeable and disposable. That does not mean the system has no state: sessions live in Redis or signed tokens, files in S3, data in databases and locks in a shared store. Local caches are fine as long as they are only an optimisation that can be rebuilt. Statelessness is what makes horizontal scaling, autoscaling, rolling deployments, Spot instances and self-healing safe, because any pod can disappear without users noticing.
Q2L1 · BasicConcept
What is session externalization?
Session externalization means moving per-user conversational state, such as login, cart, preferences or checkout progress, out of the application instance's memory into a shared, durable store or into the client. The usual server-side option is a session id cookie with the data in Redis, for example ElastiCache, or in DynamoDB or a JDBC table, with a defined expiry. The client-side option is a signed token such as a JWT carrying identity claims, which needs no lookup. Many systems combine them: JWTs for API identity and Redis for the cart. Once sessions are external, any instance can serve any request, so sticky sessions can be removed and pods added or killed freely.
Q3L2 · IntermediateInternals
How does Spring Session help?
Spring Session replaces the servlet container's in-memory HttpSession with one stored in an external repository, transparently to application code. It installs a servlet filter, SessionRepositoryFilter, that wraps each request so request.getSession() returns a session loaded from Redis, JDBC or another store, keyed by the session cookie. Attributes are written back on save or immediately depending on flush mode, and expiry is handled by the store's TTL. With Spring Boot you add spring-session-data-redis, configure the Redis connection and timeout, and optionally use @EnableRedisIndexedHttpSession to find sessions by user name. Existing controllers keep calling session.getAttribute. Use a JSON serializer rather than Java serialization so sessions survive class changes during rolling upgrades.
Q4L2 · IntermediateTrade-off
JWT vs server-side sessions?
JWTs and server-side sessions trade lookup cost against control. A JWT is a signed token carrying claims, validated locally on every request with the issuer's public key, so there is no session store to query or scale. Its weakness is revocation: a stolen or outdated token stays valid until it expires, and tokens grow with claims. Server-side sessions keep only an id in the cookie and the data in Redis or a database, so they are small, easy to revoke and can hold larger state, but every request needs a lookup and the store must be highly available. Common practice is short-lived JWTs with refresh tokens for APIs, and Redis sessions for browser state.
Q5L3 · Senior EngineerTricky
Name hidden state that breaks scaling.
Hidden state is anything an instance keeps locally that other instances cannot see. Common examples in Java services are static maps or in-memory caches used as the source of truth, so pods give different answers, and uploads written to the local disk, so a file is missing on the next pod. @Scheduled jobs run once per pod, sending duplicate emails, and in-memory rate limits multiply by the number of pods. WebSocket sessions bind a user to one pod, so messages published on another pod never reach them. Even in-flight requests are state at shutdown. The fixes are an external store, S3, ShedLock or leader election, Redis counters, pub/sub fan-out and graceful shutdown.
Q6L3 · Senior EngineerTrade-off
Why avoid sticky sessions?
Sticky sessions route a user to the same instance every time, which hides in-memory state instead of removing it. Load spreads unevenly: new pods added by the autoscaler receive little traffic because existing users stay pinned, and a pod holding heavy users becomes a hot spot. Scale-in, rolling deployments, Spot interruptions and crashes still log users out or lose their carts, because their session lived only on the pod that disappeared. Stickiness also masks hidden-state bugs, which then appear at the worst time, such as a sale day. If you want affinity for cache efficiency, keep it as an optimisation over externalized sessions, never as the mechanism that keeps state.
Q7L4 · Technical ArchitectScenario
How do you run a job once with many pods?
Use a distributed lock or leader election so only one instance runs the job at a time. With Spring, ShedLock is the simplest option: annotate the @Scheduled method with @SchedulerLock and give it a lock provider backed by the existing database, Redis or another store. Each pod tries to acquire the named lock when the schedule fires, and only the winner runs; lockAtMostFor releases the lock if that pod dies. On Kubernetes you can instead use leader election through a Lease object, or move the job to a Kubernetes CronJob or a queue-driven worker. Either way, make the job idempotent, because a lock expiry or retry can still cause occasional duplicate execution.
Q8L5 · Solution ArchitectDesign
How would you prove a service is stateless?
Prove it with a test that kills instances while users are active, rather than by reviewing code. Run a realistic load test, for example 500 virtual users logging in, adding to carts and checking out, and during it delete a random pod every minute or terminate 30% of pods at once. Assert that no user is logged out unexpectedly, no cart is lost and the error rate stays below a small threshold that retries can absorb. Also check that load spreads evenly across pods and that rolling deployments and HPA scale-in cause no spikes. Run the test regularly in staging or CI, together with graceful shutdown and a read-only root filesystem to catch local writes.