ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 7 · Application Architecture & Distributed Systems
  4. Volume VII
  5. Stateless Architecture
Book 7 · Volume VII — Resilience, Scalability & Distributed Data · Topic 1.2

Stateless Architecture

Session externalization

9 min readStage 3 · Systems8 interview questions
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
Covers
Session externalization
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Hidden State in Java Services
  5. 4A. Deep Dive — Removing Sticky Sessions
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

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.

Session externalization (TOC)
Figure 1 — Session externalization (TOC)
TOC conceptDefinition
Session externalizationRelocating 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.

Stateful vs stateless instances
Figure 2 — Stateful vs stateless instances

3Core Concepts

3.1 Session externalization

Request with externalized session
Figure 3 — Request with externalized session
YAML
# Spring Session backed by ElastiCache Redis
spring:
  session:
    redis:
      namespace: shopnow:session
      flush-mode: on-save
    timeout: 30m
  data:
    redis:
      host: ${REDIS_HOST}
      ssl: { enabled: true }
server:
  servlet:
    session:
      cookie: { secure: true, http-only: true, same-site: lax }
JAVA
@Configuration
@EnableRedisIndexedHttpSession(maxInactiveIntervalInSeconds = 1800)
class SessionConfig {}
 
@GetMapping("/cart")
Cart cart(HttpSession session) {                      // HttpSession now lives in Redis
    return (Cart) Optional.ofNullable(session.getAttribute("cart")).orElse(Cart.empty());
}
OptionHowTrade-off
Server-side store (Redis)Session id cookie → RedisRevocable, small cookie; Redis dependency
Client token (JWT)Signed claims in header/cookieNo lookup; hard to revoke, size limits
HybridJWT for identity + Redis/DynamoDB for cartCommon in APIs
DatabaseJDBC session tableSimple; slower, DB load
Table 2 — Where sessions can live
JAVA
// Stateless API authentication: JWT validated on every request, no server session
@Bean
SecurityFilterChain 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();
}
Where each kind of state goes
Figure 4 — Where each kind of state goes
Session data at ShopNowSizeStoreTTL
Authenticated user id, roles< 1 KBJWT (API) / Redis (web)15 min access, 30 d refresh
Cart2–8 KBRedis hash per customer30 days
Checkout progress1 KBRedis session30 min
Recently viewed1 KBRedis list7 days
Uploaded return photosMBsS3 (presigned)90 days
Table 3 — What moved where
Session store optionLatencyDurabilityNotes
ElastiCache Redis< 1 msReplica + AOF optionalDefault for web sessions
DynamoDBsingle-digit msMulti-AZ durableCarts needing durability, global tables
PostgreSQL (JDBC)few msDurableSimple; adds DB load
Signed cookie/JWT0 (no lookup)Client-heldSize and revocation limits
Table 4 — Session store comparison

4How It Works Internally — Hidden State in Java Services

Hidden stateSymptomFix
Static maps / in-memory caches used as truthDifferent answers per podExternal store; caches only as optimisation
Local file uploadsFile "missing" on other podS3 (multipart, presigned URLs)
@Scheduled jobsRun N times with N podsShedLock / leader election
In-memory rate limitsLimits multiply by pod countRedis / gateway limits
WebSocket sessionsMessages miss users on other podsPub/sub fan-out (Redis, Kafka)
In-flight requests at shutdownErrors on deployGraceful shutdown + drain
Table 5 — Finding hidden state
YAML
# Graceful shutdown so instances can be removed safely
server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 25s
# Kubernetes: preStop sleep lets the ALB deregister before the JVM stops
lifecycle:
  preStop: { exec: { command: ["sh", "-c", "sleep 10"] } }
terminationGracePeriodSeconds: 40

4ADeep Dive — Removing Sticky Sessions

Making a stateful app stateless
Figure 5 — Making a stateful app stateless
Users logged out during scale-in (illustrative)
Figure 6 — Users logged out during scale-in (illustrative)
JAVA
// Chaos check: kill a random checkout pod every 60 s; assert no session loss
@Test
void sessionsSurvivePodKills() {
    // login, add to cart, checkout
    var 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 stepVerification
1. Add Spring Session (Redis), keep stickinessSessions visible in Redis
2. Move files to S3, lock scheduled jobsNo local writes (read-only root FS)
3. Disable ALB stickinessEven load across pods
4. Enable HPA scale-inNo logout spikes
5. Run chaos test in CI/stagingZero lost sessions
Table 6 — Rollout plan
Sticky sessions (ALB stickiness)Consequence
Uneven loadNew pods get little traffic
Scale-in/deploy logs users outUnless sessions are also external
Hot-spot podsOne pod holds heavy users
Masks hidden stateBugs appear later
Table 7 — Why to avoid stickiness
Stateless service rules
Figure 7 — Stateless service rules

5APIs / Features / Syntax

NeedTooling
HTTP sessionsSpring Session Data Redis / JDBC
TokensSpring Security OAuth2 Resource Server (JWT)
FilesAWS SDK S3, presigned URLs
Singleton jobsShedLock, Kubernetes leases
Shutdownserver.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.

6.3 Worked example — session size

Keep sessions < 10 KBStore ids, not objects
Table 9 — Small sessions

6.4 Worked example — Redis HA

ElastiCache Multi-AZ, replicaSession store not a SPOF
Table 10 — Availability

6.5 Worked example — JWT revocation

Short expiry (15 min) + refresh tokensLimit exposure
Table 11 — Token trade-off

6.6 Worked example — S3 uploads

Presigned PUT from browserPods never hold files
Table 12 — Stateless uploads

6.7 Worked example — ShedLock

JAVA
@Scheduled(cron = "0 0 * * * *")
@SchedulerLock(name = "cart-reminders", lockAtMostFor = "PT10M")
void remind() { reminders.sendDue(); }

6.8 Worked example — WebSockets

Order-status pushRedis pub/sub to all pods
Table 13 — Fan-out

6.9 Worked example — chaos test

Kill 30% of pods during load testNo errors beyond retries
Table 14 — Proof

6.10 Worked example — rolling deploy

maxUnavailable 0, maxSurge 25%Zero-downtime
Table 15 — Deploy safety

6.11 Worked example — rate limits

Per-user 100/min in RedisConsistent across pods
Table 16 — Shared counters

6.12 Worked example — caches

Caffeine local cache for catalogueOK — rebuildable
Table 17 — Allowed state

6.13 Worked example — Spot instances

2-min interruption noticeStateless pods tolerate
Table 18 — Cost savings

6.14 Worked example — session serialisation

JSON serializer for sessionsUpgrade-safe
Table 19 — Avoid Java serialization

6.15 Worked example — idempotency

Retry on another podIdempotency keys
Table 20 — Safe retries

6.16 Worked example — config

Config from env/ConfigMapNo per-pod edits
Table 21 — 12-factor

6.17 Worked example — sticky removal plan

Externalize → verify → disable stickinessOrder matters
Table 22 — Safe migration

6.18 Worked example — metrics

Load spread per pod (stddev)Detect imbalance
Table 23 — Observability

6.19 Worked example — ADR

DecisionRationale
Redis sessions, JWT for APIs, no stickinessElastic scaling
Table 24 — Recorded

6.20 Worked example — review checklist

Check✔
No in-memory session/cart✔
No local files✔
Singleton jobs locked✔
Graceful shutdown✔
Table 25 — Statelessness review

6.21 Worked example — interview answer

ConceptAnswer
StatelessInstances hold no client state
ExternalizationSessions in Redis or tokens
Table 26 — Structured answer

7Common Problems & Mistakes

  • In-memory sessions with sticky routing.
  • Local file storage.
  • Duplicate scheduled jobs.
  • Java-serialized sessions breaking upgrades.
  • Unrevocable long-lived JWTs.
  • No graceful shutdown.

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

AspectGuideline
Session storeHA Redis, small sessions
TokensShort-lived, refreshable
FilesObject storage
JobsDistributed locks
ShutdownDrain 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.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.