Sub topic 1
What a Stateless Service Is
Prerequisites
Assume you know the basics of HTTP requests, responses, headers, cookies, web services, and load balancers.
What a Stateless Service Is
A stateless service does not need information from an earlier request to process the next request. Each request contains, or can obtain, everything required to produce a response.
For example, GET /products/42 can be handled by any service instance because the product ID is in the request and product data comes from a database or another shared dependency.
Statelessness applies to the service instance, not to the whole application. An application can still have state in databases, caches, queues, or external session stores.
What Counts as Session State
Session state is data associated with one user's ongoing interaction. Examples include:
- The authenticated user's ID.
- A shopping cart.
- A multi-step form's progress.
- A temporary anti-forgery value.
- A login or authorization session.
A request ID, access log, or product catalog is usually not session state. Those values may be useful, but they do not describe a user's ongoing interaction.
The key test is whether a later request must find data created by an earlier request. If it must, that data needs a reliable shared location or a deliberate routing strategy.
Why Statelessness Helps Scaling and Deploys
Horizontal scaling adds more instances instead of making one instance larger. A load balancer can distribute requests freely when instances do not hold unique session data.
This also simplifies rolling deployments and failover. A request can move to a new instance when an old one is replaced or becomes unhealthy. Instances can start and stop without migrating in-memory sessions.
Sticky Sessions and Their Limits
Sticky sessions, also called session affinity, make the load balancer send a user repeatedly to the same instance. This allows that instance to keep session data in memory.
The approach is simple, but it weakens failover. If the instance stops, its sessions disappear unless another copy exists. Traffic can also become uneven when one instance receives many active users. Deployments become harder because sessions are tied to instances.
| Approach | Main advantage | Main limitation |
|---|---|---|
| Sticky sessions | Simple local storage | Instance failure can lose sessions |
Exercise
Why can a stateless service send two requests from one user to different instances?
Show answer
Because neither instance depends on private in-memory session data; both can use the request and shared dependencies.