Ch.68: Digital Wallet System Design: What Can You Spend?

Transcript

0:00 Nina's digital wallet records 120 dollars, but it will let her spend only 30. 90 dollars are reserved for one purchase, so her next 50-dollar request fails. This is a stored-value wallet: you add funds, keep a balance, then use it for purchases or transfers. Its backend decides how much can leave next. We'll design that balance and reservation service. Follow the 90 dollars through a smaller final purchase, then a withdrawal whose bank response goes missing. And take two requests arriving together.

0:30 Each sees enough money on Nina's screen. If both requests succeed, we've promised more than she owns. The service has to decide which spending promise it can keep. I'd start by making the screen show the right number. But a corrected screen alone can't reserve money against another request. We'll connect that screen to the transaction granting permission to spend. First, let's follow where Nina's request goes. First, our complete architecture map follows Nina's 90-dollar request. The wallet service checks her identity and sends the request to the ledger and reservation authority, the core that records movements and approves holds.

1:05 That core records her hold beside her current total. A hold promises money to one outgoing operation. The same core keeps posted movements, meaning completed internal money movements. Once a change commits, its event feeds history, the display and outside work. Bank adapters perform the outside operations and bring evidence back. We'll follow one when Nina withdraws money. Could we keep approving from the fast display if the core goes down? It can show the committed state, but new spending still needs the core.

1:35 We'll return to this map after the purchase and withdrawal, following the operation that changes each number. Let's state the functional requirements before choosing storage. Nina needs separate posted, outgoing-held and pending-incoming amounts. She can reserve an amount, complete the spending or release it. Internal transfers move value to another wallet account, and history explains each result. Funding and withdrawals also need durable outcomes. A correction must refer to the original transaction and record what changed.

2:03 We're keeping one currency so conversion doesn't obscure those promises. Nina, for example, reserves 90, but the purchase finishes at 70. She should understand why the other 20 is free again. That smaller completion also needs an outcome the core can trust. The payment adapter handles provider requests and reconciliation: matching our operation records against the provider's evidence. We're designing the wallet's money state and spending decisions, so we won't rebuild that entire provider integration.

2:32 Amounts are integer cents here. Otherwise a floating-point rounding surprise could become an unexplained difference in someone's balance. Those operations create our non-functional requirements. Start with never approving spending above a customer account's available funds. Accepted records must survive failure and remain explainable afterward. I think the current balance belongs beside the transaction that can change it. A stale display cannot permit new spending, even if the ledger catches up later.

3:00 An uncertain bank outcome also can't quietly free money. We'll distinguish retryable unavailability from a genuine insufficient-funds answer. Use a fictional peak of roughly 2,300 money commands per second across accounts. What if a burst lands on one wallet? Then that one account becomes the bottleneck. Its callers must wait or retry around the same balance row. We'd measure that delay and its transaction conflicts separately; a fast average across customers could hide this wallet's queue. Those are requirements to test, not a vendor benchmark.

3:33 Modern Treasury's public ledger documentation gives us a useful starting distinction between posted, pending and available balances. Now take Nina's original funds. Posted balance means completed internal movements recorded for this account. As a picture, think of the original 120 as cash in a drawer. Some can already be promised to a purchase. Put 90 in an envelope for this purchase. It's still part of the recorded total, but only 30 are loose in the drawer. That's our 90 held and 30 spendable.

4:02 There is also a 60-dollar incoming bank operation. It appears as pending, separately. Our product doesn't add that potential money to spending permission yet. So the promised 60 isn't in the drawer yet. Showing 180 as spendable would let Nina use money whose incoming operation is still unresolved. Right. The formula for this customer wallet is posted funds minus outgoing holds. Pending incoming funds stay outside it until our funding policy admits them. Then why display 120 if only 30 can leave?

4:34 Because Nina also needs to see the 90 still promised to that purchase. Separate labels explain both numbers. Other wallet products may choose different credit policies, so those labels must reflect the contract we've actually implemented. Now preserve the explanation behind that balance. We need the old movements, and the next purchase also needs a current total. What breaks if a crash updates only one? If history records the spend but the total stays unchanged, Nina could spend it again. Keep each posted entry and update its running total in the same transaction.

5:08 Think of the receipt for that 70-dollar purchase beside the 50 left in the drawer. They must agree. Uber calls its unchangeable records of money movements money orders. Its engineering retrospective describes separate current balances, with new orders for adjustments. The original movement stays recorded. I like that separation. We can tell Nina which movement changed her balance, while the current total makes the next decision practical. Both still need to agree. Hold transitions leave durable events too.

5:36 Replay means reading the money movements and the history of each hold again to rebuild the posted and held totals. It gives us a way to check the current answer. The current hold row can move from pending to resolved. We're preserving its original terms and transition history, not claiming every record is immutable. Source links are in the description. That gives us history and a fast current answer; next, make a spending decision while two requests compete. Now test that current total against concurrency.

6:05 Consider a hold for 90 and a separate attempt to reserve 50 in parallel. Each caller read 120 before either operation completed. If we check first and write later without coordinating, both can pass. They promise 140 dollars from a wallet with only 120. The check and reservation need to be one operation at the current authority. How does the losing request learn it no longer fits? Inside a transaction, read the source account and check its current spendable amount. Record the reservation, update held funds and store the operation outcome together, while protecting that account from a conflicting spending decision.

6:44 If 90 wins first, 30 remain and 50 is rejected. If 50 wins first, 70 remain and 90 is rejected. We haven't promised a particular winner. A conflict may require a database retry. It reuses the request's stable identity, so losing the reply doesn't turn a retry into another hold. Mm, the screen was only an earlier observation. The reservation is the decision that changes what the other request can spend. What if the caller reuses that identity but changes the requested 90 to 50? Reject the changed request. The identity is bound to the original amount and accounts. An unchanged retry gets its saved outcome; a different purchase needs a new identity.

7:26 Next, resolve the winning reservation. Let's say the purchase's final amount is 70 dollars. We already reserved 90. What happens if we post 70 but leave the full reservation in place? Nina's posted balance falls to 50, while 90 still appear held. We've counted the same purchase twice when deciding what's available. So one transaction appends the 70-dollar source and destination entries, updates their balances, and finally resolves the hold by removing all 90 dollars reserved for it. Nina now has 50 posted and 50 available.

7:59 The merchant has 70. The unused 20 became available through releasing the remainder of the original hold. Ah, that's our own 20 coming out of the envelope, not a bonus deposit. Nina's 50 and the merchant's 70 still add up to the original 120. If we released the 90 before... ...posting the 70, another request could spend the temporary gap. Those changes belong in the same transaction. TigerBeetle's documented pending-transfer model includes this smaller final posting and remainder release. Our proposed hold resolves once, which means a second completion can't spend it again.

8:33 That single posting needs a database boundary covering both accounts. Nina and the merchant might occupy different partitions. Would calling their two wallet services make the transfer atomic? No. A crash between those calls could reduce Nina's balance without crediting the merchant. What boundary prevents that split? Put Nina's account row and the merchant's row in one distributed SQL database, even if it stores them in different partitions. Use serializable transactions: concurrent money decisions behave as if they ran one at a time.

9:03 Spanner documents that cross-partition boundary. Then our 70-dollar transaction writes both entries and balances, resolves the 90 hold, and saves the outcome. Think of one 70-dollar instruction changing two account pages: both pages change, or neither does. That coordination has a cost. How do we remember the work that follows the posting? For instance, record an outbox item saying Nina's purchase posted 70 to the merchant, with its operation identity. It's durable work saved in the same transaction, for delivery after commit.

9:35 If we commit and then crash before sending it, the item is still there. Who resumes the send? A dispatcher resumes from the pending item. Delivery can repeat, so consumers use the event's stable identity. That event refers to this same purchase. Right, repeating its delivery mustn't credit the merchant again. I think accepting coordination here is worth it. If current authority is unavailable, new spending waits or fails with retryable unavailability. A balanced entry set still isn't enough. A duplicated transfer can balance, and so can a transfer to the wrong recipient.

10:08 Identity and authorization checks remain alongside atomicity. Now return to the 60 still marked incoming. Nina has 50 after her purchase. What evidence lets the wallet admit the additional funds? For this wallet, wait for a verified success result from the funding provider. We don't let Nina spend the 60 while that result is pending. The adapter matches that evidence to the pending funding request before the core admits it. Stripe's bank-debit documentation warns about delayed failures and disputes. Even after we admit the funds, that outside risk hasn't necessarily ended.

10:43 Then who covers it if the bank takes the funding back after Nina uses the money? Our proposed policy puts that loss on the platform, funded with its own money authorized for that purpose. It records a new correction; it cannot erase the deposit or pretend Nina still has money she spent. So we've chosen both an admission trigger and a risk owner. A success result lets the 60 enter this wallet; the platform keeps the later loss. Exactly. Admitting that 60 takes Nina from 50 available to 110. That recorded funding decision is what changes her display.

11:18 Next, use the newly available funding for an outside operation. For example, Nina requests a 20-dollar withdrawal from her 110. Reserve 20 before dispatch, leaving 90 available. The adapter sends after commit, outside any database callback that can be retried. Suppose its payout response disappears. A timeout could mean the provider never acted, or acted and lost the reply. The operation is unknown. Imagine support asking, 'She canceled. Can we release the 20?' I'd want to help, but the bank might already have paid it.

11:51 Keep 110 posted, 20 held and 90 available. Suppose a lookup by the original outside operation identity finds the request, but still gives no final outcome. Finding it hasn't settled the 20. Do we send another withdrawal to hurry this up? A fresh withdrawal identity could pay her again. Use the original identity through the lookup or retry procedures that provider actually supports. That 20-dollar order ticket marked received isn't proof of delivery. The acknowledgment doesn't prove a payout. If the evidence confirms success, post the 20.

12:23 Posted becomes 90, the hold clears, and available remains 90. We haven't taken another 20 from what was free. Confirmed failure releases the hold instead. The recorded balance remains 110, and Nina can spend the entire amount again. Until there is enough evidence, neither final result is justified. So an internal reservation with no outside effect can have a safe expiry rule. An unresolved external withdrawal needs more than the same timer. A cancellation request doesn't establish failure either.

12:55 The result is an honest pending state while the adapter resolves whether the money left. Once a movement is posted, correction needs another movement. Take a refund after the merchant received 70. We preserve the original purchase and append a new authorized movement linked to it. Modern Treasury's docs make the same distinction for reversing a posted transaction. But what if the merchant has already spent its 70? Think of an empty drawer. Writing refund on the receipt doesn't put 70 dollars back into it.

13:26 The refund needs an approved funding source, such as available merchant funds or money the platform has set aside and is authorized to use. Otherwise it remains an unresolved refund request, rather than a fabricated completed refund. That keeps our customer non-negative spending rule intact. We don't silently break it merely because the requested accounting correction sounds symmetrical. Each correction records who authorized it and why, alongside its original transaction reference. A support agent can explain both events without erasing the first one.

13:57 The recorded amounts can balance without proving that the bank or platform actually has the funds needed for payment. We check that outside evidence separately. Next, keep Nina's withdrawal unresolved. Imagine a separate test: could she reserve the remaining 90 for a new purchase, or have we locked her whole account while waiting for the bank? She can reserve that 90 if the current checks pass. The database transaction ended when we recorded the withdrawal's reservation. That business hold persists without keeping a database lock through the network wait. So the original 20 stays protected, and a new transaction can reserve the other 90.

14:34 The earlier database transaction has finished. Yes. Each new spending decision takes a short transaction on that account row. Conflicting decisions must take turns or retry, even while the earlier business hold remains unresolved. What happens to the callers piling up behind that one busy account? Bound how many requests can wait. If that queue is full, return a retryable busy response. That's different from checking current funds and finding that a purchase doesn't fit. A retry keeps the same operation identity.

15:04 If an earlier attempt committed but lost its reply, the saved result must prevent a second reservation. Meanwhile, history can load in pages built from committed events. Other customers have different account rows. Measure their latency separately from this hot wallet's transaction conflicts and waiting queue. The bank can stay silent while the wallet processes new work. We still have to keep the burst of requests bounded. Before rollout, reset Nina to 120. Pause the 90 and 50 requests at the same test checkpoint, then release them together.

15:37 Only one reservation may fit, in either ordering. In a fresh test, reserve 90 and finish the purchase for 70. What happens when that same completion arrives again? It returns the saved outcome. There's one posting, 50 left for Nina, 70 for the merchant and 20 released once. For the abort variant, start over and interrupt the transaction while preparing both accounts. No half-transfer can become visible. For instance, take a clean completed purchase and deliberately corrupt Nina's current posted total to 30, leaving history untouched.

16:11 The transfer entries still balance. What catches the wrong total? Replay rebuilds 50 from the recorded movements and hold transitions, exposing the mismatch. That's different from matching funding and payout records against the bank's evidence. Our own consistent history cannot establish an outside outcome. Use a separate withdrawal test: 110, then 20 reserved and a missing response. A timer and customer cancellation must not free that 20 while the outcome is unknown. Finally, lose the authority entirely.

16:40 Return retryable unavailability, without using an old screen or inventing insufficient funds. Record which operation is pending and what evidence is missing, so recovery can finish the actual work. Finally, return to our original trace on our complete architecture map. Nina's purchase command reaches the ledger authority. Reserving 90 from her 120 leaves 30 available. The final 70-dollar spend commits both accounts' entries, their balances and the hold's resolution together. The customer retains 50, and the merchant receives 70.

17:11 Resolving the original reservation also frees its unused 20. The funding adapter verifies success for the incoming 60 under our chosen policy. Nina reaches 110. Reserving 20 for her withdrawal leaves 90 spendable before the provider's final outcome is available. Now let the adapter receive verified evidence that this withdrawal paid. The core posts 20 and clears its hold together. Nina has 90 in posted funds, zero in holds, and 90 free to spend. The bank paid it; it doesn't become available a second time.

17:42 The 120 on the opening screen was a real recorded balance. The 30 answered a different concrete question: how much can safely leave next? And every change we followed has a recorded operation. History and notifications follow those decisions; a cache refresh or an impatient timer cannot grant extra spending permission. Thanks for listening to Learning Podcasts.