Redis Tutorial 0/42 lessons ~6 min read Lesson 34

    Session Management

    Spring Session with Redis stores HTTP sessions in hashes — pods stay stateless behind load balancers without sticky sessions.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Spring Session with Redis stores HTTP sessions in hashes — pods stay stateless behind load balancers without sticky sessions. Netflix-scale session stores use hash per sessionId, TTL aligned with token expiry, cluster sharded by userId.

    @EnableRedisHttpSession sets default maxInactiveInterval. Session data must stay small; large objects belong in DB with ID reference in session.

    GDPR: session keys contain user metadata — encrypt sensitive fields and TTL aggressively.

    Understanding the topic

    Key concepts

    • spring-session-data-redis dependency.
    • @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600).
    • Session stored as Redis hash spring:session:sessions:{id}.
    • Cookie SESSION or configurable name.
    • FindByIndexNameSessionRepository for logout all devices.
    • TTL refreshed on each request by default.
    text
    flowchart LR
    Controller --> Service
    Service --> RedisTemplate
    RedisTemplate --> Redis

    Step-by-step explanation

    1. Filter intercepts HTTP session access.
    2. Session attributes serialized to Redis hash.
    3. Session id in cookie maps to Redis key.
    4. Expiry extended on activity.
    5. Destroy removes hash on logout/timeout.

    Syntax reference

    Common commands

    • namespace isolates envs on shared Redis.
    • Set cookie Secure HttpOnly in prod.
    • Cluster: sessionId random — even distribution.
    bash
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
    public class SessionConfig {}
    // application.yml
    spring.session.redis.namespace: myapp:session

    Informative example

    Store user id in session — horizontal scale without sticky sessions:

    java
    @RestController
    public class AuthController {
    @PostMapping("/login")
    public void login(@RequestBody Login req, HttpSession session) {
    User user = authService.authenticate(req);
    session.setAttribute("userId", user.id());
    session.setAttribute("roles", user.roles());
    }
    @GetMapping("/me")
    public Profile me(HttpSession session) {
    Long userId = (Long) session.getAttribute("userId");
    return profileService.load(userId);
    }
    }

    Spring Session serializes attributes. Prefer storing IDs not full User graphs. Java 21 records in session need compatible serialization.

    Real-world use

    Real-world use cases

    • Kubernetes microservices without sticky LB.
    • Logout all sessions for compromised account.
    • Multi-region session with global Redis.
    • OAuth login state in session briefly.
    • Shopping cart before checkout login merge.

    Best practices

    • Store identifiers not full entity graphs.
    • Align session TTL with JWT/access token.
    • Namespace per environment.
    • Monitor session key count and memory.
    • HttpOnly Secure SameSite cookies.
    • Spring Session + Spring Security integration tested.

    Common mistakes

    • Huge session objects — memory × concurrent users.
    • Sticky sessions enabled unnecessarily.
    • Shared Redis namespace dev/prod.
    • Non-serializable objects in session.

    Advanced interview questions

    Q1BeginnerWhy Redis for sessions?
    Shared store lets any pod serve any request — no sticky sessions.
    Q2Beginner@EnableRedisHttpSession does?
    Configures SessionRepository backed by Redis hashes.
    Q3IntermediateSession TTL refresh?
    Default extends on each request — sliding expiration.
    Q4IntermediateLogout all devices?
    Find sessions by principal index and delete via Spring Session API.
    Q5Advanced50M concurrent sessions sizing?
    ~2KB each; Cluster shard; allkeys-lru; TTL; monitor memory; avoid large attributes.

    Summary

    Spring Session + Redis = stateless pods.

    Ready to mark this lesson complete?Track your journey across the entire course.