Per-Key Token Bucket Limiter For Inference API Requests
Last updated: November 29, 2026
Quick Overview
Implement a rate limiter for a managed inference API where each API key has a token bucket with a refill rate and burst size, requests can cost more than one token, and the limiter can say how long to wait before retrying.
Crusoe
November 29, 20260
0
0 solved
Implement a rate limiter for a managed inference API where each API key has a token bucket with a refill rate and burst size, requests can cost more than one token, and the limiter can say how long to wait before retrying.
Crusoe Managed Inference sells pay-per-token and provisioned throughput, so the gateway must cap each key's request or token rate while allowing bursts. The interviewer looks for lazy refill based on timestamps, correct handling of variable cost, and a sensible Retry-After value.
What the Interviewer Expects
- Refills lazily from elapsed time instead of using a timer per key
- Supports variable cost such as estimated output tokens
- Caps tokens at the burst size
- Returns a correct retry-after, including the never-possible case
- Discusses memory per key and distributed enforcement
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you enforce this across 50 gateway replicas?
- Cost depends on output tokens you do not know until generation ends. How do you charge?
- How would you evict state for idle keys?
- Provisioned throughput customers should never be throttled by pay-per-token traffic. How do you isolate them?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
allow(key, now, cost) returns True and deducts tokens if available. Each key starts full at burst. Refill is rate tokens per second, capped at burst. retry_after(key, now, cost) returns seco...
High-Level Design
Store (tokens, last_ts) per key. On each call compute the refill from now - last_ts, then try to deduct. No background thread: state only changes when a request arrives, so cost is O(1) per reques...