Token-Based Rate Limiting for Variable-Cost API Operations
System DesignModel answerLast updated
Build a distributed rate limiter that enforces consumption budgets measured in variable billing units rather than fixed request counts.
Context
You're building infrastructure for a platform that processes variable-cost operations. Each operation consumes a different number of billing units—some might use 300 units, others 5,000—and you won't know the exact cost until after the operation completes. Operations can also run for several seconds, with costs accumulating gradually for streaming workloads.
Traditional rate limiters count requests (1 request = 1 unit), but that doesn't work here. You need to enforce budgets measured in consumption units across multiple time windows: per-minute capacity limits, hourly throttles, and monthly spending caps.
Design a distributed rate limiting system that prevents budget overruns while keeping check latency under 5 ms at p99.
Your Task
Build a service that supports this consumption model:
Two-phase flow:
- Reserve an estimated number of units before starting the operation
- Commit the actual units consumed after the operation finishes (which may differ from the estimate)
Enforcement scopes:
- Individual resource level (per-agent, per-API-key)
- User level (all resources belonging to one user)
- Account level (organization-wide pool)
Policy flexibility:
- Hard rejection when budgets are exhausted
- Soft limits that allow small overages for high-priority operations
- Queuing for lower-priority work that can wait
Streaming operations: Ten percent of operations stream results over 60+ seconds. Costs accumulate as the stream progresses, and you need to reconcile usage incrementally.
Scale Parameters
- 100,000 active accounts
- 50,000 reserve/commit operations per second at peak
- Average time between reserve and commit: 4 seconds
- 90% non-streaming (quick operations), 10% streaming (up to 60 seconds)
What to Address
-
API contracts: Define the endpoints and request/response shapes for reserving, committing, and adjusting consumption.
-
Storage and algorithms: Choose your data store and explain which rate limiting algorithm you'll adapt for variable-unit costs. Show how you'll track consumption across minute, hour, and month windows.
-
Reservation lifecycle: Walk through what happens when an operation crashes midway. How do you prevent leaking reserved units or losing track of actual consumption?
-
Distribution strategy: Explain how multiple limiter instances share quota state. What happens when one account generates far more traffic than others?
-
Consistency trade-offs: Compare strict enforcement (zero overages) against eventual consistency with bounded overages. Which approach fits which use case?
-
Failure modes: If your rate limiter becomes unreachable, should requests fail-open (allow traffic, risk overages) or fail-closed (reject traffic, preserve limits)?
Hints
Hint 1
Memory fits easily: 250k concurrent operations × 200 bytes + counters for 100k accounts across scopes = under 100 MB. Consider in-memory stores.
Hint 2
The commit step happens after work completes, so the service performing the work—not the caller—should drive commits. This prevents leakage when clients crash.
Hint 3
Token bucket naturally handles variable costs: instead of decrementing by 1, you decrement by N units. Refill rate stays constant.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Variable-Unit Rate Limiter
1. Establish Requirements and Numbers
First, translate scale parameters into concrete resource needs.
Throughput: 50k ops/s splits roughly into 25k reserves/s and 25k commits/s.
Concurrent state: With a 4-second mean duration, you have about 25k × 4 = 100k non-streaming operations in flight. Streaming operations (10% of traffic) last up to 60 seconds: 2.5k/s × 60s ≈ 150k additional leases in the worst case. Total: ~250k concurrent reservations.
Memory footprint: 250k reservations × 200 bytes each ≈ 50 MB. Counter state for 100k accounts across resource/user/account scopes and three time windows adds a few GB. Everything fits comfortably in memory.
Latency target: p99 < 5 ms rules out synchronous distributed consensus (like Spanner writes) for most checks. You need local or single-hop operations.
Clarify what "limit" means: per-minute and per-hour limits are capacity throttles (protect infrastructure), while monthly limits are billing budgets (need durable accuracy).
2. API Design
POST /reserve
{
account_id, user_id, resource_id,
estimated_units, max_units,
priority, idempotency_key
}
→ {
reservation_id,
status: GRANTED | QUEUED | REJECTED,
units_reserved,
expires_at,
retry_after_ms
}
POST /reserve/{id}/commit
{
actual_units,
idempotency_key
}
→ {
charged, refunded,
remaining: { minute, hour, month }
}
POST /reserve/{id}/extend
{
units_consumed_so_far,
additional_units_needed
}
→ { granted, expires_at }
DELETE /reserve/{id}
→ { refunded }
GET /quota/{scope}
→ { limits, consumed, remaining }
Key design choices:
- Idempotency keys on all mutations let clients safely retry without double-charging.
- Estimated units should use historical data: track p95 actual consumption per resource type and use that instead of worst-case maximums. A resource that usually consumes 800 units shouldn't reserve 30,000.
- The gateway commits, not the client. Whatever service executes the work observes actual consumption and drives the commit. This prevents leakage when clients crash.
3. Architecture and Storage
Client → Gateway ──reserve/commit──► Limiter Service
│ (Lua scripts)
↓
Redis Cluster
(sharded by account_id)
│
Gateway ──usage events──► Kafka ──► Aggregator ──► Durable Store
(Spanner/Postgres)
(monthly ledger)
Redis holds hot path state. Use hash tags {account_id} so all scopes for one account live on the same shard. This lets a single atomic Lua script check and debit resource, user, and account scopes together.
Data structures:
| Key | Value |
|---|---|
bucket:{acct}:{scope}:min | Token bucket: {tokens, last_refill_ts} |
window:{acct}:{scope}:hour | Sliding window: 60 sub-buckets (one per minute) |
monthly:{acct}:{scope} | Current month total (cached from durable store) |
lease:{acct}:{id} | {reserved_per_scope, status, expires_at} |
expiry:{acct} | Sorted set of lease IDs by expiration timestamp |
Algorithm choices:
- Token bucket for per-minute limits: Naturally supports variable costs. You debit N units instead of 1. Refill rate = limit/60s. Capacity = limit + burst allowance.
- Sliding window counter for hourly limits: Maintains 60 one-minute buckets. Sum the last 60 minutes with linear interpolation at boundaries. Avoids the double-spend problem of fixed windows.
- Cached monthly total: The durable ledger in Spanner/Postgres is the source of truth. Redis caches the current value and reconciles every few seconds via background sync.
Reserve Lua script flow:
- Clean up expired leases (lazy collection).
- Refill token buckets based on elapsed time.
- Check all scopes (resource, user, account) against their limits.
- If all pass: debit all scopes atomically and create the lease.
- If any fails: apply the policy—hard reject (429), soft allow with overdraft for high priority, or enqueue.
One Redis roundtrip in the same availability zone is 0.5–1 ms, easily meeting the 5 ms p99 target. At 25k reserves/s spread across 10–20 shards, load per shard is light.
4. Reservation Lifecycle and Leak Prevention
Normal flow:
- Reserve E units: Debit the estimate from all scopes. Create lease with 30s TTL (or 2× expected duration for streaming).
- Commit A units: Charge the actual consumption A.
- If A ≤ E: refund (E − A) to all scopes.
- If A > E: debit the additional (A − E) even if buckets go negative. The work already completed; you record the debt rather than reject retroactively. Negative balances throttle subsequent requests until refill catches up.
- Rollback: Refund E completely.
Crash handling:
- Client crashes: The gateway still commits because it observes provider output.
- Gateway crashes before commit: The lease expires. Expiration doesn't blindly refund E because units may have been consumed. Mark the lease
EXPIRED_UNRECONCILEDand refund E. Then reconcile later: the provider's usage log (on Kafka) carries the true consumption keyed byreservation_id. Charge that amount asynchronously. - Expiry mechanisms: Lazy expiry inside Lua scripts, plus a background sweeper scanning the expiry sorted sets.
This ensures no permanent leakage: either commits happen, or expirations refund immediately and usage logs correct the record.
5. Distribution and Hot Accounts
One large account with thousands of resources can overwhelm a single Redis shard. To handle this, use quota chunking (local batching):
- Each gateway instance pulls a chunk of quota from Redis—say 20k units or 5% of the per-minute limit—and holds it in local memory.
- Reservations are served from local state in microseconds.
- Unused quota is returned periodically or when the chunk drains.
Maximum overage is bounded by: num_gateway_nodes × chunk_size. Make chunk size adaptive: shrink it as saturation approaches 100%, and fall back to direct Redis checks near the limit.
For global deployments, replicate read-only quota state to all regions. Writes go to a primary region, then propagate. Accept bounded lag (eventual consistency) for capacity limits, but use synchronous writes to the durable ledger for monthly billing budgets.
6. Failure Modes
Make the failure strategy configurable per account tier:
Default (fail-open with guardrails):
- If Redis is unreachable, the gateway falls back to a local token bucket sized at
limit / num_gateway_nodesper scope. - All usage is logged to Kafka for later reconciliation.
- Operations complete; results are never dropped. Usage is always recorded durably after the fact.
Strict prepaid accounts (fail-closed):
- Reject requests with 503 or 429 if the limiter is unavailable.
- Prevents overspending but risks availability impact.
7. Trade-offs Summary
| Dimension | Strict (linearizable) | Eventual + bounded overage |
|---|---|---|
| Mechanism | Single authoritative shard or consensus | Local chunks, async reconciliation |
| Latency | 1–10+ ms, higher cross-region | Sub-millisecond local checks |
| Accuracy | Zero overage (except A > E gap) | Bounded overage (e.g., ≤ 2%) |
| Availability | Fail-closed on partition | Fail-open with local limits |
| Best for | Prepaid accounts, compliance | Most customers |
Even strict mode cannot avoid the (A > E) gap when actual consumption exceeds estimates. The key is minimizing estimation error through historical tracking and choosing the right consistency model for each limit type: eventual for capacity throttles, strict for billing budgets.
8. Observability
Emit metrics for:
- Consumption rate per scope (units/minute)
- Saturation percentage (consumed / limit)
- Rejection count and retry-after distribution
- Reservation duration histogram
- Estimation error:
|A − E| / A
Surface these in dashboards so accounts can self-pace, and billing pipelines can detect anomalies before month-end.