session persistance with IP hash

Reinis Rozitis r at
Wed Jul 27 22:01:56 UTC 2016

>Took a look at the link, but I have no idea what that would look like in my 
>upstream stanza. Can you provide an example of what that would look like if 
>I had 3 different backend servers and wanted to ensure that my hash was 
>based on a cookie, or based on just a hash that provided a different 
>backend server per session?

With the vanilla nginx it would be something like (and for example let's say 
your cookie name is BACKEND):

upstream backend {
        hash $cookie_BACKEND;
        server backend1:80;
        server backend2:80;
        server backend3:80;

The problem with this (if it matters) is that there is no (pre)defined value 
of the cookie BACKEND which would specifically route particular client to 
particular backend - I mean for example if you use values 'backend1', 
'backend2', 'backend3' the hashed keys might (or not) aswell all point to 
the same backend server.
So unless you find 3 values which for sure point to different backends the 
load/users might not be evenly distributed (in general it is the same as 
with ip_hash if the end-users don't have very distinct IPs or for example 
are in the same subnet all the users will land on the same backend (as per 
documentation - "The first three octets of the client IPv4 address are used 
as a hashing key.")). It shouldn't be too hard though.

Of course if the values differ (for each user a different cookie) in longer 
run the requests will be somewhat evenly distributed.

As a module you can try this but as 
it was mentioned in previous mail by Robert the quality might vary and if 
you want a better controlable user distribution Lua could be also an option.

p.s. In case of the bare nginx the first request is "problematic" since 
there won't be any cookie so it will always land on one backend and later if 
the cookie gets generated by backend application the user might get "moved" 
to a different backend server. (eg thatš why it is better to use a hash key 
like ip / url or browser agent header which is known to nginx immediately)


More information about the nginx mailing list