Video in progress

How does storing HTTP sessions in Redis with Spring Session work, and what problems do you run into in prod?

The session is stored in Redis as a hash, read on every request, and changed attributes are written back, so any pod can serve any user. The problems: putting large objects in the session, serialization versions, everyone being logged out if Redis goes down, and relying on expiry events.

📖 Answer

The setup is simple:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SessionConfig {
    @Bean
    RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}

In Spring Session 3.x, @EnableRedisHttpSession uses the lightweight RedisSessionRepository, which stores only the session hash with a TTL. If you need an event (SessionDestroyedEvent) when a session expires or is deleted, or you need to find all of a user's sessions, you need @EnableRedisIndexedHttpSession. It relies on extra keys and keyspace notifications, which adds load and complexity to Redis.

What I've seen in prod:

  • Putting big things in the session: a cart, the whole user profile, a permissions list. They are read and sent over the network on every request. Keep only IDs in the session.
  • JDK serialization: that's the default. If the principal class changes in a deploy, every user's session fails to deserialize and returns a 500. You need a JSON serializer and a way to "invalidate the session on a deserialization error".
  • If Redis goes down, everyone is logged out. Redis for sessions has to be HA (Sentinel/Cluster or managed), and it shouldn't share an instance with the cache, so that cache eviction doesn't wipe out sessions.
  • Concurrent requests: if two parallel requests write different attributes to the same session, the last writer wins. You need to understand the FlushMode and SaveMode settings (SaveMode.ON_SET_ATTRIBUTE writes only the changed attributes).

If the API can be stateless (JWT with a short lifetime, the refresh token in Redis), not storing sessions at all is also an option, but then you get the problem of revoking tokens.