How to correctly use nbsrv with dynamic backend selection in HAProxy?

I’m trying to set up HAProxy to redirect traffic if a backend has no available servers. I’ve got the dynamic backend selection working, but I’m stuck on the nbsrv part. Here’s what I have so far:

frontend webfarm
    bind *:80
    acl NO_SERVERS nbsrv([BACKEND_NAME]) eq 0
    http-request redirect code 301 location http://backup.mysite.com if NO_SERVERS
    use_backend %[req.hdr(host),lower,map_dom(/etc/haproxy/backends.list,default_backend)]

The use_backend line works fine. It picks the right backend based on the host header. But I can’t figure out how to use the same logic in the nbsrv check. I want to count the servers in the dynamically selected backend.

Any ideas on how to make this work? I’ve tried a few things but nothing seems to do the trick. Thanks for any help!

yo, have u tried using a lua script for this? it can be pretty powerful for dynamic stuff. something like:

frontend webfarm
    bind *:80
    http-request lua.check_backend

the lua script u can do all the fancy logic. might be worth a shot if other methods arent cutting it

I’ve encountered a similar challenge with dynamic backend selection and nbsrv in HAProxy. One approach that worked for me was using a combination of ACLs and variables. Here’s a modified version of your configuration that might help:

frontend webfarm
    bind *:80
    acl is_domain hdr(host) -i -f /etc/haproxy/domains.list
    http-request set-var(txn.backend) req.hdr(host),lower,map_dom(/etc/haproxy/backends.list,default_backend) if is_domain
    acl NO_SERVERS nbsrv(be_%[var(txn.backend)]) eq 0
    http-request redirect code 301 location http://backup.mysite.com if NO_SERVERS
    use_backend be_%[var(txn.backend)] if is_domain

This setup first sets a transaction variable with the backend name, then uses it in both the nbsrv check and the use_backend directive. Make sure your backend names in backends.list are prefixed with ‘be_’ for this to work correctly.

interesting approach! have u considered using stick tables for this? they could help track backend status dynamically. wat about setting up health checks on the backends? that might simplify things. curious to hear if u’ve explored those options or if there’s a specific reason ur going this route?