Token Budget Rate Limiter for an LLM Gateway

Last updated: November 29, 2026

Quick Overview

Build a per-API-key rate limiter that caps the number of LLM tokens (not requests) consumed in a sliding time window, returns how long a rejected caller should wait, and can correct a reservation once the real completion length is known.

Truefoundry
Coding & Algorithms
Software Engineer
Truefoundry
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Build a per-API-key rate limiter that caps the number of LLM tokens (not requests) consumed in a sliding time window, returns how long a rejected caller should wait, and can correct a reservation once the real completion length is known.

TrueFoundry's gateway enforces rate limits and budgets per team, user and model, and LLM cost scales with tokens rather than request count. The interviewer wants a correct sliding window, a sensible Retry-After value, and a story for the fact that output tokens are unknown until the stream finishes.

What the Interviewer Expects
  • Count tokens per key in a true sliding window, not fixed buckets
  • Reject requests that would exceed the limit and compute an accurate retry delay
  • Handle requests larger than the whole limit explicitly
  • Explain estimation of output tokens up front and reconciliation afterwards
  • Amortized O(1) per call
Key Topics to Cover
sliding window
rate limiting
token accounting
Retry-After
deque
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you share this state across 20 gateway pods?
  • Would you rather over-admit or under-admit when the estimate is wrong, and why?
  • How do you switch to a fixed-memory approximation for millions of keys?
  • How would per-model and per-team limits compose on one request?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

allow(key, now, tokens) returns (admitted, retry_after). The limit is limit tokens in any window of window seconds. tokens is the estimate at admission time (prompt tokens plus max_tokens ...

High-Level Design

Keep a deque of (timestamp, tokens) per key plus a running sum. On each call, pop entries older than the window and subtract them. Admit if used + tokens <= limit. If rejected, walk from the oldes...


Submit Your Answer
Markdown supported

Related Questions