Skip to Content

What does stateless in REST mean?

REST (Representational State Transfer) is an architectural style for building distributed systems like web services. One of the key principles of REST is being stateless, but what exactly does that mean?

What is Stateless?

Being stateless means that the server does not store any state about the client session on the server side. The session state is not kept on the server but is instead stored on the client side. So each request to the server is an independent request and is not related to any previous requests.

This means that in a stateless system, the client must include all the information necessary for the server to fulfill the request in each request. The server cannot rely on session state stored server-side. All session data is stored client-side in stateless REST.

Benefits of Stateless

There are several benefits to building stateless services:

  • Improved reliability – Since the server does not have to maintain and manage session state, it is less prone to failures and crashes if a client fails mid-session.
  • Easier to scale horizontally – Stateless applications can be easily scaled horizontally across multiple servers since any server can service any client request.
  • Better cacheability – Stateless requests can be cached easily since each request contains all the necessary information.
  • Loose coupling – The client and server do not have tight dependence on one another.
  • Easier load balancing and distribution of requests across servers.

Stateless in REST

REST being stateless means that REST API requests:

  • Are independent and may occur in any order
  • Do not reply on stored server context
  • Contain all the information required by the server to process the request
  • Do not rely on sessions maintained on the server

Some examples of how REST APIs remain stateless include:

  • Using tokens like API keys or JWTs to authenticate users instead of sessions
  • Including all necessary parameters and credentials in request headers instead of storing on server
  • Resources having unique URIs instead of ephemeral IDs

Maintaining State

While REST aims to be stateless, some state needs to be maintained between client and server in most applications. Common techniques used to maintain state include:

  • Client Session state – Storing session data like user id, basket etc in cookies or local storage on client
  • Resource State – State is stored on server but referenced through URI
  • State Transfer – State information converted to resource representation & transferred
  • Out of band state – Essential state stored on separate database

Challenges of Statelessness

Being completely stateless has some drawbacks as well:

  • More data (state) needs to be transferred in headers with each request
  • More client side logic is required to manage state
  • Caching is complex when state changes need to be tracked
  • Client needs to handle interrupted states like in middle of purchase

When to Use State

While REST emphasizes statelessness, some use of state is inevitable for complex applications. Common cases where state needs to be used include:

  • Shopping carts/ User session data
  • Multi step transactions like checkout process
  • Tracking progress through application flow
  • Managing transaction state
  • Persisting preferences/settings

In such cases, judicious use of state coupled with stateless principles can optimize application design.

Client Side State Storage

Since REST APIs cannot rely on server side state, client side storage is commonly used to maintain session state. Some popular options include:

Cookies

  • Small data stored as key-value pairs
  • Sent via request headers
  • Persist across sessions until expiry
  • Limited to few KB in size

Local Storage

  • Key-value storage maintained in browser
  • Persists even after browser closes
  • Much more storage space than cookies
  • Not sent automatically like cookies

Session Storage

  • Similar to Local Storage
  • Cleared when browser/tab is closed
  • Useful for short term state

The choice depends on use case, amount of data and browser support needs.

Caching

Since REST is stateless, responses can be easily cached to improve performance. Some tips for effective caching include:

  • Add Cache-Control headers to specify caching policies
  • Use ETags to validate if cached copy is still current
  • Make responses cacheable by removing dynamic/user-specific data
  • Use GET requests instead of POST/PUT which cannot be cached
  • Include versioning information in URIs to cache specific API versions

Load Balancing

Stateless services can be easily deployed across multiple servers and load balanced since any server can service a request. Some load balancing options:

Round Robin

Requests rotated sequentially among servers

Least Connections

Requests sent to server with fewest active connections

IP Hash

Requests hashed by IP mapped to server

Heartbeat

Periodic heartbeat checks server health status

Horizontal Scaling

Stateless applications can scale out easily by adding more servers since no coordination is required between servers. Scaling up to meet demand is simplified due to this loose coupling.

Benefits

  • Cost effective linear scaling
  • Smooth performance even with fluctuations
  • Resilient to server failures
  • Flexible resource allocation

Considerations

  • More complex system architecture
  • State synchronization if state present
  • Load balancer requirements
  • App code needs to be state agnostic

Security

Stateless APIs provide some inherent security advantages:

  • No sessions to be hijacked if no server side sessions
  • Replay attacks not possible as requests independent
  • DDoS resilient as all requests standalone
  • No single point of failure with distributed servers

However security best practices still essential, like:

  • HTTPS everywhere
  • Input validation and sanitation
  • Access tokens for authorization
  • Encryption of sensitive data

Testing

Stateless services are easier to test since no test state dependencies:

  • Requests can be sent in any sequence
  • Isolated requests simplify mocks and stubs
  • State store does not need to be mocked
  • Recreates real world usage closer

Tools like postman and insomnia allow easily testing stateless APIs.

Microservices

Stateless and REST go hand in hand with microservices too. Some synergies:

  • Loose coupling suits microservices architecture
  • Services independently scalable
  • Inter service communication simplified
  • Reduces coordination complexity

Microservices ecosystems rely heavily on stateless APIs for inter service calls.

Common Workarounds

Though REST aims for statelessness, some compromises are often required in practice:

API Keys

API keys used for authentication instead of sessions

JWT Tokens

State information encoded in JWT access tokens

Request Parameter

Addition of state parameters to API calls

Custom Headers

Usage of custom headers to transfer state

Gateways

Gateways used to manage sessions across services

Client Responsibilities

In a stateless system, the client takes on added responsibilities like:

  • Maintaining session/user state
  • Resending context if connection drops
  • Sending credentials with each request
  • Handling mid-process interrupts
  • App state synchronization if required

Server Responsibilities

The server responsibilities are reduced in a stateless architecture. Main ones are:

  • Idempotent endpoints to handle repeats
  • Authentication/authorization for each call
  • Validation of each request
  • Returning enough metadata for caching
  • Providing HATEOAS links for navigation

Stateless Pros

  • Improved reliability with no state
  • Easier scalability and load balancing
  • More lightweight and decoupled
  • Increased visibility with logs
  • Easier troubleshooting

Stateless Cons

  • More requests required
  • Added complexity for clients
  • Duplicate data across requests
  • Complicates user specific content
  • Does not fit all application types

Conclusion

Statelessness is a key design principle of REST APIs and provides significant benefits but also some drawbacks. Real world applications often require a pragmatic combination of stateless and stateful elements. The sweet spot is balancing the pros and cons to find the right fit for application needs.