Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 154/ 160
08. Backend

Rate Limiting

Protect APIs and budgets with token buckets and sliding windows per user/tenant.

IntermediateToken Bucket · Per-tenant3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Rate limiting is a rule that says how many requests someone can make in a given time, so no one user can use up everything or run up the bill.

Think of it like…

A turnstile with a bucket of tickets. The bucket holds 20 tickets and gets 5 new ones each second, so a crowd can pass quickly at first, then at a steady rate; a separate meter at the gate tracks how much each visitor carries in, not only how many visits they make.

Where you’ve seen it

The API has plans: free at 10 requests per minute, pro at 60 and enterprise custom. The limiter uses a token bucket in Redis keyed by rl:{tenant}:{endpoint}, implemented in a single Lua script so the read, refill and spend happen atomically. With capacity 20 and refill of 5 tokens a second, a client sending 30 requests instantly gets 20 accepted and 10 rejected with 429; two seconds later 10 tokens have returned, so 10 more can pass. A fixed window at 100 per minute would allow 100 requests at 12:00:59 and another 100 at 12:01:00, 200 in two seconds, which is why the team prefers a sliding window or token bucket. Requests aren't equal in cost, so a second limiter counts tokens: a tenant's budget is 200,000 tokens per minute, and a typical request of 3,100 input plus 420 output tokens uses 3,520, so the token limit binds at 200,000 / 3,520 ≈ 56.8 requests a minute, slightly below the 60-request plan cap. Input tokens are charged on arrival from an estimate, and output tokens are reconciled after the response using actual usage, with max_tokens setting the worst case. A concurrency limit of 5 open streams per user prevents one account from holding hundreds of connections, and a daily spend cap of $50 stops at 50 / 0.01195 ≈ 4,184 average requests. Responses carry RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset and, on 429, Retry-After: 12, so well-behaved clients back off. If Redis is unreachable the limiter fails open for authenticated paid traffic but keeps a coarse in-process limit as a safety net, and fails closed for anonymous endpoints; each choice is documented. Limits are keyed on the verified tenant from the token, with an additional per-IP limit on unauthenticated routes, and dashboards track limited requests by tenant and plan to spot both abuse and customers who need a higher tier.

Words you’ll hear

Token bucket
A limiter with a refilling bucket that permits bursts up to its capacity and a steady average rate.
Sliding window
Counting requests over the most recent period rather than a fixed clock window.
Concurrency limit
A cap on simultaneous in-flight requests or open streams.
Fail open / fail closed
Allowing or blocking traffic when the limiter itself is unavailable.

Visual diagram

Loading interactive diagram

Theory & deep dive

Algorithms and their trade-offs

A fixed window counter increments a key per clock minute (INCR plus EXPIRE), which is cheap but allows boundary bursts: with a 100-per-minute limit a client can send 100 requests at 12:00:59 and 100 more at 12:01:00, 200 in two seconds. A sliding window (log or weighted counter) removes the artefact by counting the last 60 seconds precisely, at higher memory or computation cost. A token bucket keeps tokens and last_refill: on each request add elapsed × rate tokens up to capacity, then spend one if available. With capacity 20 and rate 5 per second, a burst of 30 gets 20 accepted and 10 rejected, and after 2 seconds 10 tokens are back. It models burst tolerance and a sustained rate in two parameters and is the usual choice. A leaky bucket smooths output to a constant rate by queueing, which suits protecting a fragile downstream.

In a distributed system, state must be shared: use Redis with a Lua script (or a built-in atomic command) so that read, refill and spend are one atomic step; without atomicity two instances can each approve the last token. Return 429 with Retry-After and RateLimit-* headers so clients can pace themselves, and make the limiter cheap, since it runs on every request. Local, per-instance approximations (limit ÷ instance count) are cheaper but drift when load is uneven.

Token bucket arithmetic

Capacity 20, refill 5/s. t = 0: 30 requests arrive → 20 accepted (bucket empty), 10 get 429. t = 2 s: bucket has 10 tokens → 10 more accepted. Sustained: at most 5 requests per second on average, with bursts up to 20.

Key takeaway: Use token buckets or sliding windows in shared, atomic state and return clear 429 responses with retry guidance.

Limiting cost, concurrency and abuse in AI systems

A request limit alone treats a 50-token ping like a 100,000-token document analysis. Add a token-per-minute limit using an estimate at admission (input tokens counted, output bounded by max_tokens) and reconcile with actual usage afterwards. With a 200,000 tokens-per-minute budget and 3,520 tokens per typical request, the effective limit is 200,000 / 3,520 ≈ 56.8 requests a minute, so the token limit, not the 60-request plan cap, is what binds. Add concurrency limits (5 open streams per user), daily or monthly spend caps ($50 a day is about 4,184 average requests at $0.01195) and per-endpoint limits (embedding and file upload endpoints differ from chat). Tiered plans map to different limits, and enterprise customers can negotiate custom ones.

Operations: key limits on verified identity (tenant from the token) and add per-IP limits on unauthenticated paths; protect the limiter itself, since it sits on the hot path (cache plan lookups, keep scripts fast) and decide fail-open or fail-closed per route when Redis is unavailable (paid authenticated traffic usually fails open with a coarse local limit; anonymous or expensive endpoints fail closed). Provide visibility: dashboards of limited requests by tenant and plan, alerts for sudden 429 spikes (abuse, a buggy client or a limit that is too low) and clear error messages with the limit and reset time. Pair limits with client-side backoff and jitter, and with provider-facing limiters so your own throttling protects your upstream quota (see the provider rate limits lesson).

Which limit binds

Plan cap 60 requests/min; token cap 200,000/min. Typical request 3,520 tokens → 56.8 requests/min by tokens. A tenant sending short prompts (500 tokens) hits the 60-request cap first at 30,000 tokens; one sending long documents (20,000 tokens) is limited to 10 requests a minute.

Key takeaway: Layer request, token, concurrency and spend limits, key them on verified identity and choose failure behaviour deliberately.

How it works, step by step

Step 1 of 4
Product + backend

1. Define limits per plan and endpoint

Set request, token, concurrency and spend limits for each plan and expensive endpoint.

pro: 60 rpm · 200,000 tokens/min · 5 streams
Key numbers at this step
Cap
daily spend

When to use it & trade-offs

What it is

Rate limiting caps how much a caller can use your API in a period, protecting capacity, budget and fairness. Common algorithms are the fixed window counter (count requests in each clock minute), the sliding window (count over the last N seconds), the token bucket (a bucket of capacity b refills at r tokens per second and each request spends a token, allowing bursts up to b while enforcing an average of r) and the leaky bucket (a queue drained at a constant rate). Limits are applied per key: user, API key, tenant, IP address or endpoint. For AI APIs, request counts alone don't reflect cost, so you also limit tokens per minute, concurrent streams and daily spend. Rejected calls return 429 Too Many Requests with Retry-After and rate-limit headers.

Why it matters: Every request to an LLM backend costs money and capacity. One runaway client script, one leaked API key or one abusive account can exhaust your provider quota, spike your bill and degrade service for everyone. Rate limits turn those risks into predictable bounds and are the front line of fairness in multi-tenant systems. Getting the algorithm right matters: a naive fixed window lets callers burst to double the limit, a request-only limit lets one huge prompt consume a minute's budget and a limiter that fails closed when Redis is down turns a cache incident into an outage.

When to reach for it

  • Per-tenant request and token limits on LLM APIs
  • Concurrency caps on streams and expensive endpoints
  • Daily spend caps for free and trial accounts

When to avoid or be careful

  • Limiting only by request count
  • Limits keyed on unverified headers
  • Non-atomic read-then-write counters

Limiting algorithms

Fixed window
Best for: Simple coarse quotas

Strengths: Very cheap.

Watch out: Boundary bursts up to 2× the limit.

Sliding window
Best for: Accurate per-period limits

Strengths: No boundary burst.

Watch out: More memory or computation.

Token bucket
Best for: Allowing bursts with a steady average

Strengths: Two intuitive parameters; efficient.

Watch out: Needs atomic shared state.

Leaky bucket
Best for: Smoothing traffic to a fragile downstream

Strengths: Constant output rate.

Watch out: Adds queueing latency.

Interview signals & numbers to know

When this topic comes up

  • “How would you rate limit an LLM API?”
  • Token bucket versus fixed window
  • Limiting tokens as well as requests
  • Fail-open versus fail-closed
  • Distributed rate limiting with Redis

Benchmarks & rules of thumb

20 + 5/s -
example token bucket: capacity and refill rate
200 requests in 2 s -
worst-case boundary burst of a 100/min fixed window
56.8 requests/min -
200,000 tokens/min ÷ 3,520 tokens per request

Common mistakes & follow-ups

Common interview mistakes

  • Using a fixed window and being surprised by double bursts.
  • Counting requests but not the cost of huge prompts.
  • Failing closed on every route when Redis blips.

Likely interviewer follow-ups

  • How would you rate limit streaming responses?
  • How do you charge output tokens you don't know at admission?
  • How do you let a customer burst without exceeding their average?
Interview tip: State which limit binds (tokens or requests) for a typical request; it shows you reason about cost, not just counts.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Rate Limiting with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Background Jobs
Next topic
Idempotency Keys