Leastconn variant that considers group averages of inflight requests
Your Feature Request
As I understand it the current leastconn implementation in HAProxy is based on a completely instantaneous snapshot of the number of in-flight requests each backend server has. If the instantaneous number of in-flight requests is not high enough, this leads to weights having low accuracy - increasing a weight of a server group X might have basically no effect until you increase it by an amount large enough the server group X will start pretty consistently winning over 1 discrete in-flight request from another server group Y, which might already translate to a large load jump in group X and large load decline in group Y (especially with a cluster of HAProxy instances operating with same weights).
A toy example (but a miniature of what I encounter in production):
- HAProxy instance has itself on average 3 in-flight requests
- Backend server A has weight 5, backend server B has weight 2
Dealing with only instantaneous discrete values, you can not distribute 2 in-flight requests so that A has 5/2 times the in-flight requests B has and depending on how things play out in time this can end up overshooting or undershooting the desired proportions of in-flight requests between the servers by quite a large factor. However, you can distribute assigning in-flight requests over time so that A has on average (say over a minute) 5/2 times the in-flight requests B has. I think you can achieve this by keeping some kind of a moving average of in-flight requests for each server and then doing the request assignment on the basis of essentially floating point scores like (moving average of in-flight requests over last 100ms)/weight. While a single HAProxy in a single moment will still either put 1 in-flight request less or more to a given backend server, this could help the backend server get closer to having the desired number of in-flight requests momentarily from all HAProxy load balancers directing requests to it (since the distribution of in-flight requests over time will be different for each HAProxy).
What are you trying to do?
In a cluster of several load balancers with a large pool of backend servers, one load balancer having not that many in-flight requests in comparison to the number of servers, I am trying to make changing leastconn weights have a more gradual effect on the load of backend servers groups with given weight.
Output of haproxy -vv
HAProxy version 2.4.3-4dd5a5a 2021/08/17 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.3.html
Running on: Linux 5.10.0-1034-oem #35-Ubuntu SMP Wed Jun 23 09:55:56 UTC 2021 x86_64
Build options :
TARGET = linux-glibc
CPU = generic
CC = cc
CFLAGS = -O2 -g -Wall -Wextra -Wdeclaration-after-statement -fwrapv -Wno-address-of-packed-member -Wno-unused-label -Wno-sign-compare -Wno-unused-parameter -Wno-clobbered -Wno-missing-field-initializers -Wno-cast-function-type -Wtype-limits -Wshift-negative-value -Wshift-overflow=2 -Wduplicated-cond -Wnull-dereference
OPTIONS = USE_PCRE2=1 USE_PCRE2_JIT=1 USE_GETADDRINFO=1 USE_OPENSSL=1 USE_LUA=1 USE_ZLIB=1
DEBUG =
Feature list : +EPOLL -KQUEUE +NETFILTER -PCRE -PCRE_JIT +PCRE2 +PCRE2_JIT +POLL -PRIVATE_CACHE +THREAD -PTHREAD_PSHARED +BACKTRACE -STATIC_PCRE -STATIC_PCRE2 +TPROXY +LINUX_TPROXY +LINUX_SPLICE +LIBCRYPT +CRYPT_H +GETADDRINFO +OPENSSL +LUA +FUTEX +ACCEPT4 -CLOSEFROM +ZLIB -SLZ +CPU_AFFINITY +TFO +NS +DL +RT -DEVICEATLAS -51DEGREES -WURFL -SYSTEMD -OBSOLETE_LINKER +PRCTL +THREAD_DUMP -EVPORTS -OT -QUIC -PROMEX -MEMORY_PROFILING
Default settings :
bufsize = 16384, maxrewrite = 1024, maxpollevents = 200
Built with multi-threading support (MAX_THREADS=64, default=64).
Built with OpenSSL version : OpenSSL 1.1.1k 25 Mar 2021
Running on OpenSSL version : OpenSSL 1.1.1k 25 Mar 2021
OpenSSL library supports TLS extensions : yes
OpenSSL library supports SNI : yes
OpenSSL library supports : TLSv1.0 TLSv1.1 TLSv1.2 TLSv1.3
Built with Lua version : Lua 5.3.3
Built with network namespace support.
Built with zlib version : 1.2.11
Running on zlib version : 1.2.11
Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip")
Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND
Built with PCRE2 version : 10.36 2020-12-04
PCRE2 library supports JIT : yes
Encrypted password support via crypt(3): yes
Built with gcc compiler version 10.2.1 20210110
Available polling systems :
epoll : pref=300, test result OK
poll : pref=200, test result OK
select : pref=150, test result OK
Total: 3 (3 usable), will use epoll.
Available multiplexer protocols :
(protocols marked as <default> cannot be specified using 'proto' keyword)
h2 : mode=HTTP side=FE|BE mux=H2 flags=HTX|CLEAN_ABRT|HOL_RISK|NO_UPG
fcgi : mode=HTTP side=BE mux=FCGI flags=HTX|HOL_RISK|NO_UPG
<default> : mode=HTTP side=FE|BE mux=H1 flags=HTX
h1 : mode=HTTP side=FE|BE mux=H1 flags=HTX|NO_UPG
<default> : mode=TCP side=FE|BE mux=PASS flags=
none : mode=TCP side=FE|BE mux=PASS flags=NO_UPG
Available services : none
Available filters :
[SPOE] spoe
[CACHE] cache
[FCGI] fcgi-app
[COMP] compression
[TRACE] trace
I think I understand what you're trying to achieve, however I'm not convinced that averaging over time is the solution. Instead it seems to me that it should be averaged over a fixed number of samples so that the averages are respected.
I tried a little bit to see and found that the result is worse. E.g. spreading 10 connections over a weight of 2 and a weight of 5 respects them much less than before (18+81% instead of 27+73 for 29+71). Please try the attached patch if you want to play with it. 0001-EXP-fwlc-try-to-average-leastconn-over-a-number-of-s.patch.txt
@wtarreau I tested the patch with different window values but it did not seem to help. I understand that the patch averages the in-flight requests of the server over the last N times the server was selected, right? Why do you consider this superior to averaging over time?
To try to clarify my thinking, I am trying to fix two related problems:
- with relatively low in-flight request counts on the proxy it is impossible to distribute the requests among servers in proportion to weights
- when 1. occurs in a cluster of proxies, each proxy will bias the distribution of in-flight requests in the same direction - each proxy will overshoot some server groups with weights A, B, C, ... and undershoot some other server groups with weights D, E, F. Now the percentage error differs depending on the weight and the number of in-flight requests at the moment, so this can not be fixed by simple manipulation of the weights. For example adding some fixed +/- percentage of random jitter to the weights on each proxy does not help - it is not clear how much the weight D has to be increased to even have a detectable effect (eventually it will start winning over 1 more request in-flight from some other group?). It is as if there is some discrete number of states that can be achieved that is much smaller than the set of weight assignments possible, which is logical as the number of requests in-flight at any given moment is smaller than the sum of weights.
I was thinking it could be solved like this: each proxy tries to make the average of requests in-flight over X-ms on each server proportional to the weight (this is what I measure on the backend server when I want to know how well leastconn weights are respected), rather than trying to make the exact number of requests in-flight proportional to weight at all times. Possible this requires updating some value for all the servers every X/N ms? When the server is not selected, its average should gradually decrease. I am not sure if there is some clever indirect way to track this while updating only the state of a single server at a time.
In any case if this was implemented it should result in a single proxy sometimes overshooting and sometimes undershooting the instantaneous requests in-flight to any given server. Possibly the more often it switches between over- and under- the better, because the goal is for the overshooting from some proxies in the cluster and undershooting from other proxies in the cluster to balance out (at least partially, due to different request arrival times and server response times etc.).
Another possible idea to fix this would be a leastconn based on an in-flight request count returned by the backend server in response to the last request.
@wtarreau I tested the patch with different window values but it did not seem to help. I understand that the patch averages the in-flight requests of the server over the last N times the server was selected, right?
Yep!
Why do you consider this superior to averaging over time?
Because otherwise that will fail to even respect the slightest form of leastconn: it will mean that established connections will progressively fade away and count for less while still being there, so it will do the opposite of what is sought and result in stacking way more connections than acceptable on a server if some long-standing ones are there (think websocket or slow searches).
In addition there is a related problem to arranging them by time, which is that you cannot compare servers anymore since their arrangement will vary with time, thus you cannot even imagine efficient lookups. You'd have to scan all of them each time.
To try to clarify my thinking, I am trying to fix two related problems:
1. with relatively low in-flight request counts on the proxy it is impossible to distribute the requests among servers in proportion to weights
Sure but that is not related to the way they're counting but to the fact that you're trying to make discrete numbers (concurrent connection counts) perfectly match fractional numbers (weights). There is no way to accurately split any integral number between 1 and 6 as two parts of 2/7 and 5/7, so you cannot hope to have, say, 4 connections showing a perfect match on two servers with weights 2 and 5. However the current implementation still maintains the closest match (e.g. 27 and 73% for 28.5 and 71.5 theoretical for just 10 connections).
2. when 1. occurs in a cluster of proxies, each proxy will bias the distribution of in-flight requests in the same direction - each proxy will overshoot some server groups with weights A, B, C, ... and undershoot some other server groups with weights D, E, F. Now the percentage error differs depending on the weight and the number of in-flight requests at the moment, so this can not be fixed by simple manipulation of the weights. For example adding some fixed +/- percentage of random jitter to the weights on each proxy does not help - it is not clear how much the weight D has to be increased to even have a detectable effect (eventually it will start winning over 1 more request in-flight from some other group?). It is as if there is some discrete number of states that can be achieved that is much smaller than the set of weight assignments possible, which is logical as the number of requests in-flight at any given moment is smaller than the sum of weights.
It definitely is a discrete number, since this number is the number of connections. As you guessed, you can apply whatever constant factor you want to it, it's bijective and remains a set of discrete values.
I was thinking it could be solved like this: each proxy tries to make the average of requests in-flight over X-ms on each server proportional to the weight (this is what I measure on the backend server when I want to know how well leastconn weights are respected),
Be careful, if you're measuring them over time, you're already not doing leastconn anymore, you're doing something closer to round robin. Maybe leastconn is not what you need in the end. It's not always trivial to pick the best method for a given workload and it can change over time as the infrastructure evolves. If your problem is that you're dealing with a distributed load balancer (multiple LB nodes targetting the same servers), it's possible that random() is better instead (it's actually a P2C, defaults to 2 draws, but you can change the number). It could look better on a large scale.
rather than trying to make the exact number of requests in-flight proportional to weight at all times. Possible this requires updating some value for all the servers every X/N ms?
That's not even imaginable, it would be both extremely expensive and always outdated.
When the server is not selected, its average should gradually decrease. I am not sure if there is some clever indirect way to track this while updating only the state of a single server at a time.
What you're describing is exactly round robin.
In any case if this was implemented it should result in a single proxy sometimes overshooting and sometimes undershooting the instantaneous requests in-flight to any given server.
Just to be clear, I'm fine with the possibility of providing tunables allowing to slightly over/under shoot. I'm even wondering if it couldn't be achieved by adding noise in the measurement. We could imagine having a configurable noise level that is a ratio of connections that is added to each server's index. For example 100% would randomly add the equivalent of 0 to 1 connection, 200% would add 0 to 2 connections etc.
But that should end up being very close to P2C in the end. Could you please give "balance random" a try, changing nothing else ?
Also please try the attached which adds 0 to 1 connection to the measurement, and try adding a factor to the argument to statistical_prng_range() if needed. In its current form for 10 conns over weights 2 and 5 I'm seeing a max of 3 and 8 respectively, which means it managed to slightly overshoot each server by one at least once. And the distribution remains excellent.
0001-EXP-fwlc-add-noise-to-connections-when-requeued.patch.txt
@wtarreau I tried both random(2) and leastconn + the patch with adding noise to connection count, but neither showed much of an improvement over plain leastconn. We are in general pretty happy with leastconn, except the proportion of in-flight requests between groups of servers with same weight are off by 10%-20% in comparison to the weights and its always a fight to keep the cluster small to not make this worse. I did a lot of tests on this and also build some simulations, based on this I think random(2) suffers similar issues as leastconn with relatively low in-flight requests counts. The bias depends on both the specific weight and the given number of requests at the specific moment so it seems it cannot be corrected by some numeric factor that is not somehow dependent of those variables.
I came up with one more idea to try to improve this, hopefully more realistic than my previous one, its a small variation of leastconn - let me know what you think:
- Group servers by weight
- Keep track of the sum of in-flight requests currently processed by all servers in each group
- When picking a server for a request, first pick a group: the one for which
(sum of in-flight requests on servers in the group) / (weight of servers in the group * number of servers in the group)is lowest - (This is like picking the group with the lowest average of
in-flight requests / weighttaken across servers in the group) - Then within the group pick the server with lowest number of in-flight requests (just plain leastconn but only among servers with same weight)
I analysed this a bit, simplifying things by ignoring the passage of time, just looking at how a batch of N items arriving all at once would be distributed by which algorithm. If A, B, C are descending weights and a b c is the number of servers with given weight, plain leastconn would distribute like this:
- make sure all
aservers with weightAhave 1 req - make sure all
bservers with weightBhave 1 req - make sure all
cservers with weightChave 1 req - make sure all
aservers with weightAhave 2 req - ...
If A, B, C, ... do not have common divisors, the requests can be distributed ideally according to weights only when the number of requests is a multiple of A*a+B*b+C*c+.... If they cannot be ideally distributed, there is a reminder and remainder is distributed so that first one more request is put on all servers with weight A, then to one more request is put on all servers with weight B etc. until requests run out.
The variant I described would aim for making the group averages be in A:B:C proportion, so given the number of requests is 2*A*a + B*b + C*c it should end up in a state where:
- group
Areceives close to(A/ABC) * (2*A*a + B*b + C*c)requests - group
Breceives close to(B/ABC) * (2*A*a + B*b + C*c)requests - group
Creceives close to(C/ABC) * (2*A*a + B*b + C*c)requests - ...
In this case the remainder should be distributed among the groups in proportion to the weight of given group. Since there is not enough requests on one proxy to get the counts on all servers correct, some servers within the group will have a higher request count, some lower, but hopefully within the cluster a single given server will have a "high" from some proxies and a "low" from some other proxies and it can cancel out to some extent to get closer to the right number.
But what you describe above is very close to how it's working right now. The servers are sorted along keys equal to conn/weight, thus they implicitly constitute groups.
The problem you're facing is not when connections are kept, but the fact that they're very ephemeral, and that the algorithm takes care of always going to the least loaded server, even if it had lost its load only one microsecond ago. I really think that the "problem" in your case is that the traffic is bursty, thus you release many slots at once and take as many at once, it's between the leastconn and the roundrobin case. Our leastconn also performs roundrobin between all servers having the same key (conn/weight), but that doesn't help in your case because I think that most of your connections are too short in time.
Maybe we're attacking the problem from the wrong side and we should consider modifying roundrobin instead. First, by using RR instead of leastconn, I'm seeing that while the amount of in-flight request is not taken into account, the distribution of total and max reached follow the weights very closely. You can even try to make it slightly prefer low-conn servers to high-conn servers by adding a small offset based on the number of connections:
--- a/src/lb_fwrr.c
+++ b/src/lb_fwrr.c
@@ -264,6 +264,7 @@ static inline void fwrr_remove_from_tree(struct server *s)
static inline void fwrr_queue_by_weight(struct eb_root *root, struct server *s)
{
s->lb_node.key = SRV_EWGHT_MAX - s->next_eweight;
+ s->lb_node.key += 10*fls_auto(_HA_ATOMIC_LOAD(&s->served) + _HA_ATOMIC_LOAD(&s->queue.length));
eb32_insert(root, &s->lb_node);
s->lb_tree = root;
}
@@ -363,6 +364,7 @@ static void fwrr_queue_srv(struct server *s)
*/
s->lb_node.key = SRV_UWGHT_RANGE * s->npos +
(unsigned)(SRV_EWGHT_MAX + s->rweight - s->next_eweight) / BE_WEIGHT_SCALE;
+ s->lb_node.key += 10*fls_auto(_HA_ATOMIC_LOAD(&s->served) + _HA_ATOMIC_LOAD(&s->queue.length));
eb32_insert(&grp->curr, &s->lb_node);
s->lb_tree = &grp->curr;
This seems to make it slighty smoother in my tests.
@wtarreau I really think there is a significant difference in the variant of leastconn I describe. Again for simplicity consider starting with 0 in-flight requests and consider what happens if some number of requests arrive and no requests yet get completed. Traditional leastconn has to complete filling each server within one "group" with one more request, before it proceeds to filling another "group" with one more request, disregarding how much the group as a whole, its sum of in-flight requests over all servers, deviates from the groups weight. Its like its putting the requests in group-by-group - 1st in-flight request for all servers in group A, 1st in-flight request for all servers in group B, and so on. If A is the smallest weight, no server from another group can be chosen until all servers in group A get their request assigned, because 1/A will keep being the smallest score. So it prioritises keeping the servers equally loaded within the group over keeping the group sum of in-flight requests in proportion to the group weight.
This is a problem in a cluster because all proxies have around the same number of in-flight requests and all will be in the same stage of the process, they will have x requests on group X, y requests on group Y, ..., and be busy filling in the z+1 request on group Z with some servers having z requests and some already z+1.
This might seem too much of a simplification, because all servers complete requests, so if you consider the dynamic behaviour, you of course send requests to all servers. However, the proxy itself has some relatively stable number of average in-flight requests, meaning its average state over time will be like I just described. Since this number of in-flight requests on single proxy is low, there will be bias and the bias will be very similar for each proxy with no chance to cancel out.
I think the slight variation I described would invert the priority, it would prioritise alternating between the groups, trying to keep the group averages equal. This would be advantageous in a large cluster of load balancers, because the variance between servers within same group can balance out across the proxies in the cluster. With a single load balancer and lots of in-flight requests it would probably not change much. Of course there might also be cases where its detrimental.
I tried round robin, this makes it possible to more easily control the group averages by changing the weights, but it causes huge variation within groups and would make it necessary to have many more groups, to factor-in more differences between servers into the weights.
Overall leastconn has done a good job for us and anything else so far only seems worse, the only issue remaining is that the group averages being 10% to 20% off compared to the weight, but the variance within the group is very low, which is a nice thing. If we could have slightly more variance within the group, but have each group better hit its the weight, it would overall be beneficial, because ultimately we want all servers to operate within the same %CPU bounds and as narrow possible, so its the lowest width of max-min range that we want. So as a made-up but production-inspired illustration traditional leastconn results in this:
Group A: [75%,80%]
Group B: [65%,70%]
Group C: [85%,90%]
(low variance within group, but less than perfect accuracy in taking weights into account)
Round robin results in this:
Group A: [60%,80%]
Group B: [60%,80%]
Group C: [60%,80%]
(high variance within group, high accuracy in taking weights into account)
My hope is modified leastconn could achieve this:
Group A: [70%,80%]
Group B: [70%,80%]
Group C: [70%,80%]
(moderate variance within group, high accuracy in taking weights into account)
@wtarreau I implemented and tested such a group-based variant of leastconn, I hope I can convince you to have a look because it seems to be working very well for us in production.
Here is the patch:
0001-New-leastconn-variant-least-connected-within-least-c.patch.txt
Here is the difference this makes in production, the left side is leastconn, the right side leastconngr:

Those are load averages of whole groups of servers sharing weights on HAProxy and sharing hardware config. The weights were picked weeks ago by having one representative server from each group disconnected from all but one load balancer and by toying with the weights on this single load balancer until the loads on the servers get more or less equal. Basically how much closer the loads are now reflects how much closer the inflight requests got to the proportions specified to the weight (I also monitor the number of inflight requests directly, but a graph would not be as telling). The within-group variance in load or in inflight requests did not increase. Its definitely still a leastconn in that the number of inflight requests on each server is very stable.
Here you will find the patched version of HAProxy, but in lbtest/ directory you will also find a set of scripts for running a local test comparing leastconn and leastconngr. The scripts assume you run make in RTBHOUSE/haproxy root directory, and then cd to the lbtest directory. Afterwards you can do the following:
./start_proxies.sh leastconnwill start 6 haproxy instances listening on ports 10000...10005, with stats pages on ports 11000...11005../start_servers.shwill start 20 workers on ports 12000...12019. The workers are in Python 3 and respond with the number of inflight requests they currently have on them from all proxies. Their response time is linearly proportional to the number of inflight requests (they sleep for 50ms * number of inflight requests before responding). The last point is important because the fact that a server that has more connections typically responds slower is what I believe makes the mutual cancellation of errors made by different proxies possible/probable../start_wrk.shwill start sending requests to all proxies at once using 6 instances ofwrkcurl localhost:12000will show how much inflight requests the worker on port 12000 has so one can check how the collective current action of the whole cluster of proxies on this server reflects the weights
With./start_proxies.sh leastconn I get those results:
- workers with weight 5 - around 7 in-flight requests
- workers with weight 9 - around 19 in-flight requests - (19/7)-(9/5) = 91% too many in comparison to the weight
- workers with weight 11 - around 25 in-flight requests - (25/19)-(11/9) = 10% too many in comparison to the weight
With ./start_proxies.sh leastconngr I get those results:
- workers with weight 5 - around 13 in-flight requests
- workers with weight 9 - around 19 in-flight requests - (19/13)-(9/5) = 34% too little in comparison to the weight
- workers with weight 11 - around 22 in-flight requests - (22/19)-(11/9) = 6% too little in comparison to the weight
That is just an example, of course results vary with the number of proxies, the number of servers, weights etc., I picked the specific numbers based on my simulations but it isn't just some very specific pathological example. I think generally as long as you have multiple proxies sending requests to the same servers and the servers come in larger groups with the same weight, leastconngr will track the weights much closer. I established this not by means of this example but by experiments in production which I can't share in public, I just built this to illustrate the issue. Looking at the stats page while the test is running gives some intuition about how the algorithms are different...
Hi Jaroslaw,
I'm really confused now, because 1) the description in the first two paragraphs does not correspond at all to how leastconn works and 2) it's not clear to me exactly what your graph tries to represent, it seems to me that all your machines are equally loaded which might not be expected if they're having different weights. I'm seeing that the calculations you're doing at the end have some errors, which makes me wonder if we're discussing the same thing.
Note, to be clear, rest assured that I have nothing against adding new LB algos that work better in field for various use cases, quite the opposite, it's just that I don't want to redo differently something that already exists or that does not match what we're tring to do, or maybe works due to an analysis mistake. That's why I want to dig deeper into this with you.
I've had a look at your lbtest config. You have:
- 5 servers with a weight of 5
- 5 servers with a weight of 9
- 10 servers with a weight of 11 The total capacity of your farm is thus 180 (55+59+10*11).
As such:
- each server among those with a weight of 5 ought to receive 5/180 of the load
- each server among those with a weight of 9 ought to receive 9/180 of the load
- each server among those with a weight of 11 ought to receive 11/180 of the load
In the first test, you're seeing an average of around 57+519+10*25 = 380 in-flight requests, thus:
- servers of weight 5 ought to see 5/180*380 = 10.5 in-flight requests (you're seeing ~7)
- servers of weight 9 ought to see 9/180*380 = 19.0 in-flight requests (thus it's exactly valid)
- servers of weight 11 ought to see 11/180*380 = 23.2 (you're seeing ~25)
So I think it's working as expected, and the "91% too many" is a mistake in the way to calculate it because you seem to subtract only those of lower weight. That does not make sense since a server's frequency does not vary based on the presence of other servers of lower frequencies!
In the second test with the different algo, you're seeing values which are a bit different but show the exact same error compared to the theoretical ones, those with weight 5 take 1.3 times more instead of 1.3 times less, and those of weight 11 take 7% more instead of 7% less, and those of weight 9 take the exact theoretical ratio, so roughly the distribution is different but the error is the same.
As such it's not clear to me how you'd expect weights to work but weights correspond to a capacity. Think about using the CPU's MHz for a simplification. If you'd add a 6th server of weight 5, the total capacity would grow from 180 to 185, and that server ought to take 5/185 of the load = 10.2 connections.
The sorting key right now precisely is the in-flight requests divided by the weight. This guarantees that at any time the first server is always the one having the lowest such ratio, i.e. a server becomes less interesting once there it another one with less requests or higher weight (or both) so that its inflight/weight is lower. This guarantees this fair distribution regardless of any form of grouping.
Maybe that some artefacts you're seeing are caused at lowest loads by the "+1" on in-flight, which we use in a predictive way ("what will be the new key if this server takes a connection"). Or maybe in your test your weights are too different based on the differences of server capacities. But at this point I don't understand (even by reading the code) how the group-based approach solves any such thing nor improves the situation. Will the addition of a single server of weight 100 properly take 100/480 of the load in your case ? Will the addition of 20 servers of weight 5 result in the same, spread over all of them, without disturbing the other ones ?
I'm fine if you're telling me that you expect different behaviors, it would just indicate that you've observed some metrics of behaviors that are worth being considered and deserve to be offered as an option, and I'm perfectly fine with this. It's just that I would like to be sure that we're speaking about the same thing and for me it clearly is not exactly the case above based on how we perform our calculations. At least now with this test I'm sure both of us are talking about in-flight requests, because at some point I was wondering if you were talking about total distributed requests :-)
@wtarreau I have not been very clear, I will try to explain:
There is a total of 360 inflight requests at all times: there is an instance of wrk for every HAProxy instance, wrk is configured to keep 60 connections open, and it sends requests synchronously over each of those connections. There was a logical error in my test server, by not having a separate endpoint for querying the inflight requests that doesn't bump the inflight counter, all results got biased by an extra +1, I think this is why you arrived at 380 from the numbers I reported. I now added /inflight for querying the in-flight counter without incrementing it and repeated the test, hence slightly different numbers will come below.
I agree that the way of calculating error that results in 90% is confusing. However, it is compatible with what you described: if server B ought to receive 9/180 of the load, and server A ought to receive 5/180 of the load, then the ratio of load on B to the load on A should be (9/180)/(5/180)=(9/5)=1.8, but in reality the ratio is 19/7=2.7. Server B should receive 1.8 times the load what server A receives, but instead it receives 2.7 time the load A receives, 2.7-1.8=0.9, hence 90%: 90% of the number of requests A receives is the excess load on B. This is only to explain my original calculations, I agree this is not a very clear way of assessing the error.
Here are the results calculated like you suggested and with the corrections I mentioned above:
perfect: 5/180*360 = 10.0 leastconn: 6 leastconn/perfect: 0.6 leastconngr: 11 leastconngr/perfect=1.1
perfect: 9/180*360 = 18.0 leastconn: 18 leastconn/perfect: 1.00 leastconngr: 18 leastconngr/perfect=1.00
perfect: 11/180*360 = 22.0 leastconn: 24 leastconn/perfect: 1.09 leastconngr: 21 leastconngr/perfect=0.95
Average error for leastconn: 0.1 # abs(1-[(0.6+1.0+1.09)/3])
Average error for leastconngr: 0.01 # abs(1-[(1.1+1.0+0.95)/3])
leastconngr really is more accurate (in this test and in a cluster setup like lbtest).
With 45 connections from single wrk, there are 6*45=270 inflight requests and the result are as follows:
perfect: 5/180*270 = 7.5 leastconn: 6 leastconn/perfect: 0.80 leastconngr: 7 leastconngr/perfect=0.93
perfect: 9/180*270 = 13.5 leastconn: 12 leastconn/perfect: 0.88 leastconngr: 13 leastconngr/perfect=0.96
perfect: 11/180*270 = 16.5 leastconn: 18 leastconn/perfect: 1.09 leastconngr: 17 leastconngr/perfect=1.03
Average error for leastconn: 0.08 # abs(1-[(0.8+0.88+1.09)/3])
Average error for leastconngr: 0.03 # abs(1-[(0.93+0.96+1.03)/3])
Why should the group based approach improve anything? I encourage you to run the test with both algorithms and while the test is running to keep refreshing the HAProxy stats page and to keep looking at the inflight numbers on the servers. With leastconn you will keep seeing the same numbers on the same servers on every HAProxy instance at all times, its nearly static. There is bias due to the insufficient number of inflight requests on the proxy, the bias causes overload of some weights and underload of others. Since all proxies have roughly the same number of inflight requests and same configuration of backend servers, they will all make the same error and the relative error of the whole cluster will be the same as the error of a single proxy. The stats page just shows something close to a partitioning of an integer according to weights. This is isn't the best you can do because the cluster has more requests than a single proxy has and the server response time can act as a mechanism that synchronises the actions of the proxies to some extent.
So in leastconngr, a single proxy will have lower than perfect number of inflight requests to some servers in each group but the group themselves will be almost equally affected by this (since we try to keep the group averages of inflight requests equal between groups). This in-group error can then to some extent cancel out across the cluster - if some proxies leave some servers within the group underloaded, then those servers will respond faster, and have a lower chance of also being the ones having the lower numbers on remaining proxies - the errors of individual proxies can cancel each other.
Finally, regarding the graph from production: the graph shows the Linux 1m load average divided by the number of physical cores the given server type has, so it is a measure of utilization, 1.6 is roughly like 80% cpu utilization. I know from tests that servers of type A need X inflight requests to be 80% utilized, while servers of type B need Y inflight requests to be 80% utilized and so on. I use those numbers X, Y, ... of inflight requests needed to hit 80% utilization as the leastconn weights. If the actual inflight requests on our servers were like the "perfect" values in our calculations the utilization should become nearly equal for all server groups. This is what happens if a single server from each group is put into a single load balancer with the same weights and with leastconn. So, the convergence of the those load/cores values towards the same equal value indirectly shows how the leastconngr/perfect error is much lower than the leastconn/perfect error in our production environment. In retrospect I realize this could all sound quite confusing, but I still think the whole concept is sound. In any case if lbtest makes sense, know that we basically did something like lbtest in a real cluster with multiple proxies and a lot of servers.
@wtarreau I modified ./start_wrks.sh so that it accepts as argument the number of connections it should set up to a single proxy. I added benchmark.sh which is started like this:
./benchmark.sh 10 120 5
10 is the initial number of connections per proxy to set up, 120 is the final number, 5 is the increase step between test runs. The script will probe one worker server from each group a few times, it will average the results so the numbers are more precise, do the calculations I did by hand above and print the results. I captured the results of ./benchmark.sh 10 120 5 for leastconn and leastconngr in files called leastconn and leastconngr. benchmark_results.ipynb is a jupyter notebook I created for plotting the results. This is the result of plotting actual/perfect for each weight as a function of the number of connections and for both algorithms:

(The Y-axis is shared between the two plots)
Thank you for the detailed explanation @jaroslawr. The root of this thing is burried in one of your sentences above, it can be summed up as : with low connections counts, the imprecision resulting from integral numbers of connections that would affect each of the servers previously is now the same for a whole group instead of a single server, thus by being spread over multiple servers, it's smoothed.
I'll continue to look into it closer. I really want to see if there are any corner cases where it's not as good as the current one, in terms of instant and mid-term distribution, CPU usage or scalability. We need to check the impact of server weight changes (e.g. slowstart and up/downs). If it's at least as good as the current one in every aspect, instead of adding a new algo we could simply replace the existing one. If there are tradeoffs to be made, then we'll see.
An alternative approach that should yield the same results would likely be to just keep a cumulated error that would be used to correct the key over time, but that's likely what you initially wanted with the to try when you suggested to smooth the measure over time. The only problem is that there isn't such a thing as a measurement error when picking a value from the tree but probably that we can make one up by looking at the fractional part of inflight*(srvweight/srvweight) which would then be subtracted from the key each time it goes over 1.
@wtarreau Cool, thanks for the patience with this! Now that the general picture is clear, I have a few minor points of note about the patch and the tests I did and didn't do:
-
I had one doubt with my implementation: I calloc() and free() the fwlcgr_group structure inside the lbprm lock and I was wondering if this isn't too heavy especially in tricky situations like the ones you just mentioned, e.g. slowstart with some servers flapping, where groups could potentially form and disform more often. I was thinking of doing it out of the lock and doing some double checking but this started looking too "smart" for my multithreading skills in C so I gave up on it. Now I think you could just preallocate 2 groups (one active and one backup) for each of the 256 possible weights and only move the groups in and out of the trees without any allocations.
-
I have not tested behaviour of backup servers or the allbackup option because we don't use this in the cluster I created this for. I can spend some more time on it if/when you decide the patch can move forward. I tested healthcheck transitions but not slowstart - similar story.
-
On the other hand the patch, after some preliminary smaller scale tests, ran on our production cluster for a full day, so it sustained substantial requests/s without noticeable increase in HAProxy CPU usage. I monitor within-group variance in the number of inflight requests, and for individual servers I monitor not only minute averages of inflight requests but also within-minute std dev of inflight requests (which seems to have decreased when the patch was deployed), so the smoothness aspect of it looks pretty solid also outside the synthetic test. I don't claim this is the ultimate answer to all such possible issues but it is a pretty serious battle test.
So I studied a bit closer the algo and what it does is find the first group and within it the first server. Thus this can be done with a unique key because the group is the high part of the word and the server the low part. We're back to what we were saying earlier in this thread, but with a different and more precise view now. Right now you're using 64 bits to store the group key, we can simply shrink it to 32 bits and make it the 32 topmost bits of a 64-bit key, and keep the per-server value in the lower 32 bits. This way a single tree node is needed for each server and there's no need for a key for the group. It should work because each pickup should result in the exact same server as the one that would have been picked using the two-tree method. I'll eventually run tests with this but for now I'm trying to port your test setup here on my test machines so that we can discuss about the same things.
Regarding malloc/free, they're clearly frowned upon, even more under a lock! We could have a pool for this and allocate out of the lock, even if it means releasing on exit if not needed. But if we can get the thing to work with a single tree, then we don't need sorting between the groups anymore and we can simply declare an array of the 4096 possible weights for which to keep a group structure.
In my tests on 16 threads, I notice a ~5-10% performance loss due to the increased overhead of manipulating two trees. This one could disappear if a single tree approach works. A few months ago I worked on a reimplementation of leastconn that would be compatible with multiple thread groups, and that's also something to keep in mind, as we definitely want this to nicely scale.
@wtarreau How would you deal with computing the group key if it had to fit in 32 bits? Before I got this to work reasonably well I struggled a bit with this. The leastconn_tree for the groups is 64-bit because I do this:
group->leastconn_node.key = (((uint64_t) group->inflight) << 32) / (group->size*group->weight);
I tried other ways of computing the key but the distribution then ended up not as good as now. Plain leastconn can use the fact that the weight is known to fit in certain bounds, but here the group size is an additional factor... Actually I was now reminded I had an idea of having an EB-tree for fractions, where nominator and denominator are stored separately as 32-bit numbers and where you do a 64-bit calculation during sorting, using the fact that a/b>c/d if and only if ad>bc, so a, b, c, d can be 32-bit datums in the tree node, but during insertion or lookup you can compute uint64_t ad = a*d, uint64_t bc = b*c and do the comparison itself without any error.
Putting the ideas together you could dedicate 32-bits to group_size*group_weight, 16 bits to group_inflight and 16 bits to server_inflight. The node would be 64 bit and the tree would need to have some extra logic for doing the comparisions.
Am I overcomplicating this, do you see a simpler way?
I finally found a way to emphasize the problem you're describing, @jaroslawr , using a single haproxy process. The astuce consists in injecting a number of connections that is an exactly integral multiple of the total number of the number of servers. I monitor all servers at once 10 times per second with this:
$ while sleep 0.1; do echo $(for p in {12000..12019}; do curl -s 0:$p/inflight;done);done
With 30 connections and the original leastconn I get this:
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
This is not great for 55, 57 and 10*11, as it's visible here that 5 & 7 get exactly 1 connection vs 2 for 11.
With yours I get this:
1 1 0 1 1 2 1 1 1 2 2 2 2 2 2 2 2 2 2 1
1 1 1 0 1 1 1 2 2 2 2 2 2 1 2 2 1 2 2 2
1 0 1 0 1 2 1 2 2 2 1 2 1 2 2 3 2 2 2 2
0 1 1 1 0 2 1 2 1 1 2 2 2 2 2 1 2 2 2 2
1 1 1 0 1 1 2 2 1 2 2 1 1 2 2 2 2 1 1 2
1 0 1 0 1 2 1 2 2 1 2 1 2 2 2 2 1 2 2 2
1 0 1 1 1 2 1 1 2 2 2 2 2 2 2 2 2 2 1 2
1 1 1 1 1 2 2 1 2 2 1 3 2 1 2 1 2 2 1 2
It's less regular but over time it's of course better.
With 60 connections it's even more visible:
--leastconn--
1 1 1 1 1 3 3 3 3 3 4 5 4 4 4 4 4 4 3 4
1 1 1 1 1 3 3 3 3 3 4 4 4 4 4 4 4 5 4 4
1 1 1 1 1 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4
1 1 1 1 1 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4
1 1 2 1 1 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4
1 1 1 1 1 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4
--leastconngr--
2 1 2 2 2 3 3 4 2 3 3 4 3 4 3 3 4 3 4 4
1 2 2 2 1 3 3 3 3 3 3 3 4 4 4 4 4 3 4 4
2 2 2 2 2 3 3 3 3 3 4 3 3 3 3 4 4 3 4 4
2 2 2 2 2 3 3 3 3 3 3 4 4 4 3 3 4 4 3 4
1 2 2 2 1 4 3 3 2 3 3 4 3 4 4 4 4 4 3 4
2 2 2 1 2 3 3 3 3 3 4 3 4 3 4 3 4 4 4 4
2 2 1 2 2 3 3 3 3 3 4 4 3 4 3 3 4 3 4 3
1 2 2 2 2 3 3 3 3 3 3 3 4 3 4 4 4 4 3 3
One could argue that leastconn is more stable than leastconngr and avoids overshooting on low-capacity servers but it's obvious that this results in a not so good distribution with so few requests in flight.
I need to think a little bit more about it. What you're calculating above is just a fraction. It's the number of inflight requests divided by the sum of the weights in the farm, scaled by 2^32. So that gives a number of inflight request by units of server weight. The dynamics of this metric is not huge, it roughly varies linearly with a single server's capacity. Thus you don't care about too low values. For example you would want to be able to represent with a moderate accuracy that you're keeping 1 million connections on a single server, because those running in active-backup modes may very well face this when they have leastconn in their defaults section. But they don't care about the last bits. And those with only 10 requests spread over 5 servers of weight 200 will not care whether it's group 200 or group 195 that takes the next request, so the 10/1000 or 10/975 will be roughly identical.
As such I think we could find an inflexion point and represent the key three ways:
- as a 0..1 ratio of
inflight/global.maxconnthat is multiplied by 2^64 and divided by sum_weights. This gives the high part, we just have to add the server's key. - as a square root of the current value, that always fits into 32 bits and is still monotone
- as a scaled log2 of current value, that is always monotone as well and takes even less bits (but is likely faster to compute).
But I'm getting increasingly convinced that simply keeping the lost carry in the computations for next time should be sufficient, as you initially wanted to do. Now that I'm having an easy reproducer I can experiment.
@wtarreau Update from my side:
-
I changed my implementation to use preallocated groups and tested it in production again, here is the patch: 0001-New-leastconn-variant-least-connected-within-least-c.patch.txt
-
I think it is not possible to use a single tree for both the groups and the servers or at least I do not understand how to do it. It is possible to fit the group key and server key in a single word, but whenever a server acquires a connection, all servers in the group would need to be re-positioned in the tree because the group part of the key should change for all of them (position of the group changes whenever any of the servers in the group acquire or release a request).
-
I did some more tests in a slightly more systematic way. I modified the benchmark scripts so it queries a random server from each group some N times so the results should also be more accurate.
Results with 5 proxies and 3 distinct weights (weights: 5, 7, 9; 5 servers for each weight):

Results with 10 proxies and 3 distinct weights (weights: 5, 7, 9; 5 servers for each weight):

Results with 5 proxies and 5 distinct weights (weights: 5, 7, 9, 11, 13; 5 servers for each weight):

Hi @jaroslawr,
glad you sent this update, as I was about to go back working on it.
* I changed my implementation to use preallocated groups
Cool, I thought about it as well. I'm a bit worried about the amount of RAM it can take (128kB per backend, that becomes a lot for those with many backends, we've seen configs with 100k+ i.e. 12GB of static RAM). I think that pools with group nodes might work better (something closer to your previous patch but using pool_alloc() / pool_free() instead of malloc/free).
and tested it in production again, here is the patch: 0001-New-leastconn-variant-least-connected-within-least-c.patch.txt
I'm more and more convinced we'd rather merge it as a replacement for the current leastconn algo. I think it's acceptable to take a small performance hit as long as there are still options (e.g. random) for those who with to keep the absolute highest performance level. Because with leastconn, the fairness of the traffic distribution is probably more important than with several other algos (often long-lived connections).
As such, could you please try to modify the existing leastconn with your work (i.e. rename your files lb_fwlc* and run the diff again) ?
* I think it is not possible to use a single tree for both the groups and the servers or at least I do not understand how to do it. It is possible to fit the group key and server key in a single word, but whenever a server acquires a connection, all servers in the group would need to be re-positioned in the tree because the group part of the key should change for all of them (position of the group changes whenever any of the servers in the group acquire or release a request).
I came to the same conclusion after my several failed attempts above, and hoped to find a solution but apparently there is none. I could demonstrate it in my head by the fact that the groups impact all servers of the same group at once, and that if the key is only calculated when the server is repositionned, it's not considered anymore when the server is picked. A variant could have consisted in recalculating the key when a server is picked and optionally repositioning it if not the best one anymore, but 1) it would still skew the calculation, and 2) there are degenerate cases where we'd have to evince a large number of servers, which costs even more CPU. What I'm trying to keep in mind is that these "groups" are not exactly groups of servers, but just groups of values which do not divide each other well and which, once grouped, give larger ratios that help diminishing the rounding error by the number of servers sharing the same value. I've been wondering if it would not be enough to use a list of servers inside a tree node for the group's total load (push at the head when releasing a server, push at the tail when releasing it), but that wouldn't cope perfectly with fast variations like a server being restarted and leaving all of its connections.
* I did some more tests in a slightly more systematic way. I modified the benchmark scripts so it queries a random server from each group some N times so the results should also be more accurate.
No doubt the results are better, and that's why I'd prefer to simply replace the existing algo with yours in 2.5. Please just revisit your patch regarding the points above and do not hesitate to tell me if you need any form of help (I didn't propose because I noticed from your patches that you were particularly autonomous on this, but do not be shy if needed)!
@wtarreau Here is the patch after implementing your suggestions: 0001-Improve-accuracy-of-weights-with-leastconn-load-bala.patch.txt
I have only one doubt: I don't know what should happen if pool_alloc fails, I just return for now.
(I tested this locally, after it looks good to you I would test some more in production again)
At first glance it seems to look fine. I'll have to look closer at the pool_alloc() tomorrow, I think we need to return NULL and make sure we haven't started moving the server. Thanks Jaroslaw!