Linux – Do multiple Nginx servers load balance the same IP address to the same backend with the ip_hash directive

hashlinuxload balancingnginxPROXY

I have two separate Nginx machines. The domain uses round-robin DNS and has two A records, one for each of the two frontend Nginx server.

Both Nginx servers use the ip_hash directive and proxy requests to the same backend servers.

Will an IP address that goes to the first Nginx server always be routed to the same backend server as that same IP address that goes to the other Nginx server?

This may be of help: What IP does nginx use for ip_hash sticky sessions?

Best Answer

The Nginx servers are unaware of each other with their own ip_hash tables. So a specific server will route traffic to the backend based on its own ip_hash pool. Any consistency between the frontend Nginx servers would be due to chance alone.

Now in practice, this may be less of an issue because the client's DNS is unlikely to change during their session. As a result, they will hit the same front-end server and be routed to the same backend server.

Another approach to this is to use something like HAProxy, which can balance on a number of metrics, e.g. as a URL parameter. Your application can set a parameter to assure the client gets routed to the same backend. Of course normalizing your data over your backends with a distributed tool is preferred but that can be challenging with legacy applications.