LESSON 03 · Token bucket

Allow controlled bursts with tokens

Capacity sets burst size; refill rate sets the long-run pace.

SYSTEM VIEW

The decision path

Diagram view
Swipe or scroll to explore the full diagram
A bucket permits a bounded burstThe bucket refills at a steady rate, holds no more than its capacity, and spends one token per accepted request.A bucket permits a bounded burstrefillavailableemptyTime2 tokens / secondToken bucketcapacity 10 · current 7Request allowedspend one tokenRequest throttledno token remainsExample: capacity 10; refill 2 per second; one token per request.
The bucket refills at a steady rate, holds no more than its capacity, and spends one token per accepted request.
Trace the quota decision before a request reaches the API.
THE IDEA

How it works

A token bucket stores up to a capacity of tokens. Tokens refill over time. Each request consumes a token if one is available; otherwise it is throttled. A capacity of 10 and a refill of 2 tokens per second permits a burst of 10 after idleness, then sustains roughly 2 requests per second. Refill is capped at capacity, so unused allowance does not grow without bound.

With those numbers: at 0 seconds the bucket is full and 10 requests arrive, leaving no tokens. At 1.5 seconds it has earned 3 tokens. Four requests then arrive: three pass and one is rejected. Over a full minute it can admit at most 130: the starting 10 plus 120 from refill. No background timer is needed; store the token count and the last update time, then work out the refill when the next request arrives. Amazon API Gateway describes its throttling this way, with a rate and a burst setting.

This is useful when ordinary traffic arrives in short bursts but its average should remain bounded. It is a poor fit when the protected system cannot absorb a burst, since a full bucket releases its whole capacity at once. A leaky bucket instead drains a finite queue at a steady pace, which is helpful when downstream work needs a smooth output rate; NGINX’s limit_req module uses this method. With room for 20 queued requests and a drain of 5 per second, the last one waits 4 seconds. When the queue fills, requests must be rejected or handled by another explicit policy.

DECISION POINT

An API may accept ten rapid actions after idle time but only two per second thereafter. Which parameters fit?

Write a sentence or two to unlock the guidance. Committing first is what makes it stick.

Keep in mind

  • Token capacity and refill rate control different behavior.
  • Leaky bucket smooths output but introduces queue delay.
CHECK YOUR UNDERSTANDING

Put it into practice.

1 OF 3
ApplyQUESTION 01

A bucket has capacity 50, refills 5 tokens per second, and has been idle for an hour. How many one-token requests can it allow right now?

Choose an answer. You’ll see the explanation once you get it right.

Next lesson

0 of 3 checkpoints answered correctly to complete this lesson.