Section 19.4.3

Fixed-point units and fractional-refill loss

Definition

Fixed-point units are equal fractions of a quantity, fixed in advance, in which the quantity is counted as a whole number: with 4 units per token, the integer 3 means exactly three quarters of a token. Fractional-refill loss is a counting error in a rate limiter §9.38 whose credit, counted in tokens, grows with elapsed time: each update rounds the newly earned credit down to whole tokens, discards the fraction and records the current time, so the fraction is never credited. Fixed-point units, or a carried remainder, prevent the loss.

The idea

A token bucket §19.4.1 is a common rate limiter: a counter of credit, called tokens, that grows at a fixed rate up to a maximum, and from which each request spends tokens. Suppose the bucket must earn one token every 4 ticks, where a tick is one period of the system timer, the unit in which the operating system counts time. An obvious implementation runs this update whenever a request arrives: take the number of ticks elapsed since the stored timestamp, divide it by 4 with integer division, which keeps only the whole part of the quotient, add that number of tokens, and store the current time as the new timestamp.

Called once after 4 ticks, the update earns 4/4=14 / 4 = 1 token, as intended. Called on every tick, each call sees 1 elapsed tick, earns 1/41 / 4 of a token, which integer division turns into 0, and still moves the timestamp forward. The quarter token earned in that tick is gone for good. Four calls earn nothing, and so do four million. The rate the bucket grants now depends on how often requests arrive, not on how much time has passed, and a source that sends a request on every tick never earns a single token: its legitimate requests are refused forever.

The repair is to keep the fraction: count credit in quarter tokens, so that one tick earns exactly one unit, or carry the leftover ticks into the next update. Either way the credit depends only on elapsed time.

How it works

Both repairs use integer arithmetic only, which is exact and suits small processors without hardware for fractional numbers.

Repair 1: fixed-point units. Let the rate be p/qp / q tokens per tick, where pp and qq are positive integers.

  1. Choose a scale SS, the number of units in one token, so that one tick earns a whole number of units, a=Sp/qa = S p / q. The simplest choice is S=qS = q, which gives a=pa = p.

  2. Store the bucket level, and the capacity (the largest level allowed), in units.

  3. Convert every cost to units once, by multiplication: a request that costs cc tokens costs cSc S units.

  4. On each update, read the current time from a monotonic clock §9.35 (a clock that never runs backwards), compute the elapsed ticks Δ\Delta since the stored timestamp, add Δa\Delta a units, limit the level to the capacity, and store the current time.

  5. Admit a request when the level is at least its cost in units, and subtract the cost.

No step divides, so no fraction is discarded.

Repair 2: carry the remainder. Keep whole tokens, but carry forward the part of the elapsed time that did not yet make a whole token. With one token per 4 ticks, an update computes k=⌊Δ/4⌋k = \lfloor \Delta / 4 \rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down to a whole number, adds kk tokens and advances the timestamp by 4k4k ticks instead of setting it to the current time. The Δ−4k\Delta - 4k leftover ticks, between 0 and 3, stay between the timestamp and the current time and count again in the next update. A separate variable that holds the leftover works equally well.

Every quantity needs an exactly defined unit: the clock, the level, the capacity and every cost. A conversion between two units must be a multiplication, or a division whose remainder is kept. A division that drops its remainder on every update brings the loss back.

Worked example

The rate is 1 token per 4 ticks, a request costs 1 token, the bucket starts empty, and the update runs on every tick from tick 1 to tick 4. The table shows, after each tick, the tokens held by the faulty update, the units held by repair 1 with S=4S = 4 (so 1 unit per tick and 4 units per token), and the tokens and leftover ticks held by repair 2.

tick faulty: tokens repair 1: units repair 2: tokens, leftover
1 0 1 0, 1
2 0 2 0, 2
3 0 3 0, 3
4 0 4 1, 0

The faulty update computes ⌊1/4⌋=0\lfloor 1 / 4 \rfloor = 0 on every tick and moves its timestamp each time, so at tick 4 it refuses the request. Repair 1 reaches 4 units, which is 4/4=14 / 4 = 1 token; it admits the request and its level falls to 4−4=04 - 4 = 0 units. Repair 2 converts its 4 leftover ticks into ⌊4/4⌋=1\lfloor 4 / 4 \rfloor = 1 token and admits the same request.

If the faulty update instead runs every kk ticks, each call earns ⌊k/4⌋\lfloor k / 4 \rfloor tokens, so the granted rate is ⌊k/4⌋/k\lfloor k / 4 \rfloor / k tokens per tick instead of 1/4=0.251 / 4 = 0.25:

Both repairs grant 0.25 tokens per tick for every kk.

A second rate shows the choice of scale. For 3 tokens every 10 ticks (p=3p = 3, q=10q = 10), the scale S=10S = 10 gives 10×3/10=310 \times 3 / 10 = 3 units per tick, and a 1-token request costs 10 units. After 7 ticks the bucket holds 7×3=217 \times 3 = 21 units: 2 whole tokens and 1 unit, a tenth of a token, kept for later. That equals the exact credit, 7×3/10=2.17 \times 3 / 10 = 2.1 tokens.

Stated precisely

Let the rate be p/qp / q tokens per tick, with pp and qq positive integers. Let nn updates see elapsed times of Δ1,Δ2,…,Δn\Delta_1, \Delta_2, \ldots, \Delta_n ticks, and let D=Δ1+Δ2+⋯+ΔnD = \Delta_1 + \Delta_2 + \cdots + \Delta_n be the total elapsed time. The exact credit over the whole time is Dp/qD p / q tokens.

Faulty update. It credits ∑i=1n⌊Δip/q⌋\sum_{i=1}^{n} \lfloor \Delta_i p / q \rfloor tokens. Each term loses its fractional part, which is less than 1, so the total loss is less than nn tokens: it grows with the number of updates, not with time. If every Δip<q\Delta_i p < q, every term is 0 and the bucket never gains anything.

Fixed-point units. With a scale SS chosen so that a=Sp/qa = S p / q is an integer, the level grows by Δ1a+⋯+Δna=Da\Delta_1 a + \cdots + \Delta_n a = D a units, which is exactly Dp/qD p / q tokens however DD is split into updates.

Carried remainder. Keep a remainder ρ\rho, measured in units of 1/q1 / q token and starting at 0. On each update, compute t=ρ+Δpt = \rho + \Delta p, credit ⌊t/q⌋\lfloor t / q \rfloor tokens and set ρ=tmodq\rho = t \bmod q, the remainder of tt divided by qq. After the updates, qK+ρ=pDq K + \rho = p D with 0≤ρ<q0 \le \rho < q, where KK is the number of whole tokens credited so far. Therefore K=⌊Dp/q⌋K = \lfloor D p / q \rfloor: the bucket lags the exact credit by less than one token at any moment and loses nothing over time. For p=1p = 1 and q=4q = 4, ρ\rho is the number of leftover ticks of repair 2.

These statements assume three things: no product or sum overflows its integer type; the clock is monotonic, so every Δi≥0\Delta_i \ge 0; and the level stays below the capacity. Credit discarded at the capacity is the intended limit on bursts, not a loss.

Limits and common mistakes

Rounding up is the mirror mistake. If each update rounds its credit up to a whole token, a source that triggers an update on every tick earns 1 token per tick, a quarter token rounded up: four times the intended rate. Any rounding applied to each update separately makes the granted rate depend on how often updates run. Only rounding the running total, as the carried remainder does, avoids that.

Finer units do not remove overflow. After a long idle time, the product Δa\Delta a can exceed its integer type: with a=1000a = 1000 units per tick in an unsigned 32-bit variable (largest value 4,294,967,295), any Δ\Delta above 4,294,967 ticks overflows, which at 1000 ticks per second is about 72 minutes. Before multiplying, compare Δ\Delta with the room left below the capacity and set the level to the capacity if Δ\Delta is that large, or compute in a 64-bit type. Converting a cost, cSc S, needs the same check.

Limiting the level to the capacity must neither create credit nor cancel a debt. Some designs let the level go negative, recording a debt after an operation that cost more than the level held. The correct update sets the level to the smaller of the capacity and the level plus the gain, computed without overflow, so a debt is repaid before the level rises. Setting a negative level to 0 before adding the gain cancels the debt. Such a design must store the level in a signed variable: in an unsigned 32-bit variable, charging a cost of 1 to a level of 0 wraps around to 4,294,967,295 tokens of credit.

In C, integer division and the remainder operator round toward zero, not down: -1 / 4 gives 0 and -1 % 4 gives -1. The two roundings agree only for non-negative operands, so a signed remainder, such as a debt counted in units, needs explicit handling of negative values.

A scale that does not fit the rate brings back a smaller loss. With a rate of 1 token per 3 ticks and a scale of 1000 units per token, one tick should earn 1000/3≈333.331000 / 3 \approx 333.33 units but earns 333, so the bucket fills about 0.1% too slowly. Choose SS as a multiple of qq, or carry the remainder of that division as well.

Exact counting fixes the rate and nothing else. It does not make the limiter fair between sources, and it does not bound how long a request waits.

Questions answered

Give a failure example.

A token bucket, a rate limiter whose credit (tokens) grows with elapsed time and is spent by requests, is meant to earn one token every 4 ticks of the system timer, and it fails when its update rounds each step’s credit down to whole tokens and then sets its timestamp to the current time. Called on every tick, each update sees 1 elapsed tick, computes 1/41 / 4 with integer division, which gives 0, and discards the quarter token by moving the timestamp. After 4 ticks, and after any number of ticks, the bucket holds 0 tokens and refuses every request, although the same limiter called once after 4 ticks earns 1 token. The granted rate depends on how often the update runs instead of on elapsed time, and a source that sends a request on every tick never gets one through.

The repair is to stop discarding the fraction. Count credit in quarter tokens, which are fixed-point units: 1 unit per tick and 4 units per token, so the level grows 1, 2, 3, 4 units and holds one token at tick 4. Or advance the timestamp only by the ticks converted into tokens, so the leftover ticks count in the next update. Costs and the capacity must be converted into the same units, and the multiplications must be checked for overflow.

Related entries: Overflow-safe range check (§4.17), Integer promotion and conversion (§4.18), Rate limiting (§9.38), Token bucket: rate, burst, and the arrival envelope (§19.4.1), Ceiling division for a conservative wait (§19.4.4), Unsigned modular arithmetic (§4.16).