Achieving Distributed Session Consistency with Spring Session and Redis

This article explains the challenges of sharing HTTP sessions across a clustered backend, evaluates common workarounds, and demonstrates a complete solution using Spring Session backed by Redis together with Nginx load balancing to achieve reliable distributed session consistency.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Achieving Distributed Session Consistency with Spring Session and Redis

Distributed Session Consistency?

In a server cluster, sharing HTTP session data between instances is a common problem.

What is a Session?

A session tracks the communication state between client and server. When a client first accesses the server, the server returns a sessionId stored in a cookie; subsequent requests include this ID, allowing the server to retrieve the stored session data or create a new session if none exists.

Problems with Distributed Session

If a client first contacts service A (which creates a session ID) and then contacts service B, B will not find the session data for that ID, create a new session, and return a different ID, breaking session sharing.

Typical Solutions

Use cookies only (insecure and unreliable).

Bind IP to a specific server in Nginx (prevents load balancing).

Synchronize sessions via a database (low efficiency).

Use Tomcat's built‑in session replication (may cause latency).

Replace sessions with tokens.

Adopt Spring Session with Redis storage.

Current Project Issues

Two services run on ports 8080 and 8081.

Dependencies

<!--springboot parent project-->
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
        <!-- web dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
</dependencies>

Test Controller

/**
 * Author: SimpleWu
 * date: 2018/12/14
 */
@RestController
public class TestSessionController {

    @Value("${server.port}")
    private Integer projectPort; // project port

    @RequestMapping("/createSession")
    public String createSession(HttpSession session, String name) {
        session.setAttribute("name", name);
        return "Current port: " + projectPort + " sessionId: " + session.getId() + " stored successfully!";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpSession session) {
        return "Current port: " + projectPort + " sessionId: " + session.getId() + " name: " + session.getAttribute("name");
    }
}

YAML Configuration (single instance)

server:
  port: 8080

Host Mapping

# Map local IP to www.hello.com
127.0.0.1 www.hello.com

Nginx Cluster Configuration

# default round‑robin
upstream backserver{
        server 127.0.0.1:8080;
        server 127.0.0.1:8081;
}
location / {
        proxy_pass http://backserver;
        index index.html index.htm;
}

Calling http://www.hello.com/createSession?name=SimpleWu stores the name in the session of the server that handled the request (e.g., 8081).

“Current port: 8081 current sessionId: 0F20F73170AE6780B1EC06D9B06210DB stored successfully!”

Subsequent requests are routed by round‑robin to the other instance (8080), which cannot find the session and creates a new one, resulting in a different session ID and a null name.

“Current port: 8080 current sessionId: C6663EA93572FB8DAE27736A553EAB89 name: null”

Repeating the request again may hit 8081, but the session ID has already changed, so the stored name is still missing.

How to Share Sessions Between the Two Services

Spring Session provides a ready‑made solution. Add the following dependencies:

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
</dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
</dependency>

Redis‑Backed YAML Configuration

server:
  port: 8081
spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
redis:
  hostname: localhost
  port: 6379

Session Configuration Class

/**
 * Author: SimpleWu
 * date: 2018/12/14
 */
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SessionConfig {

    @Value("${redis.hostname:localhost}")
    private String hostName;
    @Value("${redis.port:6379}")
    private int port;

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory connection = new JedisConnectionFactory();
        connection.setPort(port);
        connection.setHostName(hostName);
        return connection;
    }
}

Session Initializer

/**
 * Author: SimpleWu
 * date: 2018/12/14
 */
public class SessionInitializer extends AbstractHttpSessionApplicationInitializer {
    public SessionInitializer() {
        super(SessionConfig.class);
    }
}

After starting both services (8080 and 8081) with the above configuration, the session is stored in Redis and shared automatically.

Store a name:

“Current port: 8080 current sessionId: cf5c029a-2f90-4b7e-8345-bf61e0279254 stored successfully!”

Retrieve it (the next request goes to 8081):

“Current port: 8081 current sessionId: cf5c029a-2f90-4b7e-8345-bf61e0279254 name: SimpleWu”

Both the session ID and the stored attribute are now identical across instances.

Implementation Principle

When a web server receives an HTTP request, a filter forwards session creation to Spring Session. Instead of keeping the session in the server’s memory, Spring Session persists it in an external store (Redis, MySQL, etc.). All servers connect to this shared store, enabling true session sharing.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javadistributed-systemsspring-boot
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.