Shared Storage Allowance Service Across Many Products
System DesignModel answerLast updated
Design a globally consistent service that tracks one storage allowance per user across several products, guaranteeing usage never exceeds the limit while staying fast and available.
Several products (for example a file-storage app and a photo app) share a single storage allowance per user, such as 100 GB in total. Design the central service that tracks and enforces this allowance.
Required operations
- Consume allowance when a product stores data.
- Release allowance when data is deleted.
- Optionally, query the user's current allowance and usage.
Non-functional goals
- A user must never exceed their limit, not even briefly and not under concurrent requests from different products or regions.
- Strong consistency and high availability.
- Low latency wherever possible.
- Scale to millions of daily active users and very high request rates.
Your answer should cover
- API design (consume, reserve, confirm, release, query) and how idempotency works.
- Storage choice and data model, and whether you need ACID guarantees.
- Read and write paths, replication and acknowledgement rules that prevent double-spending.
- Handling concurrency across services and regions.
- A state model for allowance (available, reserved with expiry, occupied) plus timeout and recovery behavior.
- Synchronous vs asynchronous processing, failure handling and retries.
- Sharding, multi-region disaster recovery and failover.
- Whether to cache, and how to keep any cache consistent.
- Backpressure, rate limiting and hot-key mitigation.
- Monitoring, SLOs and capacity planning.
Hints
Hint 1
Treat 'used + reserved <= limit' as a hard invariant and ask which storage and transaction design can enforce it under concurrency, rather than starting from caching or throughput.
Hint 2
Key every table by user so that each operation touches one shard and one transaction; then think about what a conditional update gives you that read-modify-write in application code does not.
Hint 3
Separate operations that must be synchronous (anything that grows usage) from ones that can be delayed safely (releases), and ask what a delayed or lost message does to the invariant in each case.
Hint 4
Model a reservation with an expiry and decide what happens when a confirm arrives after the expiry; also decide whether the service fails open or closed when it is unreachable.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Make the core invariant explicit: for every user, used + reserved <= limit at all times, across all products and regions. Everything else (latency, caching, availability) is designed around not breaking it.
Assumptions to state aloud: 1B users, 100M DAU, about 300k write QPS at peak (reserve, confirm, release), about 1M read QPS (quota bars, pre-checks). Storage is small: roughly 150 B per user row gives about 150 GB, plus perhaps 1-2 TB of TTL-bound reservation and idempotency records. The hard part is coordination, not volume.
2. API and idempotency
Reserve(user, product, bytes, idem_key, ttl) -> reservation_id | QUOTA_EXCEEDED
Confirm(reservation_id, actual_bytes <= reserved, idem_key) -> OK
Release(user, product, bytes | reservation_id, idem_key) -> OK
Consume(user, product, bytes, idem_key) -> OK | QUOTA_EXCEEDED // reserve+confirm for small writes
Query(user, consistency = STRONG | STALE_OK) -> {limit, used, reserved, per_product}
Idempotency: each mutating call has a client-generated key scoped to (user, product, key). The key and its result are stored in the same transaction as the balance change and kept for at least 24 h. A retry returns the stored result. This prevents double-spend on retried reserves and double-credit on retried releases. Confirm or release of an unknown or expired reservation returns an explicit status, never a silent success.
3. Storage and data model
Requirement: linearizable, ACID transactions on a single user's data. Use a range-sharded, consensus-replicated store (Spanner or CockroachDB style), or sharded Postgres/MySQL with synchronous quorum replication. Eventually consistent, last-writer-wins stores are ruled out: two replicas could each accept a reserve and together overdraft.
quota(user_id PK, limit, used, reserved, version)
reservation(user_id, reservation_id, product, bytes, state, expires_at)
usage_by_product(user_id, product, used)
idempotency(user_id, product, key, result, expires_at)
Lead every key with user_id, so one user's rows live on one shard and every operation is a single-shard transaction with no two-phase commit.
Reserve is one transaction:
UPDATE quota SET reserved = reserved + :b
WHERE user_id = :u AND used + reserved + :b <= limit; -- 0 rows => QUOTA_EXCEEDED
INSERT reservation(... state='RESERVED', expires_at=now()+ttl);
INSERT idempotency(...);
The guard inside the WHERE clause is what prevents overdraft. Reading and then writing in application code would race.
4. State model
Available -> Reserved(TTL) -> Occupied -> (release) -> Available, with cancel or expiry returning Reserved to Available.
- Confirm:
reserved -= r; used += actual; unused remainder is freed. - Expiry: a per-shard sweeper finds
state='RESERVED' AND expires_at < now()and releases each one in a transaction guarded by state, so repeated sweeps are harmless. - Long uploads extend the reservation through a heartbeat call.
- Late confirm: re-run the capacity check. If it passes, accept; otherwise the product must reject or delete the upload. This makes expiry safe: it can only make the system conservative, never overdrafted.
5. Read and write paths
Write: product -> regional frontend -> shard leader for the user -> consensus commit to a majority -> ack. Acknowledge only after quorum commit, so a leader failover cannot lose an acknowledged reservation, and the new leader cannot hand the same bytes out twice.
Sync vs async:
- Reserve and consume are synchronous; the caller needs a definitive answer.
- Release can go through a durable queue with retries and idempotency keys. A delayed release only leaves the user with temporarily less free space.
Failure handling: on timeout, retry with the same key. If the service is unreachable, products fail closed for operations that grow usage, while deletes proceed and their releases are queued.
Reads: STRONG goes to the leader (or a read-index/timestamp read). STALE_OK for UI bars reads from followers or a cache with bounded staleness (around 10 s).
6. Sharding, regions, DR
- Hash or range shard by
user_idacross thousands of consensus groups with automatic split and rebalance. - Give each user a home region where the leader lives, with replicas in two other regions (for example a 2+2+1 voter layout across three regions) so a whole-region loss keeps a majority.
- Cost: a cross-region quorum adds roughly 20-60 ms to writes. Reduce it by keeping a voting majority within one geography.
- Failover: leader election takes seconds; affected users are briefly unavailable for writes but never inconsistent. This is a deliberate CP choice.
- If a user relocates, transfer leadership rather than migrating data.
7. Caching
- No cache on the write path: the conditional update is the authority.
- A read cache for
STALE_OKis fine, filled from a change-data-capture stream with a short TTL as a backstop. - Optimization for bulk uploaders: a product reserves a chunk (say 1 GB) and sub-allocates locally. This is safe because the chunk already counts against the limit; return the unused part on completion or expiry. It cuts QPS for bulk backups dramatically.
8. Protection and hot keys
- Per-product token buckets and concurrency limits at the frontend, with load shedding that prioritizes deletes and small writes.
- A single user is serialized on one leader, so a hot user (a shared or service account) is the main risk. Mitigate with client-side chunk leases, request coalescing, and per-key rate limits; for genuinely huge accounts, split the allowance into sub-buckets that are rebalanced periodically while the sum stays under the limit.
9. Operations
SLOs: 99.99% availability, p99 write under about 50 ms in-region. Track reserve latency, quorum commit time, quota-exceeded rate, sweeper lag, queue depth for releases, and replication lag. Run a continuous reconciler that checks used against actual stored bytes per product and alerts on drift. Plan capacity for peak QPS with 2x headroom and per-shard load, and rehearse region failover.
Common mistakes
- Using an eventually consistent store or a cache for admission decisions.
- Doing read-then-write in application code.
- Forgetting idempotency, so retries double-count.
- Failing open during outages, which permits overdraft.
- Ignoring late confirms after reservation expiry.
- Using cross-shard transactions when user-keyed co-location avoids them.