Design a Cloud Storage Quota Accounting Service
System DesignModel answerLast updated
Design a distributed service that tracks per-user byte consumption, enforces storage limits across concurrent multi-part uploads, and reconciles drift against blob storage.
Background
Cloud storage platforms give each user a finite storage budget — a few gigabytes on a free tier, more on paid plans, and a shared pool for team workspaces. Files are uploaded in chunks over sessions that can last minutes or hours. Multiple uploads and deletions may run in parallel for the same account.
Your task is to design a Storage Quota Accounting and Enforcement Service that reliably tracks how many bytes each account has consumed and blocks uploads that would push usage over the limit.
Functional Requirements
- Reserve capacity: when a client starts an upload and declares a file size, hold that many bytes against the account's limit so parallel operations cannot collectively exceed it.
- Commit and release: once an upload finishes successfully, convert the held bytes into permanent usage. If the upload is cancelled, times out, or is abandoned by the client, release the held bytes back to the available balance.
- Reclaim on deletion: when a file is deleted or moved to trash, reflect the freed space promptly (exact policy — whether trashed files still count — is a design choice you should justify).
- Drift correction: provide an asynchronous background process that detects and repairs mismatches between the accounting records and the actual objects present in blob storage.
Non-Functional Requirements
- Latency: the capacity-check-and-reserve step must complete at p99 < 25 ms so upload initiation feels instant.
- Scale: support 1 billion total accounts; 100 million active per day; peaks of 50,000 upload initiations per second.
- Consistency: hard quota guarantees are required — small, bounded overages during traffic spikes are acceptable only if you explicitly justify the trade-off.
- Availability: the quota verification path must target 99.99% uptime; file reads and downloads must never be blocked by quota service degradation.
What Your Answer Should Cover
- API surface: endpoints for reserving, committing, releasing, and querying quota; identify which calls must be idempotent and why.
- Reservation state machine: the full lifecycle of a multi-part upload reservation, including heartbeats, timeouts, retries, and the case where the actual file size differs from the declared size.
- Data model and storage: schema for usage counters, pending reservations, and tier limits; where and what to cache; why the chosen database fits the consistency and latency targets.
- Concurrency near the limit: how the system prevents two concurrent uploads from both "seeing" enough free space when only one can fit.
- Reconciliation pipeline: architecture for continuously or periodically detecting discrepancies and correcting them without disrupting live traffic.
Address trade-offs at each layer. There is no single correct technology choice, but every choice needs a justification.
Hints
Hint 1
Start by naming the core invariant the system must maintain: committed_bytes + reserved_bytes ≤ limit_bytes. Every design decision should be evaluated against whether it preserves that invariant atomically.
Hint 2
The reservation check-and-decrement must happen in a single atomic operation — never a read followed by a separate write in application code. Think about what database primitive (compare-and-set, conditional update, Lua script) gives you that at the latency target.
Hint 3
Drift between accounting records and blob storage is unavoidable. Think about two complementary layers: a streaming path that catches most discrepancies within seconds, and a daily snapshot diff that catches anything the stream missed.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core invariant
Name this up front: committed_bytes + reserved_bytes ≤ limit_bytes, enforced atomically per account on every write. Everything else in the design — reservations, TTLs, idempotency keys, reconciliation — exists to keep that invariant true across long-running uploads and partial failures.
1. Clarifying scope and sizing
Quota owner: an individual user or a shared pool (team workspace, organization). Every file maps to exactly one owner; quota is charged to that owner.
Storage: 1B accounts × ~200 bytes of counter state ≈ 200 GB of quota metadata. That fits comfortably in a sharded strongly-consistent store. No heroics needed.
Write throughput: 50k reservations/s peak, plus roughly the same number of commits, releases, and delete adjustments — call it ~150k quota writes/s total. Sharding by owner_id distributes this naturally; per-row contention is low because most users have only 1–3 concurrent uploads. Shared team pools are the hot-key exception (addressed below).
Latency target: p99 < 25 ms for reservation means at most one synchronous round trip to a single database shard. Cross-shard two-phase commit on the hot path is off the table.
Availability: quota verification must not block reads or downloads. Those paths should bypass the service entirely.
2. API
POST /v1/owners/{owner}/reservations
body: { bytes, idempotency_key, upload_session_id, ttl_s }
200: { reservation_id, expires_at }
409: QUOTA_EXCEEDED { available_bytes }
POST /v1/reservations/{id}:extend { ttl_s }
POST /v1/reservations/{id}:commit { actual_bytes, file_id, idempotency_key }
POST /v1/reservations/{id}:release { reason }
POST /v1/owners/{owner}:adjust
body: { delta_bytes, cause: DELETE|TRASH|RESTORE|RECONCILE, event_id }
GET /v1/owners/{owner}/usage
200: { limit, committed, reserved, trash_bytes }
Every mutating endpoint is idempotent. Retrying commit or adjust with the same idempotency_key or event_id returns the original outcome and has no side effect. This is essential because clients retry on transient failures and delete events may be delivered more than once.
3. Data model
Use Spanner or CockroachDB for the quota tables — strongly consistent, horizontally scalable, single-shard transactions fast enough to hit the latency target. Tables are interleaved under owner_id so every reservation lifecycle operation touches one shard.
quota_account(
owner_id PK,
tier_id,
limit_bytes,
committed_bytes,
reserved_bytes,
trash_bytes,
version,
updated_at
)
reservation(
owner_id FK → quota_account,
reservation_id UUID,
PRIMARY KEY (owner_id, reservation_id),
bytes BIGINT,
state ENUM(PENDING, COMMITTED, RELEASED),
idempotency_key UNIQUE,
upload_session_id,
expires_at TIMESTAMP,
file_id,
created_at
)
INDEX (state, expires_at) -- for the expiry sweeper
quota_ledger(
owner_id, seq, delta_bytes,
cause, ref_id UNIQUE, ts
) -- append-only; used for audits and reconciliation
quota_account holds denormalized counters for fast reads. quota_ledger records every change with its cause. Both are written in the same transaction, so they cannot diverge.
Caching: tier limits and the display usage shown in the UI can be cached at ~30 s TTL (CDN or Memcache). Enforcement always reads from the primary row. Optional fast path: if cached usage is well below the limit (say, < 70%), the service can grant small reservations optimistically and write asynchronously — this is the bounded-overage trade-off the requirements allow. Within 30% of the ceiling it always uses the strict synchronous path.
4. Reservation lifecycle
(none) ──reserve──► PENDING ──commit──► COMMITTED
│ ▲ extend
release/TTL │ └─────────────┘
▼
RELEASED
Reserve: a single conditional update:
UPDATE quota_account
SET reserved_bytes = reserved_bytes + :b
WHERE owner_id = :o
AND committed_bytes + reserved_bytes + :b <= limit_bytes
plus an insert of a PENDING reservation row, all in one transaction. A duplicate idempotency_key returns the existing row.
Extend: each uploaded chunk (or a periodic heartbeat) pushes expires_at forward. A 1-hour TTL with extensions is far better than a 24-hour static TTL — abandoned uploads release their held space quickly.
Commit with size mismatch:
actual ≤ reserved: moveactualfromreserved_bytestocommitted_bytes, release the remainder.actual > reserved: attempt a conditional top-up of the delta in the same transaction. If that fails, reject finalization withQUOTA_EXCEEDED. A small tolerance (e.g., ≤ 1 MB or 1%) avoids failing a multi-GB upload over minor metadata overhead.
Release or expiry: reserved_bytes -= b, state = RELEASED, guarded by WHERE state = 'PENDING'. This ensures the transition happens exactly once and prevents a race between the TTL sweeper and a concurrent late commit.
Late commit after expiry: treated as a fresh reserve + commit. If quota is still available, it succeeds. Otherwise the upload fails cleanly.
5. Concurrency near the limit
If a user has 1 GB remaining and starts three 600 MB uploads simultaneously, the database serializes the three conditional updates on the single quota_account row. Two get QUOTA_EXCEEDED with available_bytes in the response. No application-level read-check-write pattern is ever used — that is precisely the race condition to eliminate.
Redis alternative: Redis counters + Lua script for check-and-increment is faster (~1 ms vs ~8 ms), but acknowledged writes can be lost on failover. Acceptable only when paired with reconciliation and an explicit bounded-overage policy. Name this trade-off; don't pick Redis silently.
Shared team pools (hot keys): shard the pool counter into N sub-counters, each holding 1/N of the limit. Reservations hash to a sub-counter. Periodically rebalance. This keeps per-row contention low at the cost of some implementation complexity.
6. Deletions and reclaim
The metadata service writes an outbox event on deletion; a consumer calls adjust(-size, event_id). Deduplication on event_id makes repeat delivery harmless. Reclaim is visible within seconds.
Whether trashed files count against the quota is a policy choice — Drive counts them, which avoids users exploiting trash as free storage. Either way, moving to trash is committed_bytes -= size, trash_bytes += size; permanent delete is trash_bytes -= size.
Out-of-order events (delete arriving before its corresponding create) are handled by per-file version numbers. The consumer ignores events whose version is stale relative to the ledger.
7. Reconciliation pipeline
Drift is unavoidable — lost events, Redis failover, aborted multipart uploads whose parts persisted, bugs.
Streaming layer (seconds to minutes): blob storage emits CDC records (object_created, object_deleted, owner, size, seq) to Kafka or Pub/Sub. A Dataflow or Flink job maintains per-owner windowed byte sums and compares them against ledger deltas over the same window. Owners with mismatches are enqueued for deep reconciliation.
Daily snapshot diff (catches everything else): export a consistent object-storage inventory (all objects + sizes + owners) and compare it against the ledger. Per-owner discrepancies trigger a corrective adjust(delta, cause=RECONCILE, event_id=snapshot_run_id+owner_id).
Correction write: reconciliation adjustments go through the same adjust endpoint as deletes, inheriting idempotency and ledger logging. Corrections are bounded by the actual discrepancy — they never set an absolute counter, which would risk races with live traffic.
Common mistakes to avoid
- Read-check-write in application code. Always use a conditional update or atomic increment at the database level.
- Long static TTLs. A 24-hour TTL on reservations inflates the apparent used space and blocks legitimate uploads.
- Assuming reconciliation is optional. Drift will happen; design for it from the start, not as an afterthought.
- Blocking reads on quota state. Downloads and file access must never depend on quota service availability.
- Ignoring idempotency. Without it, retried commits or delete events double-count bytes and corrupt balances.