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.
- Reset (
rst_nlow, synchronous): the bucket is full (CAPtokens), the refill counter restarts at the beginning of a period, andgrantis 0. - 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, the2*PERIOD-th, and so on) one token is added, unless the bucket is already full. - Grant: on a clock where
reqis 1 and the bucket holds at least one token before that clock's refill, one token is used andgrantis 1 after the edge. Otherwisegrantis 0 after the edge. A token that arrives on a clock cannot serve a request on that same clock. - 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.