Q268FreeSystemVerilog
Token-Bucket Rate-Limit Monitor
Interview prompt
Question
Model a token-bucket limiter and verify whether each packet should be accepted or throttled. Tokens accumulate while idle but never exceed the configured burst capacity.
Starting point
Question code
class TokenBucket;
function new(int capacity, int refill_tokens, int refill_period);
void tick();
bit accept(int cost);
int available_tokens();
endclassReviewed example
Trace one case
Input
capacity=4, refill=1 token/cycle
cycle 0 request cost=3
cycle 1 request cost=2
cycle 2 request cost=2Expected output
cycle 0 allow (tokens 1)
cycle 1 allow after refill (tokens 0)
cycle 2 deny after refill (tokens 1)Tokens saturate at capacity, refill before admission, and are consumed only by allowed requests.
What to cover
Requirements
- Refill at the configured rate and saturate exactly at capacity.
- A packet is accepted only when its complete cost can be consumed without underflow.
- Define deterministic ordering when refill and consume occur in the same cycle.
- Reject invalid configuration and nonpositive packet cost.

