How to Share Sessions Across Distributed Servers: Nginx, Tomcat, Redis, and Cookie Solutions
This article explains why session sharing is critical in micro‑service architectures, compares common Nginx load‑balancing methods, and provides four practical solutions—ip_hash load balancing, Tomcat session replication, Redis‑based session caching, and cookie‑based sharing—complete with configuration examples and pros/cons.
When a micro‑service or distributed system deploys across multiple server clusters, a user's session may be stored only on the server that initially handled the request, causing repeated logins if subsequent requests are routed to other servers. Sharing sessions across all nodes is therefore essential.
Common Nginx reverse‑proxy strategies
Round‑robin
Weighted ratio
ip_hash
Custom strategies
Solution 1: Nginx ip_hash load balancing
Requests are assigned to a server based on the hash of the client IP, ensuring that the same client consistently reaches the same backend node.
Configuration example:
upstream backend {
ip_hash;
server 192.168.128.1:8080;
server 192.168.128.2:8080;
server 192.168.128.3:8080 down;
server 192.168.128.4:8080 down;
}
server {
listen 8081;
server_name test.csdn.net;
root /home/system/test.csdn.net/test;
location ^~ /Upload/upload {
proxy_pass http://backend;
}
}Advantages and disadvantages are illustrated below:
Solution 2: Tomcat session replication
This approach copies the generated session ID to all servers in the cluster, so any server can retrieve the session without forcing the user to log in again.
Implementation details (code diagram) are shown below:
Pros and cons of session replication:
Solution 3: Redis‑based unified session cache
Each request's session ID is stored in Redis with an expiration time, allowing any server to retrieve the session while it remains valid.
Sample configuration diagram:
Advantages and disadvantages of using Redis for session sharing:
Solution 4: Cookie‑based session sharing
By storing the session identifier in a cookie, every request automatically carries the session information, eliminating the need for additional server‑side synchronization.
Reference: NetEase Cloud Classroom Source: blog.csdn.net/qq_36520235/article/details/87830929
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
