Definition
Ceiling division is division of an integer by a positive integer with the quotient rounded up to a whole number, written : , 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 units of credit and credit grows by units per tick, one period of the system timer, 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 ticks. After 2 ticks the worker has earned only 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 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 be the deficit, the credit the request still lacks, and the credit earned per tick, both integers in the same unit.
Refill the bucket from the elapsed time, then compute as the cost minus the level. If , admit the request without waiting.
If , credit never arrives. Refuse the request, or wait for a change of configuration; do not divide by zero.
Divide with remainder: , with quotient and remainder , where . In the C language, is
d / rand isd % r.Set the wait if , and otherwise.
Sleep for at least ticks.
On waking, refill from the time that actually passed, which may be more than 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 , where means rounded down. The quotient-plus-one form of step 4 avoids the sum , which can overflow a fixed-width integer type when 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 tokens, rate tokens per tick. Since , the quotient is , the remainder is , and the wait is ticks. Check: 2 ticks earn tokens, and 3 ticks earn . The surplus token stays in the bucket.
Remainder zero. Deficit , rate . Since , the wait is 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 and . The textbook form computes , which wraps around to , and : a wait of 0 ticks, which is wrong. The quotient-plus-one form computes , so , and never forms a value above 251. Checked outside the 8-bit type: and .
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 tokens, so the deficit is . The new wait is tick (quotient 0, remainder 1). At tick 3 the bucket holds 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 and , is the unique integer with . It is therefore the least integer with . Writing with , when and when . The surplus credit lies between 0 and : less than one tick’s worth.
The wait keeps its promise under four assumptions: credit grows by exactly per tick from the moment is computed; no other request spends that credit in the meantime; the sleep lasts at least ticks; and and 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 and . C’s division rounds toward zero, so for and it gives and , hence , while . Admitting the request whenever , 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, , which does not fit, because the largest value is . 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 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 ticks, the deficit (credit still missing) divided by the rate (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 ticks. After the first slice of 2 ticks, tokens have been earned and 1 is still missing; the next wait is 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).