What is a session

The Web-server can automatically create sessions for users accessing the same browser to provide storage functions. Generally, user information and login information are stored in the session.

What are session consistency issues

When there is only one Web-server on the back end, the correct session can be found for every HTTP request. The problem is that high availability cannot be satisfied and one server dies. The solution is redundancy + failover, deployment of multiple Web-servers, routing from Nginx to different Web-servers. If every TIME HTTP requests a route, there is no guarantee that it will be routed to the same server, this is a consistency problem.

Common solutions to session consistency

Consistency of the hash

This is the first solution that comes to mind. Hash based on the client IP address to ensure that the same IP address falls on the same Web-server, i.e., four layers of hash. You can also hash based on business fields, such as userId and cityId, or use a more flexible seven-layer hash. But this breaks the single rule and makes gateways relevant to the business, which is not recommended unless necessary. Advantages: Save cache, available horizontal expansion (session synchronization method is not available, limited by memory). Disadvantages: If some services restart, the session will be lost, causing some users to log in again. If the hash is extended horizontally, sessions are redistributed after the hash is rehash, and some users fail to enter the session.

The session synchronization

Sessions of multiple Web-servers are synchronized with each other, so that each Web-server contains all session information. Advantages: Each Web-server contains all sessions, and no information is lost when a single server fails, at least in theory. Disadvantages: Wasted cache, limited number of clusters by memory, limited scale.

Client storage

Login information is saved to the client, and each request carries the user information. The server is completely stateless for easy expansion. Advantages: The server does not need storage. Disadvantages: Each HTTP request carries user information, which wastes extranet traffic. If the session is on the client, there is a risk of information leakage. Cookies cannot store too much information.

Back-end centralized storage

Web-server links to a unified storage to store session information, which is recommended to be stored in redis cluster for subsequent expansion. Advantages: No risk of information disclosure; Horizontal scaling does not lose data; Disadvantages: added a network request, need to modify the business code, query redis.