Section 19.4.4

Ceiling division for a conservative wait

Definition

Ceiling division is division of an integer dd by a positive integer rr with the quotient rounded up to a whole number, written ⌈d/r⌉\lceil d / r \rceil: ⌈5/2⌉=3\lceil 5 / 2 \rceil = 3, where ordinary integer division gives 2. A conservative wait is a waiting time that is never too short for its purpose. When a request lacks dd units of credit and credit grows by rr units per tick, one period of the system timer, ⌈d/r⌉\lceil d / r \rceil is the fewest whole ticks after which enough credit has accrued. Rounding down would wake the request too early.

The idea

A rate limiter §9.38 refuses a request whose credit is short, and a caller that wants the request served must decide how long to sleep before trying again. Suppose a worker needs 5 more tokens of credit and the limiter grants 2 tokens per tick. Ordinary integer division gives 5/2=25 / 2 = 2 ticks. After 2 ticks the worker has earned only 2×2=42 \times 2 = 4 tokens, one short, so it wakes, fails the check and must sleep again. Worse, code that trusts the computed wait without checking proceeds with too little credit. Waiting 3 ticks earns 2×3=62 \times 3 = 6 tokens, which is enough.

A wait is counted in whole ticks, so when the exact answer is a fraction, here 2.5 ticks, it must be rounded one way or the other. Rounding up wastes less than one tick’s worth of credit. Rounding down guarantees a premature wake-up. A conservative choice errs toward the side that keeps the promise, here the promise that the credit suffices on waking.

How it works

Let dd be the deficit, the credit the request still lacks, and rr the credit earned per tick, both integers in the same unit.

  1. Refill the bucket from the elapsed time, then compute dd as the cost minus the level. If d≤0d \le 0, admit the request without waiting.

  2. If r=0r = 0, credit never arrives. Refuse the request, or wait for a change of configuration; do not divide by zero.

  3. Divide with remainder: d=qr+ρd = q r + \rho, with quotient qq and remainder ρ\rho, where 0≤ρ<r0 \le \rho < r. In the C language, qq is d / r and ρ\rho is d % r.

  4. Set the wait w=qw = q if ρ=0\rho = 0, and w=q+1w = q + 1 otherwise.

  5. Sleep for at least ww ticks.

  6. On waking, refill from the time that actually passed, which may be more than ww ticks, and test again whether the level covers the cost. Also recheck cancellation §9.29 (the caller withdrawing the request) and any other state that can change during the sleep, such as a closed connection.

A common textbook form of ceiling division is ⌊(d+r−1)/r⌋\lfloor (d + r - 1) / r \rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down. The quotient-plus-one form of step 4 avoids the sum d+r−1d + r - 1, which can overflow a fixed-width integer type when dd is close to the largest value of that type.

Many systems cap each sleep at a maximum length, called a slice, so that the sleeping code wakes regularly and notices cancellation, shutdown or a change of rate. A slice changes how the wait is carried out, not when the request may proceed. After each slice the code repeats steps 1 to 6 with the new deficit, and each new sleep is again capped at the slice.

Worked example

Remainder not zero. Deficit d=5d = 5 tokens, rate r=2r = 2 tokens per tick. Since 5=2×2+15 = 2 \times 2 + 1, the quotient is q=2q = 2, the remainder is ρ=1\rho = 1, and the wait is w=2+1=3w = 2 + 1 = 3 ticks. Check: 2 ticks earn 2×2=4<52 \times 2 = 4 < 5 tokens, and 3 ticks earn 2×3=6≥52 \times 3 = 6 \ge 5. The surplus 6−5=16 - 5 = 1 token stays in the bucket.

Remainder zero. Deficit d=6d = 6, rate r=2r = 2. Since 6=3×2+06 = 3 \times 2 + 0, the wait is w=3w = 3 ticks, and 3 ticks earn exactly 6 tokens.

Overflow in the textbook form. Take an unsigned 8-bit type, whose values run from 0 to 255, with d=251d = 251 and r=10r = 10. The textbook form computes 251+10−1=260251 + 10 - 1 = 260, which wraps around to 260−256=4260 - 256 = 4, and ⌊4/10⌋=0\lfloor 4 / 10 \rfloor = 0: a wait of 0 ticks, which is wrong. The quotient-plus-one form computes 251=25×10+1251 = 25 \times 10 + 1, so w=25+1=26w = 25 + 1 = 26, and never forms a value above 251. Checked outside the 8-bit type: 25×10=250<25125 \times 10 = 250 < 251 and 26×10=260≥25126 \times 10 = 260 \ge 251.

Wait capped at a slice. The bucket is empty, a request costs 5 tokens, the rate is 2 tokens per tick, and the slice is 2 ticks. At tick 0 the deficit is 5 and the computed wait is 3 ticks, so the worker sleeps for the slice of 2 ticks. At tick 2 it refills: it has earned 2×2=42 \times 2 = 4 tokens, so the deficit is 5−4=15 - 4 = 1. The new wait is ⌈1/2⌉=1\lceil 1 / 2 \rceil = 1 tick (quotient 0, remainder 1). At tick 3 the bucket holds 4+2=64 + 2 = 6 tokens, at least the cost of 5, and the request is admitted. The total wait is 3 ticks, the same as one uncapped sleep, at the price of one extra wake-up. Treating the end of the first slice as the end of the wait would have admitted the request 1 token short.

Stated precisely

For integers d≥0d \ge 0 and r>0r > 0, w=⌈d/r⌉w = \lceil d / r \rceil is the unique integer with r(w−1)<d≤rwr (w - 1) < d \le r w. It is therefore the least integer ww with rw≥dr w \ge d. Writing d=qr+ρd = q r + \rho with 0≤ρ<r0 \le \rho < r, w=qw = q when ρ=0\rho = 0 and w=q+1w = q + 1 when ρ>0\rho > 0. The surplus credit rw−dr w - d lies between 0 and r−1r - 1: less than one tick’s worth.

The wait keeps its promise under four assumptions: credit grows by exactly rr per tick from the moment dd is computed; no other request spends that credit in the meantime; the sleep lasts at least ww ticks; and dd and rr were computed without overflow. Then, on waking, the level is at least the cost. Each assumption can fail in a real system, which is why step 6 tests the level again instead of assuming it.

Limits and common mistakes

A rate of zero must be handled before dividing. The C standard leaves integer division by zero undefined; x86 processors raise a fault, while Arm Cortex-M processors that have a hardware divide instruction return 0 by default, a silently wrong answer.

The quotient-plus-one formula is correct only for d≥0d \ge 0 and r>0r > 0. C’s division rounds toward zero, so for d=−3d = -3 and r=2r = 2 it gives q=−1q = -1 and ρ=−1\rho = -1, hence w=0w = 0, while ⌈−3/2⌉=−1\lceil -3 / 2 \rceil = -1. Admitting the request whenever d≤0d \le 0, as step 1 does, keeps negative values away from the formula.

Computing the deficit can itself overflow. If the level is a signed integer that may be negative, recording a debt, then the cost minus the level can exceed the type: in a 32-bit signed type, 0−(−231)=2310 - (-2^{31}) = 2^{31}, which does not fit, because the largest value is 231−12^{31} - 1. Check the range first, or compute in a wider type.

Round the rate down, never up. If a fractional rate such as 2.5 tokens per tick is stored as 3, the computed wait is too short; store it as 2, or use fixed-point units §19.4.3 (whole-number counts of fixed fractions of a token).

The wait is the minimum time needed to earn the credit, not a deadline. The scheduler can run the worker later, and other work can be queued ahead of it, so the response time §9.32 of the request, from arrival to completion, can be much longer than ww ticks.

When several requests share one bucket, another request can spend the credit while this one sleeps. Without an order among waiting requests, one request can lose the race again and again, which is starvation §9.18.

A short slice costs processor time, because every wake-up runs code. A slice of 0 ticks turns sleeping into a busy loop. The slice bounds how late the code notices cancellation, not how late the request proceeds.

Questions answered

What if the wait is capped at a slice?

If the wait is capped at a slice, the worker sleeps for at most one slice at a time, and the end of a slice does not mean that the request has earned enough credit. The full wait is ⌈d/r⌉\lceil d / r \rceil ticks, the deficit dd (credit still missing) divided by the rate rr (credit earned per tick) and rounded up. After each slice the worker must refill the credit from the time that actually passed, recheck cancellation and any other state that may have changed, such as a closed connection, and then either proceed, if the credit now covers the cost, or compute a new rounded-up wait for the remaining deficit and sleep again, once more capped at the slice.

Example: the deficit is 5 tokens, the rate 2 tokens per tick and the slice 2 ticks. The full wait is ⌈5/2⌉=3\lceil 5 / 2 \rceil = 3 ticks. After the first slice of 2 ticks, 2×2=42 \times 2 = 4 tokens have been earned and 1 is still missing; the next wait is ⌈1/2⌉=1\lceil 1 / 2 \rceil = 1 tick, after which 6 tokens cover the cost of 5. Proceeding after the first slice would overspend by 1 token. The slice makes the worker more responsive to cancellation; it does not shorten the wait or change the condition for admission.

Related entries: Overflow-safe range check (§4.17), Signed integer overflow (§4.15), Cancellation (§9.29), Monotonic clock (§9.35), Fixed-point units and fractional-refill loss (§19.4.3), Starvation (§9.18).