Video in progress

Why do people move the HTTP session to Redis when the application runs on several instances?

By default the session lives in each instance's own memory: if the next request lands on a different instance, the user gets "logged out". Spring Session writes the session to Redis, and any instance can read it.

📖 Answer

Say there are 3 pods behind a load balancer. The user logs in on pod 1, and the session sits in that pod's heap. The next request lands on pod 2, which doesn't know this session and sends the user back to the login page.

The options: sticky sessions (the balancer always sends the user to the same pod), but if the pod restarts or dies, the sessions are lost anyway. A shared store closes this problem.

<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>
spring:
  session:
    timeout: 30m

After that you work with HttpSession as usual; Spring stores it in Redis as a Hash and keeps refreshing the TTL itself.

Be careful: don't put large objects in the session (a whole cart, lists), because they are read from Redis on every request. The classes stored in the session also have to be serializable, and if you change them in a deploy, old sessions may become unreadable.