Design a quota service - Drive, Photos and Gmail share one storage limit per user, and one service says yes or no before every upload. It holds space while an upload runs, counts it when the upload is done, and takes it back when a caller disappears. The staff-level signal is one short lock per user that every change of state goes through, so two requests at the same moment, a late commit or a stale cache can never push a user over the limit.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The happy path is quick to draw: read the balance, check that the file fits, subtract. The interview is decided by four questions about what happens when two requests meet, a caller disappears, the numbers drift, or the reads outgrow the database. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | Photos asks for 6 GB and Drive for 7 GB in the same millisecond. 10 GB are left. What happens? | Each request checks the balance, then subtracts | Both read 10 GB before either writes. Both get a yes: 103 GB on a 100 GB plan. The check and the write must be one step, per user |
| DD2 | A caller holds 3 GB, crashes, and commits one minute after the hold timed out. What now? | Holds time out after 5 minutes | |
The same three habits answer all four:
Do not spend your questions on how files are uploaded. Spend them on what the quota service promises.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| One limit per product, or one for all? | One shared pool per user. Drive, Photos and Gmail all draw from it | Requests from different products meet on the same record (DD1) |
| May a user be over the limit for a short time? | No. If two requests together do not fit, one is denied | The check and the hold must be one atomic step. "Fix it later" is not allowed |
| How long does an upload take? | From under a second to many minutes | |
Out of scope (say this out loud): uploading and storing the files, billing and plan changes (we read the limit, we do not sell it), a separate limit per product inside the pool, and several regions that all accept writes. API rate limits are a different problem: a rate limit counts requests per second and forgets them, a quota counts bytes that stay. See Distributed Rate Limiter for that one.
FR1 — Reserve. A product asks for a number of bytes for a user. The answer is yes or no. A yes holds the space. The products that call us are the upstream services on this page.
FR2 — Commit or release. When the upload is done, the caller commits the hold: the bytes now count as used. When the upload failed, the caller releases it: the space is free again.
FR3 — Expire. A hold that nobody commits or releases runs out after a set time, and the space returns by itself.
FR4 — Give back on delete. When a user deletes a file, the product returns its bytes to the pool.
FR5 — Read the balance. Anyone may ask for a user's limit, used bytes, held bytes and free bytes, and for the split per product.
Three words are used all through this page. Committed bytes belong to files that exist. Held bytes belong to uploads that are running. Available is what is left: the limit minus committed minus held.
The key principle behind all five
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| I read 10 GB available | 10 GB are available when I write | Another request may have taken them in between. Reading and writing must be one step |
NFR1 — The limit holds, always. Committed plus held is never more than the limit, for every user, at every moment, also during crashes and retries.
NFR2 — Speed. A reserve answers within 10 ms at p99. Every upload on the platform waits for it.
NFR3 — Scale. 500,000 writes a second (reserve, commit, release) and 2,000,000 balance reads a second at peak.
NFR4 — Nothing committed is lost, nothing held is stuck. Committed bytes survive any crash. A forgotten hold is back in the pool a few minutes later.
NFR5 — Availability, fail closed. 99.9% of the time the service answers. When it does not, the upload does not start.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Users | 50 million, 5 million of them active at a time |
| Writes at peak | 500,000 a second: about 250,000 reserves, each followed by one commit or release |
| Balance reads at peak | 2,000,000 a second: 4 reads per write |
| Live holds | Most uploads are small and finish in seconds. With an average of 4 seconds: 250,000 × 4 = 1 million holds at a time |
| Quota rows | About 100 bytes × 50 million users = 5 GB |
The number that identifies the real system is not on this list. It is how many requests one user sends at the same time:
whole platform 500,000 writes a second spread over 100 shards: an ordinary load
one user 2 or 3 requests in the same millisecond: the whole problem
the data 5 GB would fit in the memory of one machine
The data is small and the total load splits cleanly by user. What is hard is that Photos and Drive can ask for the same user's last gigabytes in the same instant, and that exactly one of them may get them. The shard count, the 4-second average and the row sizes are illustrative assumptions.
Interviewer signal: candidates who say "500,000 writes a second, so we need a fast counter in Redis" have missed the system. Candidates who say "the load is easy to split by user, the hard part is two writers on one user's record, and a hold that outlives its caller" have found it.
Three ideas shape everything:
If we subtract when the upload starts and the upload fails, the user has lost space for nothing. If we subtract when it ends, two uploads can both start into the same free space. So there are two steps. A reservation holds the space at the start. A commit turns the hold into used bytes at the end. A hold has an expiry time, so a caller that disappears cannot keep it.
The rule "committed plus held is never more than the limit" is a rule per user. So the lock is per user too: one row in the database, locked for about 2 milliseconds while the service reads the state, checks the rule and writes. Two requests for alice wait for each other. A request for bob never waits for alice.
The store keeps the limit, the committed bytes and each hold. What is free is always worked out from those: limit minus committed minus the live holds. A stored "available" column would be a second copy of the truth, and two copies drift apart.
The core recognition
This is an admission gate with a two-step protocol. Reserve, then commit or release, with a timer behind the hold. Every step is one short transaction on one user's row.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| Reserve first, commit later | Space is held while the upload runs, and a failed upload costs the user nothing |
| A row lock on the user's quota row | Check and write become one step. Two requests for one user cannot both see the same free space |
Two tables carry the design:
user_quotaandreservation. The first says what a user may use and has used. The second says what is on hold right now.
One row per user. Every write for this user locks this row first.
Swipe to see all columns
| user_quota | ||
|---|---|---|
| Field | Type | Comment |
user_id | STRING | Key, and the shard key |
limit_bytes | BIGINT | The plan, read from billing. alice: 100 GB |
committed_bytes | ||
There is no "available" column and no "held" column. Both are computed.
One row per hold. The status is its whole life: it starts as RESERVED and ends exactly once.
Swipe to see all columns
| reservation | ||
|---|---|---|
| Field | Type | Comment |
reservation_id | STRING | Key, for example res_1 |
user_id | STRING | Whose space is held |
service_id | ||
An idempotency key is a name the caller gives to one attempt. If the same request arrives twice with the same key, the second one returns the first one's result instead of making a second hold.
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
| Service usage | Per user and product: committed_bytes | The split for the storage page: Drive 50 GB, Photos 30 GB, Gmail 10 GB |
| Usage ledger | One row per commit, delete or correction: user, product, resource, delta_bytes, reason, idempotency_key | |
Three indexes matter: (user_id, status) to add up one user's live holds, (status, expires_at) so the Sweeper finds expired holds without reading the table, and the unique (user_id, idempotency_key).
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Quota store (PostgreSQL, 100 shards by user) | Quota rows, reservations, usage per product, the ledger | The source of truth. All rows of one user are on one shard, so every operation is one local transaction |
| Balance cache (Redis) | One small entry per active user | A copy. Deleted after every write, refilled by the next read. Never used to approve |
Why a relational database: the reserve must read a row, add up a few other rows, check a rule and insert, all as one atomic step. A transaction with a row lock does exactly that. A key-value store with conditional writes handles "change this one item if it still looks like this" well, but the sum over the holds does not fit into one condition.
The service is internal. Only other services call it, and the reserve sits in the path of every upload, so the calls use gRPC: a compact binary protocol with typed requests.
Swipe to see all columns
| The calls | ||
|---|---|---|
| Call | Who calls it | What it does |
ReserveQuota | A product, before an upload | Takes user, product, resource, requested_bytes and an idempotency key. Answers approved or not, and for a yes the reservation_id, expires_at and what remains. A no writes nothing |
CommitReservation | A product, after the upload | |
The contract in one sentence: a yes from ReserveQuota is a hold with an end time, and the caller owes us a commit or a release. If it sends neither, the hold runs out.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 reserve (black), Phase 2 commit or give back (blue), Phase 3 take back a forgotten hold (green), Phase 4 read the balance (purple). All four follow one user, alice, for sixteen minutes. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Reserve (FR1) | Black | Photos asks for 6 GB for a video. The service locks alice's row, checks, and writes a hold | One hold of 6 GB. No file yet |
| Phase 2: Commit, or give back (FR2, FR4) | Blue | The upload is done and the hold becomes used bytes. Then alice deletes a 4 GB file | Committed 92 GB, no holds |
How to read the picture
Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: say yes or no within a few milliseconds, and make a yes impossible to give twice.
ReserveQuotaUpstream services (Photos) → Quota serviceNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | Photos calls ReserveQuota: user alice, resource vid_7, 6 GB, idempotency key k-vid7. | Nothing yet |
| 2 | The Quota service opens a transaction and locks alice's quota row. It reads: limit 100 GB, committed 90 GB. | The row is locked. Nothing written |
| 3 | It adds up alice's live holds: 0. It checks the rule: 90 + 0 + 6 = 96, which is not more than 100. | |
Why it is built this way
Because then the number "used" would include files that do not exist. If the upload fails, somebody must remember to add the 6 GB back, and if that somebody has crashed, they are gone for good. A hold is a separate row with its own end time. It can be committed, released or left to run out, and in every case the used bytes only ever count real files.
Goal: turn a hold into used bytes exactly once, and return bytes when a file is deleted.
CommitReservationUpstream services (Photos) → Quota serviceNothing is written in this step.
Swipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | At 12:03:00 the upload is done. Photos calls CommitReservation: res_1, actual size 6 GB. | Nothing yet |
| 2 | The Quota service locks alice's row and reads res_1. It is still RESERVED, and 6 GB is not more than it holds. | Nothing |
Why it is built this way
RESERVED can be committed. That one check is what makes a late commit harmless (DD2).ReleaseReservation sets the hold to RELEASED and the space is free in the same moment. The timer is only for callers that cannot call.Because the space was already taken out of "available" when it was held. Available is the limit minus committed minus held. Before the commit that is 100 − 90 − 6 = 4 GB. After it, 100 − 96 − 0 = 4 GB. The commit moves bytes from one bucket to the other. Only the reserve, the release, the expiry and the delete change what is free.
Goal: a caller that disappears keeps its hold for a few minutes, not for ever.
ReserveQuotaUpstream services (Drive) → Quota service → Quota storeapproved: res_2res_2new rowalice (shard 37)updateSwipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | At 12:10:00 Drive reserves 3 GB for the archive zip_5. Approved, as in Phase 1. | res_2: RESERVED, 3 GB, expires 12:15:00. Available 5 GB. Version 44 |
| 2 | At 12:11 Drive's upload worker dies. It sends no commit and no release. | Nothing. res_2 still holds 3 GB |
| 3 | ||
Why it is built this way
RESERVED. It still counts, and Drive could still commit it. It ends at the moment the Sweeper writes EXPIRED, and not before. One column, one answer.It is the price of a clear rule. At 12:16:00 the 3 GB may already belong to somebody else's hold, so the service cannot simply accept. Drive reserves again. If there is room, it gets a new hold, commits it, and the user notices nothing. If there is no room, Drive removes the uploaded bytes and tells alice that her storage is full. Uploads that often run longer than 5 minutes should get a longer hold from the start.
Goal: answer 2 million reads a second without touching the path that approves uploads.
GetQuotaStateUpstream services → Quota serviceNothing is written in this step.
Swipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | alice opens her storage page. The page calls GetQuotaState for alice. | Nothing |
| 2 | The Quota service looks in the Balance cache. The entry is not there: the last write deleted it. | Nothing |
| 3 | It reads the truth from the Quota store with a plain read, no lock: limit 100 GB, committed 92 GB, held 0, version 45. | |
Why it is built this way
ReserveQuota does not look at it. A page may show "8 GB available", and the next reserve may still be denied because another upload got there first. The page was not wrong. It was a moment old.Because two writers can finish in one order in the database and reach the cache in the other order. Then the older numbers land last and stay. A delete has no such problem: whatever order the deletes arrive in, the entry is gone, and the next read gets the current state from the store. DD4 closes the one gap that remains, a slow reader that fills the cache with numbers it read before the write.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: it is 12:00:00. alice has 10 GB available: 90 of 100 GB are committed. In the same millisecond Photos asks for 6 GB for vid_7 and Drive asks for 7 GB for the backup bak_3. The requests land on two servers of the Quota service, Q1 and Q2. 6 + 7 = 13 GB do not fit. Who gets a yes?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Each server reads alice's balance, checks that the request fits, and writes a hold.
Where it breaks. Q1 reads 10 GB available. Q2 reads 10 GB available, because Q1 has not written yet. Q1 says 6 fits and writes. Q2 says 7 fits and writes. Now 90 + 6 + 7 = 103 GB are promised on a 100 GB plan, and both uploads start. Each server did everything right. The time between the read and the write is the hole, and at 500,000 writes a second something falls into it every day.
The idea. Read without a lock and remember the row's version. Write the hold with a condition: only if the version is still the one I read. If the write is refused, read again and decide again. This is called optimistic concurrency: assume nobody interferes, and check at the end.
What it fixes. The overshoot. Q1 and Q2 both read version 40. Q1's write goes through and makes it version 41. Q2's write finds version 41 and writes nothing. Q2 reads again, sees 4 GB available and denies the 7 GB. Correct.
What it still misses. Every loser starts over. alice's phone backs up four photos at once: four reserves read the same version, one wins, three try again, then two, then one. That is 4 + 3 + 2 + 1 = 10 transactions for 4 holds. With twenty at once it is 210 for 20. The retries arrive together again, so they collide again, and nobody can say how long the last one waits. The busier a user is, the more work each request costs.
The key idea. Do not find out afterwards that somebody else was there. Stand in line before you look. The line is one row: alice's quota row.
How it works
SELECT ... FOR UPDATE on the user's quota row. Q1 sends it first and gets the lock.This is : assume somebody will interfere, and keep them out for the two milliseconds that matter.
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
SELECT the balance of aliceQuota server Q1 → Quota storelimit 100 GB, committed 90 GB, held 0Nothing is written in this step.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: read, check, write | Good: write if unchanged | Great: lock the row | |
| What the second server sees | The old balance | The old balance, then a refused write | The new balance, after a short wait |
| Photos 6 GB and Drive 7 GB | Both approved: 103 GB | One approved, one denied | One approved, one denied |
Check it against the scenario
| Two requests for alice's last 10 GB | |
|---|---|
| Situation | Outcome with the Great option |
| Photos (6 GB) gets the lock first | Photos is approved. Drive waits 2 ms, sees 4 GB available, and is denied |
| Drive (7 GB) gets the lock first | Drive is approved. Photos waits, sees 3 GB available, and is denied |
| Photos sends its request twice with the key k-vid7 | The second one finds res_1 under the unique key and returns it. One hold |
| Q1 crashes while it holds the lock | The database ends its transaction and frees the lock. Nothing was written. Photos retries with the same key |
| A request for bob arrives at the same moment | |
The trade-off to name. Requests for one user run one after the other. For a person with two or three uploads that is a wait of a few milliseconds. For twenty at once the last one waits 40 ms, which is over the 10 ms target, so a client that uploads a whole folder should send one reserve for the batch. And a lock that is held must stay short: the transaction does reads and one insert, and never calls another service while it holds the row.
An atomic decrement does close the gap of the Bad option: check and subtract become one command. But the hold then lives only in memory. If Redis restarts, nobody knows which uploads were running and how much they held. And the hold needs more than a number: a status, an owner, an end time, a key for retries, and a commit that moves bytes into a durable total in the same step. That is a transaction over several rows, and a database already does it. Redis keeps its place as the read cache.
"The invariant is per user: committed plus reserved never exceeds the limit. Two services can ask for the same user at once, so check and write must be atomic. I take a row lock on the user's quota row with select for update, sum the active reservations, check the invariant and insert the reservation in one transaction. The lock is held for a couple of milliseconds and never during the upload. Contention is per user, and since I shard by user ID, one busy user only slows down that user's own requests."
Follow-up: "Why not optimistic concurrency?" — It is also correct, but under contention every loser retries, so a user with many parallel uploads does a quadratic amount of work and the tail latency has no bound. With a lock, requests wait in line and each one runs once.
Scenario: at 12:10:00 Drive holds 3 GB for zip_5: res_2, with expires_at 12:15:00. alice has 5 GB available. Without the hold it would be 8. At 12:11 Drive's upload worker stalls. At 12:15:40 Photos asks for 8 GB. At 12:16:00 Drive's upload finishes after all, and Drive commits res_2.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The caller reserved, so the caller commits or releases. The service waits.
Where it breaks. A worker that has crashed sends nothing. At 12:15:40 Photos asks for 8 GB, and the service counts 92 + 3 + 8 = 103: denied, although only 92 GB are real files. The 3 GB are gone until somebody repairs the row by hand. If only 1% of 250,000 reserves a second are abandoned, 2,500 holds get stuck every second. Users pay for space that nobody is using.
The idea. Give every hold an end time. A Sweeper marks holds that are past it as EXPIRED, and the space returns. A commit adds the uploaded bytes to the total, as before.
What it fixes. The stuck hold. At 12:15:30 the Sweeper ends res_2 and alice has 8 GB available. At 12:15:40 Photos reserves 8 GB and is approved: 92 + 8 = 100.
What it still misses. The caller that was slow, not dead. At 12:16:00 Drive commits res_2 with 3 GB. The commit does what it always does: it adds the bytes. Committed is now 95 GB, Photos still holds 8, and 95 + 8 = 103 GB. The same 3 GB were given out twice, once to Drive at 12:10 and once to Photos at 12:15:40. The timer and the commit each work. Together they break the limit.
The key idea. A hold ends exactly once. Whoever ends it must first take the user's lock and look at the status. Whoever comes second finds a status that is already final.
How it works
RESERVED and has three possible endings: COMMITTED, RELEASED, EXPIRED. An ending is never changed.RESERVED sets it to EXPIRED. One transaction per hold.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. A dashed box is not part of every design.
ReserveQuotaDrive → Quota serviceapproved: res_2. Available: 5 GBres_2new rowSwipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: no end time | Good: timer, blind commit | Great: the status decides | |
| A caller that crashed | Holds the space for ever | Freed after 5 minutes, plus at most 30 s | The same |
| A commit after the hold expired | Cannot happen | Accepted: 103 GB | Refused: reserve again |
Check it against the scenario
| res_2 between 12:15 and 12:16 | |
|---|---|
| Situation | Outcome with the Great option |
| Drive never comes back | The Sweeper ends res_2 at 12:15:30. alice has 8 GB available again |
| Drive commits at 12:15:10, past the end time but before the Sweeper | The status is still RESERVED, so the commit is accepted. The Sweeper later skips the hold |
| Drive commits at 12:16:00, and Photos has taken the space | RESERVATION_EXPIRED. The new reserve is denied. Drive removes the file |
| Drive commits at 12:16:00, and nobody took the space | |
The trade-off to name. An upload that was slow can finish and still be refused. The service chooses a clear rule over a kind exception. The end time is a guess about how long uploads take: too short, and good uploads are refused; too long, and a crash blocks space for longer. So the time is set per kind of operation, and a caller that is alive can ask to extend its hold.
It can be made to work, and then the clock is part of every check: the reserve must ignore holds past their time, and the commit must refuse them, both under the lock and both with the same clock. Two servers whose clocks differ by a second then disagree about whether a hold is alive. With a status there is nothing to disagree about. One writer sets EXPIRED once, under the lock, and everyone else reads it. The price is that a forgotten hold lives up to 30 seconds longer.
"Reservations are durable rows with an expiry time. A sweeper scans an index on status and expiry every thirty seconds and reclaims each expired reservation in its own transaction. The race I care about is a late commit against the sweeper. Both lock the user's quota row and re-check the reservation's status under the lock, so exactly one transition happens. If the sweeper wins, the commit fails with an explicit error and the caller must reserve again. If the commit wins, the sweeper skips the row."
Follow-up: "What does the caller do with a file that is already uploaded?" — It reserves again. If that is approved it commits and the user sees nothing. If it is denied, the caller removes the bytes and reports that storage is full.
Scenario: suppose the delete of Phase 2 went wrong. Drive removed doc_2, 4 GB, and crashed before it called us. Our record for alice says 96 GB, with Drive at 50. Her files add up to 92 GB, with Drive at 46. And there is bob, on a 15 GB plan: our record says 14 GB, but a bug in Gmail stored 2 GB without a commit, so his files add up to 16 GB. Each night at 02:00:00 every product can report the bytes it really stores per user.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Every upload and every delete goes through the service, so its numbers are right.
Where it breaks. They are right until one call is lost. alice wants to upload 6 GB. The service sees 4 GB available and says no. She really has 8. Nobody will ever find out, because nothing compares the record with the files. bob keeps 16 GB on a 15 GB plan for the same reason. Each lost call and each bug adds to the gap, and the gap never closes by itself.
The idea. A nightly job takes the report of real bytes and writes it into the quota row.
What it fixes. Old errors. alice's 4 GB come back, bob's 2 GB are counted.
What it still misses. The report is a photo of 02:00:00, and the service keeps working. At 02:00:05 Photos commits a 2 GB upload for alice: the record says 98 GB. At 02:00:10 the job writes 92. The commit is wiped out: the record says 92, the files are 94. The job repaired an error of 4 GB and made a new one of 2 GB, in the dangerous direction, because alice can now go over her limit. And nothing says what was changed, by how much, or why.
The key idea. Only correct a user who has been quiet since the report was taken. Record the correction before making it. Add or subtract the difference instead of replacing the number.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. A dashed box is not part of every design.
delete doc_2, then crashUpstream services (Drive)Nothing is written in this step.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: trust the counters | Good: overwrite nightly | Great: correct by the difference | |
| When the numbers are compared | Never | Every night | Every night, quiet users only |
| A commit that lands during the job | — | Wiped out | The user is skipped this round |
Check it against the scenario
| The Reconciler meets alice and bob | |
|---|---|
| Situation | Outcome with the Great option |
| alice's row changed after the report was taken | Skipped. She is looked at again in the next round, with a new report |
| alice has a live hold | Skipped as well. A correction under a running upload could break the rule |
| alice is quiet: record 98 GB, files 94 GB | Ledger row first, then committed 98 to 94 GB. She has her 4 GB back |
| bob is quiet: record 14 GB, files 16 GB | Plus 2 GB at once. He is over his plan, keeps his files, and cannot upload |
| The Reconciler crashes halfway | |
The trade-off to name. A user who is always uploading is never quiet and is skipped again and again. For such users the job needs a second way in, for example a report that names the last change it includes, so that record and files can be compared at the same point. And corrections treat the symptom. The cure is at the caller: a product that deletes a file should record "tell the quota service" in the same transaction and repeat the call until it is answered.
Because they risk different things. If we counted too much, the user is short of space she paid for. That is annoying, and correcting it only gives space back. If we counted too little, the user can pass the limit, which is the one thing this service exists to prevent. So an upward correction is applied the moment it is known. But the files are already there, and deleting a user's files to fix our counting would be far worse than the error. The service blocks new uploads and lets the user decide what to remove.
"Tracked usage will drift from real usage: lost release calls, bugs, partial failures. I run a daily reconciliation job off-peak. For each user it compares our committed bytes with what the upstream services report. It skips users with active reservations or changes since the snapshot and revisits them later. When it finds drift it writes an audit entry first and then applies the correction as a delta under the same row lock. Over-counting is corrected down and frees space. Under-counting is corrected up immediately, and we block new uploads instead of deleting files."
Follow-up: "Why not just overwrite our number?" — A commit that lands between the snapshot and the write would be lost, which creates under-counting. And without an audit entry nobody can explain why a user's number jumped.
Scenario: every storage page and every "do I have room?" hint reads the balance: 2,000,000 reads a second, four times the writes. alice has just committed 6 GB. And there is the team account acme, one pool shared by 20,000 employees: when its cache entry disappears, 3,000 readers ask within the same 50 ms.
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The database has the right numbers. Read them there.
Where it breaks. 2,000,000 reads a second over 100 shards are 20,000 reads a second per shard, on top of 5,000 writes. The reads compete with the reserve transactions for the same machines, and the reserve p99 passes 10 ms. Uploads get slower because somebody is looking at a progress bar. To keep reserves fast, the database would have to be four times larger, for a number that changes only when a user uploads or deletes.
The idea. A read looks in Redis first. On a miss it reads the store and keeps the answer for 60 seconds.
What it fixes. The load. The store now sees about one read per active user per minute.
What it still misses. Three things. First, alice commits 6 GB and her page still says "10 GB available" for up to a minute. Second, the number is now so cheap that products start to trust it: Photos sees "10 GB available" and uploads without a reserve, Drive does the same, and alice is at 103 GB. Third, when acme's entry times out, 3,000 readers miss within 50 ms and send 3,000 identical queries to one shard. This is a thundering herd: many callers doing the same expensive thing at the same instant.
The key idea. Keep the cache fresh by removing an entry the moment it becomes wrong. Let one caller refill it. And never let it answer the question "may I upload?".
How it works
ReserveQuota never reads the cache. If Redis is down, pages show the balance late or not at all, and every upload still gets a correct yes or no.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure. A dashed box is not part of every design.
SELECT the balance of aliceUpstream services → Quota service → Quota storelimit 100 GB, committed 96 GB, available 4 GBNothing is written in this step.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: read the database | Good: cache with a timer | Great: delete on write | |
| Where reads go | The database | The cache, misses to the database | The same |
| Reads on one shard | 20,000 a second | About one per active user per minute | One per user after each write |
Check it against the scenario
| Reads around a write | |
|---|---|
| Situation | Outcome with the Great option |
| alice commits 6 GB and reloads her page | The commit deleted her entry. The reload reads the store: 4 GB available |
| acme's entry is deleted while 3,000 people have the page open | One read goes to the store. 2,999 wait a few milliseconds for its answer |
| A reader read version 41, the commit made version 42, then the reader fills the cache | The fill is refused or replaced: the entry never goes back to an older version |
| The delete of a cache entry fails | The entry is wrong for at most 60 seconds, then it runs out |
| Redis is down | |
The trade-off to name. A user who writes all the time gets little from the cache: every write deletes the entry, and the next read goes to the store. That is acceptable, because such a user is rare and one read is cheap. The stronger rule is the last one. The cached number will always be tempting as a shortcut for "is there room?". It may be used to grey out a button. The upload itself must still ask the store.
No. The page showed the state at the moment it was read. Between that moment and the reserve, another upload may have taken the space, from another device or another product. The reserve looked at the state under the lock, and that is the only look that counts. A good client treats the shown balance as a hint and is ready for a no.
"Balance reads are four times the writes and tolerate a little staleness, so they go through a Redis cache. Writes always go to the database first and then invalidate that user's entry. Reads fall through to the database on a miss and repopulate. To stop a thundering herd on a hot key I coalesce concurrent misses into one query. The cache is display only. The reserve path never reads it, because the admission decision must be made on locked, current state."
Follow-up: "What if Redis goes down?" — Reads degrade: they hit the database behind a rate cap or return no number. Reserve, commit and release do not depend on Redis at all.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| The user upgrades or downgrades the plan | The limit comes from billing and is kept in the quota row. It is refreshed every few minutes, and before a reserve if it is old. An upgrade simply adds room. After a downgrade below the used bytes, nothing is deleted: new uploads are denied until the user is under the new limit |
| The quota service is down | Fail closed: the product refuses the upload. Each product has a circuit breaker, so after a few failures it stops waiting for timeouts and fails fast. A product may be allowed a small, bounded exception, for example 1% over the limit during planned maintenance, which the Reconciler corrects afterwards |
| One product uses the whole pool | Sub-limits per product are out of scope. Soft signals help: an alert when one product passes 80% of a pool. Hard limits per product belong to the product, not to this service |
| Several regions | |
For the patterns behind this page, see Reservation and Availability Check, Locking and Concurrency Control and Idempotency and Exactly-Once, and the Caching building block for the read path.
A counter that is lowered at the start of an upload counts files that may never exist. Hold the space with a reservation and count it at the commit.
Two requests both read the same free space and both get a yes. The check and the write must be one step, under a lock on the user's row.
A lock that lasts minutes blocks every other request for that user. The lock covers the 2 ms check. The upload is covered by the hold.
A crashed caller then keeps the space for ever. Every hold has an expiry, and a Sweeper takes back what nobody ended.
A commit that arrives after the hold expired adds bytes whose space was already given away. Commit only a hold that is still RESERVED, and refuse the rest.
A stored "available" is a second copy of the truth and will drift from the first. Compute it from the limit, the committed bytes and the live holds.
The cached balance is a moment old, and two products that trust it both upload. The cache fills pages, and the store alone says yes.
A commit that lands during the job is wiped out, and nobody can see what changed. Skip busy users, write a ledger row, and correct by the difference.
The shape of a strong answer: reserve before the upload, under a short lock on the user's row. Commit after it, and only a hold that is still alive. Give every hold an end time and a Sweeper. Serve the balance from a cache that is deleted on every write and never asked for a decision. Compare the record with the real bytes every night and correct by the difference. When the service cannot answer, do not upload.
Hold first, count later
A reservation holds space for an upload that is running. A commit turns it into used bytes. A hold that nobody ends runs out after 5 minutes and is taken back.
One lock per user
Reserve, commit, release, expire and correct all lock the same row and look at the state under the lock. Two requests in the same millisecond, or a commit and the Sweeper, can never both win.
The store decides
The cache is a copy for display. The products' own numbers are checked once a day. A yes to an upload comes from one place only, and no answer means no.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | Names the two records, the user's quota and the reservations, and explains reserve then commit. Says why lowering a counter is not enough for an upload that takes minutes |
| Mid-level | Keeps reservations in their own table. Explains how committed plus held stays under the limit. Brings up the Sweeper and at least one failure, such as a crashed caller that leaves space held |
| Senior | Goes to the hard parts unasked: the row lock and what it costs, the late commit against the Sweeper, drift and its audit trail, and fail closed with one bounded exception |
These aren't toy problems — they reflect real infrastructure challenges at companies where many products share one account. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
Why does the service hold space with a reservation instead of lowering a counter when the upload starts?
Question 2 of 10
What does ReserveQuota lock?
Question 3 of 10
alice has 10 GB available. In the same millisecond Photos asks for 6 GB and Drive for 7 GB. What happens with the row lock?
Question 4 of 10
Why is there no column for the available bytes?
Question 5 of 10
The Sweeper ended a hold at 12:15:30. At 12:16:00 the caller commits it. What does the service do?
Question 6 of 10
A hold was made for 6 GB. The file ends up at 7 GB. What does CommitReservation do?
Question 7 of 10
A commit and the Sweeper reach the same hold in the same moment. Why can only one of them end it?
Question 8 of 10
Which statement about the Reconciler is NOT true?
Question 9 of 10
The Balance cache says alice has 10 GB available. Photos wants to upload 6 GB. What must Photos do?
Question 10 of 10
A product wants to start an upload, and the quota service does not answer. What is the default?
| Right, but the late commit still arrives. If it simply adds its bytes, space that was already given to someone else is counted twice |
| DD3 | Your record says 96 GB. The files add up to 92 GB. How do you repair it? | Overwrite our number with the real one every night | A commit that lands during the job is wiped out. Skip users who are busy, write down every correction, and correct by the difference |
| DD4 | The balance is read 2 million times a second. How do you serve that? | Put Redis in front | Yes, for display. But a cached number is old by nature. It may fill a progress bar. It may never approve an upload |
| Space must be held while the upload runs: a hold, then a commit (Phase 1, Phase 2) |
| What if a caller crashes with a hold? | The hold times out after a few minutes and the space returns | Holds are stored rows with an expiry time, and something must take them back (DD2) |
| How often is the balance read? | About four times as often as it is written | Reads get their own path with a cache (DD4) |
| What if the quota service does not answer? | The upload is refused | Being correct comes before being available. This is called fail closed |
| The reserve was approved | The bytes are used | The upload may fail or never finish. A hold is a promise of space, not a file |
| The hold timed out | The upload stopped | The caller may only be slow. It can still come back and try to commit |
| A product called us for every upload | Our number matches its files | Calls get lost and products have bugs. Only a comparison shows it |
| The cache says there is room | There is room | The cache is a copy from some moment ago. Only the store knows now |
| Hold rows |
| About 200 bytes × 1 million live holds = 200 MB |
| Shards | 100, split by user: 5,000 write transactions a second and 500,000 users each |
| Reads without a cache | 2,000,000 / 100 = 20,000 reads a second per shard, four times its writes |
| Cache | 5 million active users × 100 bytes = 500 MB |
| Holds as rows with a status and an expiry time |
| A crash loses nothing. A hold that nobody ends can be found and taken back |
| The status decides, not the clock | A hold ends exactly once: committed, released or expired. A late commit meets a status that is already final |
| Shards by user | Every transaction touches one shard. No transaction ever spans two |
| A cache for reads, deleted after every write | 2 million reads a second stay away from the database. The cache never approves anything |
| A nightly comparison with the real bytes | Lost calls and bugs are found and corrected, with a record of each correction |
| Fail closed | No answer means no upload. A wrong yes cannot be taken back, a refused upload can be retried |
BIGINT |
| Bytes of files that exist, over all products |
version | BIGINT | Goes up by one with every change to this user's row or holds |
limit_refreshed_at | TIMESTAMP | When the limit was last read from billing |
updated_at | TIMESTAMP | When this user's state last changed |
STRING |
| Who holds it: drive, photos or gmail |
resource_id | STRING | What it is for, for example vid_7 |
requested_bytes | BIGINT | How much is held |
status | ENUM | RESERVED, then COMMITTED, RELEASED or EXPIRED |
idempotency_key | STRING | Chosen by the caller. Unique together with user_id |
expires_at | TIMESTAMP | After this moment the Sweeper may end the hold |
| A history of every change to committed bytes. It makes a repeated delete call harmless and shows what a correction changed (DD3) |
| Cache entry | quota:alice holds limit, committed, held and the row's version, for 60 seconds | A copy for display (DD4) |
Takes reservation_id and actual_bytes. The real size may be smaller than the hold, never larger. Fails with RESERVATION_EXPIRED if the hold has already ended |
ReleaseReservation | A product, when the upload failed | Ends the hold at once. Calling it for a hold that has already ended does nothing |
ReleaseConsumedQuota | A product, when a file is deleted | Takes user, product, resource, release_bytes and an idempotency key. Lowers the committed bytes, never below zero |
GetQuotaState | Any product, for display | Returns limit, committed, held and available. Served from the cache |
GetServiceBreakdown | The storage page | Returns committed and held bytes per product |
| Phase 3: Take back a forgotten hold (FR3) |
| Green |
| Drive holds 3 GB and goes silent. The Sweeper ends the hold |
| The 3 GB are free again |
| Phase 4: Read the balance (FR5) | Purple | alice opens her storage page. The balance comes from the store once, then from the cache | One cache entry |
| Nothing |
| 4 | It inserts the hold and commits the transaction. The lock is free again, about 2 ms after step 2. | res_1: RESERVED, 6 GB, expires 12:05:00. Version 40 to 41 |
| 5 | It deletes alice's entry in the Balance cache. | The cache entry is gone |
| 6 | It answers Photos: approved, res_1, expires at 12:05:00, 4 GB remaining. Photos starts the upload. | Nothing |
| In the same transaction it moves the bytes from held to committed. |
res_1: RESERVED to COMMITTED. Committed 90 to 96 GB. Photos 30 to 36 GB. One ledger row. Version 42 |
| 4 | It deletes alice's entry in the Balance cache. | The cache entry is gone |
| 5 | It answers Photos: committed, 4 GB remaining. | Nothing |
| 6 | At 12:04:00 alice deletes doc_2, a 4 GB file in Drive. Drive calls ReleaseConsumedQuota with the key k-del-doc2. | Committed 96 to 92 GB. Drive 50 to 46 GB. One ledger row. Version 43 |
RESERVEDexpires_at| Nothing |
| 4 | The Sweeper locks alice's row and looks at res_2 again. It is still RESERVED, so it becomes EXPIRED. One transaction for this one hold. | res_2: RESERVED to EXPIRED. Available 8 GB. Version 45 |
| 5 | The Sweeper deletes alice's entry in the Balance cache. | The cache entry is gone |
| 6 | At 12:16:00 Drive wakes up and calls CommitReservation for res_2. The status is EXPIRED. The answer is RESERVATION_EXPIRED: reserve again. | Nothing |
| Nothing |
| 4 | It fills the cache with these numbers and the version, to live for 60 seconds. | Cache entry quota:alice |
| 5 | It answers: limit 100 GB, committed 92 GB, held 0, available 8 GB. | Nothing |
| 6 | A second later the Drive page asks the same. The cache answers in under 1 ms. The store is not asked. | Nothing |
| DD1 |
| Two services ask in the same millisecond |
| 6 GB and 7 GB for 10 GB of room |
| NFR1, NFR2 — The limit, speed |
| DD2 | A caller dies with a hold, and wakes up late | A commit one minute after the hold expired | NFR1, NFR4 — The limit, nothing stuck |
| DD3 | Our number and the real bytes disagree | A lost delete call, and a bug that stored without asking | NFR4 — Nothing lost |
| DD4 | Two million balance reads a second | A fresh commit, and 3,000 readers on one key | NFR3, NFR5 — Scale, availability |
| Four reserves at once for one user |
| May overshoot |
| 10 transactions |
| 4 transactions, the last after 8 ms |
| Twenty at once | May overshoot | 210 transactions, no bound on the wait | 20 transactions, the last after 40 ms |
| Who waits | Nobody | Nobody, they retry | Only requests for the same user |
| It locks bob's row, on bob's shard. It never waits for alice |
EXPIRED. The answer is RESERVATION_EXPIRED, and nothing is added.COMMITTED, and one second later the Sweeper finds nothing to end.| Commit and Sweeper in the same moment |
| — |
| Both can go through |
| Exactly one goes through |
| The Sweeper crashes halfway | — | Depends on how it batches | Done holds stay done, the rest wait one round |
| The limit | Kept, but space is lost | Broken | Kept |
RESERVATION_EXPIRED| We counted too much (alice) |
| She loses 4 GB for ever |
| Fixed |
| Fixed, with a ledger row |
| We counted too little (bob) | He stays over his plan | Fixed | Fixed at once. No file deleted, uploads blocked |
| Trace of the change | — | None | One ledger row per correction |
| Each user is one transaction. The done ones stay done, and the next run finds the rest |
| After alice's commit |
| Correct at once |
| Wrong for up to 60 s |
| Correct on the next read |
| 3,000 readers miss at once | 3,000 queries | 3,000 queries | 1 query |
| Who may approve an upload | The store | The cache, by mistake | The store only |
| Reads go to the store under a rate cap, or the page shows no number. Reserves are not affected |
| One global lock per user would break the 10 ms. The practical step is a share of the quota per region with a regular comparison, accepting that a user can be over for a short time by what the regions over-allocated |
| The file turned out larger than the hold | The commit fails. The caller first reserves the extra bytes, then commits |
| The file turned out smaller | Commit the real size. The rest of the hold is free in the same transaction |
| An upload takes longer than the hold lives | Give that kind of operation a longer end time, or let a caller that is alive extend its hold before it runs out |
| The answer to a reserve is lost | The caller sends the same request with the same idempotency key and gets the same reservation back |
| Twenty reserves at once for one user | They wait in line, 2 ms each. A client that uploads a folder should reserve once for the whole batch |