session consistency
What is session
web-server can automatically create sessions for users accessing the same browser and provide storage functions. Generally, user login information is stored in the session.
What is the session consistency problem
When there is only one web-server in the backend, the correct session can be found for every http request. The problem is that it cannot meet high availability. If one server hangs up, it will be over. Redundant failover, deploy multiple web-servers, and nginx routes to different web-servers. Every http request is routed and is not guaranteed to be routed to the same server, causing consistency issues.
Common solutions to solve session consistency
Consistency hash
The first solution that comes to mind is to hash based on the client IP to ensure that the same IP falls on a web- on the server. You can also use hashes based on business fields, such as userId and cityId, which are more flexible to use. However, this destroys the principle of singleness and makes the gateway and business sticky. It is not recommended to use it unless necessary. Advantages: saves cache, can be horizontally expanded. Disadvantages: When some services are restarted, sessions will be lost, causing some users to log in again. If the hash is expanded horizontally and the session is redistributed after rehash, some users will not be able to route the session
session synchronization
The sessions between multiple web-servers are synchronized with each other, so that each web-server Both contain all session information. Disadvantages: Because it contains all sessions, the number of clusters is limited by memory and expansion is limited.
Client storage
Login information is saved to the client, and each request carries user information. The server is completely stateless and easy to expand. Advantages: No storage is required on the server side. Disadvantages: Each http request carries user information, which wastes traffic; there is a risk of information leakage; cookies cannot store too much information.
Back-end centralized storage
The web-server links to a unified storage to save session information. It is recommended to store it in the redis cluster to facilitate subsequent expansion. Advantages: There is no risk of information leakage; horizontal expansion does not lose data; Disadvantages: An additional network request is added, and the business code needs to be modified to query redis.
The above is the detailed content of session consistency design. For more information, please follow other related articles on the PHP Chinese website!