Token-Weighted Rate Limiter for a Serverless Inference API
Last updated: November 29, 2026
Quick Overview
Implement a per-API-key rate limiter for an LLM inference endpoint where each request costs a variable number of tokens, supporting try_consume(key, cost, now) and retry_after(key, cost, now).
Nebius
November 29, 20260
0
0 solved
Implement a per-API-key rate limiter for an LLM inference endpoint where each request costs a variable number of tokens, supporting try_consume(key, cost, now) and retry_after(key, cost, now).
Nebius Token Factory (formerly AI Studio) sells open-model inference priced per token, so limits are naturally expressed in tokens per minute rather than requests. The interviewer wants a correct token bucket with lazy refill, sensible behavior for requests larger than the bucket, and a clear path to a distributed version.
What the Interviewer Expects
- Chooses a token bucket and explains why it allows bursts while bounding average rate
- Refills lazily using elapsed time instead of a background timer
- Handles cost greater than capacity explicitly
- Provides a correct Retry-After computation
- Discusses estimating cost before the output length is known
- Sketches a distributed version (Redis Lua script or per-gateway shards)
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
- Output tokens are unknown when the request starts; how do you charge for them?
- How do you enforce one limit across 50 gateway replicas without a round trip on every request?
- How would you add a separate concurrency limit for long streaming requests?
- Clock skew between gateways: what breaks?
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 key has a bucket of capacity tokens refilling at refill_per_sec. A request with cost c succeeds if the bucket holds at least c and then deducts it. Rejected requests get a retry hint. New...
High-Level Design
Store [tokens, last_ts] per key. On every call, refill by elapsed * rate capped at capacity, then decide. No timers, so idle keys cost nothing but memory, and an LRU or TTL can evict them....