HAProxy: routing by Basic Auth credentials

credentialshaproxyload balancing

I have many requests coming in from a single IP with credentials supplied in the HTTP Header in Basic Auth format. Even though the origin is the same, the credentials vary frequently across requests.

This is an API that derives a lot of benefit from having an in-memory cache. For this cache to work, however, I need to be able to route requests with a particular set of credentials to the same machine.

This means I need to come up with a routing solution that somehow "sticks" a particular credential to a single machine for a set amount of time -say 30 minutes- but also distributes as-yet-unattached credentials in a round-robin fashion.

Is this possible with HAProxy?

Best Answer

Yes, HAProxy can balance on any request header sent by the browser. From the manual:

  hdr(name)   The HTTP header <name> will be looked up in each HTTP request.
              Just as with the equivalent ACL 'hdr()' function, the header
              name in parenthesis is not case sensitive. If the header is
              absent or if it does not contain any value, the round-robin
              algorithm is applied instead.

In case of Basic Authentication each request will be authenticated with an Authorization header, which takes the form of Authorization: Basic <base64(username+password)>. So in you HAProxy configuration the following should work:

 ...
 balance roundrobin
 balance hdr(Authorization)
 ...