Video in progress

Strong Junior 🧩 Microservices

What does "a service must be stateless" mean, and where do you keep the user session?

Stateless means an instance doesn't keep user state in its own memory between requests, so any replica can handle any request. If you need a session, it lives inside a JWT or in a shared place like Redis.

📖 Answer

Say that after login the user data is in HttpSession, which means in Tomcat's memory. With one pod, everything is fine. With 3 pods, the load balancer sends the next request to a different pod, which has no session, and the user gets "logged out". If a pod restarts or the autoscaler removes it, the same thing happens.

Sticky sessions (always routing a user to the same pod) are only a patch: if the pod dies, the session is still lost, and the load is spread unevenly too.

The right options:

  • keep the state in the token: the user ID and roles in a JWT, and the server remembers nothing;
  • if you need a server-side session, move it to a shared place. If you add the spring-session-data-redis dependency, HttpSession is stored in Redis automatically (in Boot 3 you don't need a separate store-type setting):
spring:
  data:
    redis:
      host: redis
      port: 6379

Stateless isn't only about sessions. Files uploaded to local disk, in-memory queues, work that "only runs on this pod": all of it is lost when the pod dies. Move files to object storage (S3, MinIO) and queues to a broker. A local cache is fine: if it's lost, the data can be fetched again from elsewhere.