How cookies work with non persistance load balencers
Solution 1:
A cookie is set in the browser, not in a server. It is restricted to a domain and, optionally, a specific path in the URL, so as long as both servers are accessed by the same domain, the cookie will be there.
If a cookie points to a session, then it is necessary that both server1 and server2 have access to that session in some way. If sessions cannot be shared between the servers then you need to force a user to persist to a specific server. This can be easily accomplished with DNS and alittle bit of URL rewrite magic:
- www.example.com points to both servers.
- www1.example.com points only to server1
- www2.example.com points only to server2
Using a set of simple(ish) rewrite rules and a cookie, the user can then be locked to a particular server, ensuring that the his session persists.
Here are some more details.
DNS:
- example.com A 1.1.1.1, A 2.2.2.2
- www.example.com CNAME example.com
- www1.example.com A 1.1.1.1
- www2.example.com A 2.2.2.2
Rewrite rules:
- persistence cookie: "backend"
- initial connection: "backend" not defined, set "backend" to www1 or www2, depending on which server has answered and redirect to that server. The cookie must be set to domain "example.com", this way it will be loaded on both www1 and www2
- If "backend" is defined, ensure that its value matches the server instance and redirect if necessary.
- Ensure that the session cookie is defined in the full domain name of the server - that is www1.example.com or www2.example.com
The rewrite logic is to be defined in the web server itself. All modern web servers have very featureful rewrite languages that are totally capable of implementing this functionality.