RTL Design #71 · 2026-12-03 · Rate limiting · Medium · about 25 min

A token-bucket rate limiter

Write token_bucket, a rate limiter. It holds up to CAP tokens. A request that finds a token uses it up and is granted. One new token arrives every PERIOD clocks.

  1. Reset (rst_n low, synchronous): the bucket is full (CAP tokens), the refill counter restarts at the beginning of a period, and grant is 0.
  2. Refill clock: the refill counter counts clocks continuously after reset, whether or not requests arrive. On the last clock of each period (the PERIOD-th clock after reset, the 2*PERIOD-th, and so on) one token is added, unless the bucket is already full.
  3. Grant: on a clock where req is 1 and the bucket holds at least one token before that clock's refill, one token is used and grant is 1 after the edge. Otherwise grant is 0 after the edge. A token that arrives on a clock cannot serve a request on that same clock.
  4. If a token is used and a token arrives on the same clock, the count stays the same.

req is sampled at every rising edge. grant is registered: it shows the decision of the previous edge.

Example (CAP = 2, PERIOD = 3), req held high from the first edge after reset:

edge tokens before refill? req grant after tokens after
1 2 no 1 1 1
2 1 no 1 1 0
3 0 yes 1 0 1
4 1 no 1 1 0
5 0 no 1 0 0

Fill in bucket.sv. Run drives this example.

Write and run your answer in the browser. The hidden tests check it, and it’s free.