Stateless Services
Lesson 15Beginner1h 16mAssessment-backed

Stateless Services

Learn why stateless services scale and recover better, where state should live, and how sessions, files, jobs, and graceful shutdown affect production behavior.

What you will be able to do

Explain stateless services and why they enable horizontal scaling.
Identify unsafe local state such as sessions, files, in-memory queues, and background jobs.
Understand where durable and shared state should live.
Connect stateless design to Kubernetes, autoscaling, SIGTERM, readiness, and liveness.
Design a production-safe request service that can restart without losing user work.

A stateless service does not require a specific instance to remember user or workflow state between requests. Any healthy instance can handle the next request.

Why Statelessness Matters

Horizontal scaling, load balancing, rolling deploys, autoscaling, and failure recovery all become easier when service instances are replaceable. If one instance dies, another can continue because durable state lives outside the instance.

Stateless services using external database cache object storage and queue
Stateless instances are replaceable because durable/shared state lives in external systems.
State typeUnsafe locationBetter location
User sessionOne API server memorySigned token or shared session store/cache.
Uploaded fileLocal disk on one containerObject storage.
Pending workIn-memory listQueue.
Business dataProcess memoryDatabase.
Config/secretsHardcoded in instanceConfig service, environment, secret manager.

Scenario: Assessment Submission

A learner submits a strict assessment. The system should not lose the attempt if an API container restarts after accepting the request. Local memory is the wrong place for submitted answers or scoring jobs.

StepState decisionReason
Receive submissionValidate request and user auth in APIShort synchronous path.
Store submitted answersDurable database/object recordSubmission must survive crash.
Start scoringQueue scoring jobScoring may take time and can retry.
Track progressDatabase status fieldUser can refresh and see state.
Notify completionAsync event/notificationShould not block durable score.

Kubernetes and Runtime Behavior

Stateless design matters in Kubernetes and container platforms because instances can be moved, restarted, scaled down, or replaced. The service must handle lifecycle signals correctly.

ConceptMeaningDesign implication
Readiness probeCan this instance receive traffic?Fail readiness during startup or graceful shutdown.
Liveness probeIs the process stuck or dead?Restart only when local process is unhealthy.
SIGTERMShutdown signalStop accepting new work, finish or hand off in-flight work.
Grace periodTime before forced killKeep requests short or checkpoint long work.
Horizontal Pod AutoscalerAdds/removes instancesRequires externalized state and safe concurrency.

Design principle

If losing one instance loses accepted user work, the service is not stateless enough for reliable horizontal scaling.

12-Factor Connection

12-factor style applications push config into environment, treat backing services as attached resources, keep processes stateless, and write logs as event streams. These ideas make services easier to deploy and scale.

12-factor ideaSystem design meaning
Config in environmentDeploy the same build to different environments.
Backing servicesDatabase, cache, queue, and object storage are external resources.
ProcessesInstances are disposable and stateless.
LogsWrite logs to stdout/event pipeline, not local files.
ConcurrencyScale by process/container count.

Cloud Stateless Platforms

NeedAWSGCPAzure
Container appECS/EKSCloud Run/GKEContainer Apps/AKS
Serverless functionLambdaCloud FunctionsAzure Functions
Shared cache/sessionElastiCacheMemorystoreAzure Cache for Redis
Object storageS3Cloud StorageBlob Storage
Queue for workSQSPub/Sub/Cloud TasksService Bus/Storage Queues
SecretsSecrets Manager/Parameter StoreSecret ManagerKey Vault

Beginner Mistakes

  • Storing sessions only in local memory and expecting load balancing to work.
  • Writing uploaded files to container disk.
  • Starting long background work inside an API request without durable tracking.
  • Ignoring SIGTERM and dropping in-flight requests during deploys.
  • Using liveness probes to check deep dependencies and causing restart loops.

Guided Practice

Practice task

A resume upload API stores files on local disk and starts parsing in memory. Redesign it so instances can scale horizontally and restart safely.

Sample Answer

ProblemFix
Local file diskUpload directly or move immediately to object storage.
In-memory parse jobCreate durable parse job in queue.
No status trackingStore uploadId, file URL, parse status, and errors in database.
Duplicate retriesUse idempotency key or upload session ID.
Unsafe shutdownOn SIGTERM stop accepting new work and let queue retry unfinished jobs.

Before You Continue

  • You should know why stateless services scale better.
  • You should identify unsafe local state.
  • You should understand readiness, liveness, SIGTERM, and externalized state.
  • You are ready to learn how caching and CDNs reduce repeated work.