Greatly improve the rate limit algorithm, so it is correct for a low

ticket to period ratio.
This commit is contained in:
Nils O. Selåsdal
2013-10-15 15:03:27 +02:00
parent 41bb24bb61
commit 763032fb04
2 changed files with 19 additions and 27 deletions
+7 -11
View File
@@ -34,12 +34,7 @@
*
* uc_ratelimit_init(&r,20, 1, time(NULL));
*
* NOTE. The the internals uses integer arithmetic to replenish the tickets,
* this can lead to greater errors estimating the available tickets the smaller
* the number of tickets is in relation to the period. The arithmetic is scaled
* by 1000 currently, so if ticket = 1 and period = 60, we get 1000/60 = 16. This
* should be 16.6667, which is an error of about 3.6%, which means we really just
* rate limit to 1 per 62 seconds.
* NOTE. period * tickets * 2 must not exceed the value of a long
*
* for (;;) {
* int fd = accept(..);
@@ -59,12 +54,11 @@ struct RateLimit {
//internal fields:
//scaled up number of tickets, to avoid floating point
//math
long scaled_tickets;
//how much each ticket is worth.
long ticket_cost;
//number of tickets we have (scaled up)
long available_tickets;
//money we have to "buy" tickets
long funds;
//time of the previos period
long last_ts;
};
@@ -72,6 +66,8 @@ struct RateLimit {
/**
* Initialize a struct RateLimit, which can hand out @tickets per @period
* the perioid must be in the same units as the current_ts
*
* NOTE. period * tickets * 2 must not exceed the range of the RateLimit.funds
*
* @param r RateLimit to initialize
* @param tickets number of tickets (bucket depth)