Token-Based Rate Limiter for a Shared Model API
Last updated: November 29, 2026
Quick Overview
Implement a per-API-key rate limiter for an OpenAI-compatible model endpoint where each request costs the number of tokens it will consume, not one unit. Expose allow(key, cost, now) that returns whether the request may proceed.
Baseten
November 29, 20260
0
0 solved
Implement a per-API-key rate limiter for an OpenAI-compatible model endpoint where each request costs the number of tokens it will consume, not one unit. Expose allow(key, cost, now) that returns whether the request may proceed.
Baseten's shared Model APIs bill and throttle by tokens, so a limiter that counts requests lets one long-context caller starve everyone else. A phone screen version checks that you can pick a token bucket, handle fractional refill and explain why rejected requests should not burn quota.
What the Interviewer Expects
- Chooses a token bucket and explains why it allows short bursts while bounding the average rate
- Refills lazily from elapsed time instead of using a background timer
- Does not deduct quota for rejected requests
- Handles a request costing more than capacity (always rejected) and new keys starting full
- States O(1) time per call and O(keys) memory
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
- The true output length is unknown at admission. How do you reserve an estimate and settle the difference when the stream ends?
- How would you share this limit across 20 gateway pods without a round trip per request?
- How do you evict buckets for keys that have gone idle?
- How would you add a separate requests-per-minute limit on top of tokens-per-minute?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Each API key has a budget of capacity tokens that refills at refill_per_sec. A request with cost tokens (prompt plus max output) is allowed only if the bucket holds at least cost. Calls arrive...
High-Level Design
Store (tokens, last_ts) per key in a dict. On each call, top up the bucket by elapsed * rate, capped at capacity, then compare against cost. This is lazy refill: no timers, and the state is two nu...