Try
↑ ↓ move↵ openesc close
In this lesson · topic 6 of 7
  1. 1. Why callers need a limit
  2. 2. Five ways to count
  3. 3. Race five limiters across a window edge
  4. 4. What each limiter admits at the edge
  5. 5. The sliding counter, worked by hand
  6. 6. Pricing requests and stacking limits
  7. 7. Choosing a limiter under pressure

Topic 6

Pricing requests and stacking limits

5 min read

Counting requests treats a cached lookup and a ten-second export as the same thing. In production they are not, and a limiter that cannot tell them apart protects the cheap path and leaves the expensive one open.

Charge by cost

A token bucket extends naturally. Each request takes tokens in proportion to the work it causes. Take a bucket of 100 tokens that refills at 10 a second. A lookup costs 1 token. A bulk export costs 25.

  • A caller who has been idle can send 4 exports back to back, which empties the bucket. A fifth is rejected.
  • Sustained, the refill supports 10 / 25 = 0.4 exports a second, one every 2.5 seconds, or 24 a minute.
  • Or the same refill supports 600 lookups a minute. The caller picks the mix.
  • A caller doing 5 lookups a second has spent half the refill. What is left supports 5 / 25 = 0.2 exports a second.

One number, the refill rate, now stands for capacity in the units that matter. You do not need one limit per endpoint, and the cost table is the only thing to keep current.

Predict first

The bucket holds 100 tokens, refills at 10 a second, and an export costs 25. A caller who has been idle sends 5 exports in the same instant. How many are admitted?

Pick the key with care

The key decides who shares an allowance.

  • API key or account. The usual choice. It maps to a customer and to a contract.
  • Source address. The only choice for anonymous traffic. It is also a trap: 500 users behind one office gateway share one address. With a per-address limit of 50 a second, each gets 0.1 request a second if they all work at once.
  • Route. An allowance per endpoint, so a flood against search does not use the login allowance.
  • Global. One bucket for the whole service, as a last guard.

Stack the layers

Real systems use several at once, such as 10 a second per key, 50 a second per address and 2,000 a second overall. A request must pass all of them. Two details decide whether this behaves.

Order. Check the narrow, cheap limits first. If the per-key limit rejects a request, it should not consume a token from the global bucket, or one noisy caller drains the allowance of everyone else without even getting served.

Refunds. If the request is admitted and then fails before doing the costly work, for example on a validation error, refunding the tokens keeps honest callers from paying for the service’s own rejections. Many teams skip this and accept slight over-charging.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms