Design a Distributed Usage Enforcement System
System DesignModel answerLast updated
Design a quota enforcement service that handles millions of checks per second across many tenants, covering APIs, consistency trade-offs, hot-key handling, and billing accuracy.
Distributed Usage Enforcement System
Many large platforms expose APIs and managed resources — storage buckets, virtual machines, network bandwidth — and need to prevent any single tenant from consuming more than their allocated share. Your task is to design a service that other internal services call to check and record usage in real time.
Context
The service must handle two meaningfully different kinds of limits:
- Throughput limits — e.g., 5,000 API calls per second, 10M requests per day. These refill over time. A small, bounded overage is acceptable.
- Capacity limits — e.g., 500 GB of stored data, 20 virtual machines. These are held until explicitly released. Exceeding them is not acceptable.
What to design
Define the core API. What operations does the enforcement service expose? Think about what inputs callers need to provide, what responses they get back, and how the interface handles retries safely.
Address concurrency correctness. At very high request rates, multiple callers will race to consume from the same quota simultaneously. How do you prevent incorrect over-admission without serializing everything through a single bottleneck?
Compare strong and eventual consistency. Explain when each is appropriate for this system, what the trade-offs are in latency and accuracy, and how you bound the error in the eventual case.
Handle hot keys. A single large tenant might generate over one million requests per second against a single quota key. How does your architecture remain accurate and fast in that case?
Reconcile usage for billing. Your enforcement counters may drift or reset. How do you ensure that the billing system sees an accurate, deduplicated view of every unit consumed, including any overage that slipped through enforcement?
Discuss availability and latency targets. State reasonable numbers and explain the design choices that let you meet them.
Constraints and scale
- Roughly 10M quota checks per second globally, across roughly 50M distinct quota keys
- p50 latency under 1 ms, p99 under 5 ms for throughput checks; ~10–20 ms is acceptable for capacity changes
- 99.99% availability — the enforcement service must not be a single point of failure for every downstream caller
- Hot-key traffic: a single key may see over 1M QPS
- Overage on throughput quotas should be bounded to roughly 1–5% of the configured limit
- Billing must be exact and idempotent, even when enforcement is approximate
Expected output
A structured walkthrough covering the API, data model, architecture, and a deep dive on each of the five areas above. Discuss trade-offs explicitly and call out common mistakes.
Hints
Hint 1
Split the problem in two before touching architecture: throughput quotas (refilling, eventual consistency is fine) and capacity quotas (held until released, need strong consistency). The right design for each is quite different, and mixing them causes subtle bugs.
Hint 2
The classic concurrency mistake is a read-check-write race where two callers both read 'used=99, limit=100' and both succeed. Think about how a single-writer shard, a conditional atomic update, or a client-side lease each eliminate this race — and what each one costs in latency or complexity.
Hint 3
Enforcement counters and the billing ledger should be separate concerns. Every served request should emit a durable, deduplicated usage event. Billing reads only from that log, so overage that slips through enforcement still shows up accurately — and a reconciliation job can detect counter drift after failovers.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The first move is to split quotas into two types, because they demand different consistency guarantees and the rest of the design follows from that split.
| Type | Examples | Acceptable overage | Consistency |
|---|---|---|---|
| Throughput | 5k req/s, 10M calls/day | ~1–5% | Eventual |
| Capacity | 500 GB storage, 20 VMs | None (or tiny tolerance) | Strong |
Mixing these into a single code path is a common mistake. Treating capacity quotas as eventual leads to real resource over-allocation; treating throughput quotas as strongly consistent causes unnecessary latency at scale.
API Design
# Throughput and allocation checks
CheckAndConsume(key, amount, request_id, mode=THROUGHPUT|CAPACITY)
-> { allowed: bool, remaining: int, retry_after_ms: int }
# Long-running operations where final size is unknown upfront
Reserve(key, amount, request_id, ttl_sec) -> { reservation_id } | DENIED
Commit(reservation_id, actual_amount) -> OK
Release(reservation_id) -> OK
# Internal: hand a client a time-limited slice of a limit
AcquireLease(key, client_id, requested_rate) -> { granted_tokens, expires_at }
# Admin and observability
GetUsage(key) -> { used, limit, window }
SetLimit(key, limit, window, policy) -> OK
A few design decisions worth calling out explicitly:
request_idmakes every call idempotent. A client that retries after a timeout must not double-consume or double-bill. Each shard keeps a short-TTL dedupe set of recently seen IDs.- Reserve/Commit/Release handles uploads or batch jobs where the final amount isn't known until the operation ends. A reservation expires after its TTL if the client crashes, preventing leaked capacity.
retry_after_msin the denial response lets clients implement proper backoff rather than hammering the service and making the hot-key problem worse.
Data Model
- QuotaConfig
(key, limit, window_sec, algorithm, overage_policy, fail_mode)— read-heavy, cached aggressively. - RateCounter
(key, shard_id, window_start, tokens, last_refill_ts)— held in memory on the owning server, replicated asynchronously to a standby. - CapacityUsage
(key, used, reserved, version)— stored in a strongly consistent store (Spanner or equivalent). - Reservation
(reservation_id, key, amount, expires_at, state). - UsageEvent
(request_id, key, amount, timestamp, region)— append-only log, the billing source of truth.
Architecture
Client library embedded in each calling service. For hot keys, the library holds a local token cache or lease and enforces limits in-process with sub-microsecond latency. It batches usage reports back to regional servers.
Regional quota servers sharded by consistent hashing on key. Each shard has a single designated owner that processes updates serially — this makes atomic increments trivial and eliminates most concurrency bugs without locks.
Global aggregator that runs every 100 ms to 1 s. It exchanges per-region consumption totals for globally-scoped keys and redistributes each region's share of the limit based on observed demand. The root sees a handful of lease RPCs per second, not millions.
Capacity store (Spanner or equivalent) for strongly consistent capacity quotas. Writes go through transactions; reads can use slightly stale replicas for dashboards.
Metering pipeline — every usage event flows to Kafka, gets deduplicated by request_id, aggregated, and written to a usage warehouse. Billing and reconciliation jobs read only from here.
Concurrency Correctness
The classic bug is a read-check-write race: two requests both read used=99, limit=100, both check that 99+1 ≤ 100, and both succeed. Three patterns prevent this:
- Single-writer shards — the shard owner serializes all updates for a key. Check and increment become one atomic step. This is the preferred approach for throughput quotas.
- Conditional atomic update —
UPDATE … SET used = used + n WHERE used + n <= limit. A Spanner transaction or a CAS onversionfield. In Redis, a Lua script does the same atomically. This is the preferred approach for capacity quotas. - Idempotency key dedupe — even with the above, a client retry after a network timeout could re-execute. The short-TTL dedupe set on each shard returns the original decision for a duplicate
request_id.
For capacity quotas specifically, the Reserve/Commit/Release pattern adds another layer: capacity is held during the operation and released if the client disappears before committing.
Strong vs. Eventual Consistency
Capacity quotas use the strong path. Every mutation is a transaction. The cost is roughly 10 ms and lower write throughput, which is acceptable because bucket creates and deletes are rare relative to API calls.
Throughput quotas use the eventual path via leases (similar to the Doorman approach). Each region or client acquires a slice of the limit — say, 2,000 tokens/s for 10 s — and enforces it locally. The global aggregator periodically rebalances slices based on observed demand.
Worst-case overage is bounded by the sum of all outstanding, unexpired leases. That bound is a tunable knob: shorter lease durations tighten accuracy but increase traffic to the aggregator. A 1 s lease window typically bounds overage to well under 5%.
Algorithm choice matters here. A token bucket (or GCRA) allows short bursts and is natural for per-second limits. A sliding-window counter avoids the 2x burst problem at fixed-window boundaries and is better for daily or monthly limits.
Hot-Key Handling
A single key at 1M QPS cannot live on one server. Three techniques work together:
- Counter sharding — store
key#0throughkey#N-1, each withlimit/N. Route requests by caller ID or randomly. If one sub-shard is exhausted, try one more before denying. Rebalance split counts periodically based on demand. - Hierarchical leasing — the global root grants budget to regional servers, which grant sub-leases to client libraries. The root sees only a handful of RPCs per second regardless of client traffic.
- Client-side batching — clients consume from a local allotment and sync back to the server every few milliseconds.
Hot keys should be detected automatically using per-shard QPS sketches, and sharding should be applied dynamically. Cold keys stay unsplit for accuracy.
Billing Reconciliation
The critical rule: enforcement counters are not the billing ledger. They will drift, reset on failover, and carry bounded overage. The billing system must not read them directly.
Every request the service admits emits a UsageEvent with request_id. The metering pipeline deduplicates these (with a watermark of, say, 1 hour for late arrivals) and produces exact totals. Billing reads only this pipeline.
Overage beyond the configured limit shows up in the ledger accurately and is handled by the configured overage_policy — absorb it if within tolerance, bill it at an overage rate, or carry it forward to the next window.
A reconciliation job runs periodically to compare ledger totals against live counters and correct drift (common after shard failovers that reset in-memory state). If measured overage consistently exceeds the theoretical lease bound, that signals a bug in the leasing logic, not just normal drift.
Contracts should state explicitly: enforcement is approximate, billing is exact.
Latency and Availability
- The common-case path for a hot throughput key never leaves the client library — it's a local token decrement with sub-microsecond latency.
- Regional server checks should take under 1 ms p99 within a region. Keep QuotaConfig aggressively cached; a config miss shouldn't block a check.
- Fail-open vs. fail-closed is a per-quota configuration. Safety-critical limits (VM counts, financial spend caps) should fail-closed. Convenience limits (API calls for a free tier) can fail-open during an outage, with the overage reconciled later.
- No single quota server should be in the critical path for unrelated services. The client library should handle server unavailability gracefully by falling back to a cached lease or a local conservative estimate.
- Deploy regional servers in at least two zones per region, with the shard owner failing over to the standby within seconds.
Common Mistakes to Avoid
- Using a single Redis key per quota and relying on
INCRwithout a matchingDECRon denial — this conflates check and increment with no rollback path. - Assuming the enforcement counter is exact and feeding it directly to billing — it isn't.
- Not bounding lease overage — without calculating the worst-case sum of outstanding leases, you can't make any accuracy guarantees.
- Ignoring idempotency — a retry storm after a network partition will double-count usage if
request_iddedupe isn't in place. - Treating all quota types the same — the latency and consistency requirements of "did this request go over rate limit" and "does this tenant have room for one more VM" are fundamentally different.