Ch.49: Splitwise System Design: Who Do You Actually Owe?
Outline
- 0:00 The recipient changed
- 0:43 Facts on one path, proposals on another
- 1:12 What the roommates can do
- 2:05 Exactness before scale
- 2:50 Paid share versus owed share
- 3:26 Keep the leftover cent
- 4:03 Keep the explanation, not just the total
- 4:48 One position per person
- 5:28 The arrow didn't move money
- 6:14 Dinner changes after repayment
- 7:05 Build the corrected payment plan
- 7:48 Greedy is not a minimum proof
- 9:06 One gate for every monetary writer
- 10:09 A consistent plan can still be old
- 10:51 Scale the groups, respect their boundaries
- 11:38 Test each person's answer
- 12:30 The same map, with the payment preserved
Transcript
0:00 Splitwise tracks shared bills to work out who owes whom. Enter dinner and a taxi. It tells Casey to pay Alex 30 dollars, but Blair covered Casey's taxi. Did it pick the wrong person? Not necessarily. A group can settle everybody's net balance through different payment paths. Blair can stop collecting from Casey when Blair's own share elsewhere cancels it. My first thought is somebody got shortchanged. Right. We'll design our own Splitwise-like backend: recorded expenses, each person's net amount, and repayment proposals stay separate.
0:32 Then we'll correct a bill after Casey already paid. Yeah. Forgetting that payment risks charging Casey twice. Where do the facts live while the arrows get reshuffled? That separation leads to our two-path architecture. Group commands record bills and payment reports. Those facts determine balances. The planner only draws suggestions from balances. So it's a whiteboard, not a cashier. Casey's 30-dollar arrow can change while the recorded dinner and payment stay put. Drawing an arrow isn't paying.
1:02 Yep. Redrawing the whiteboard doesn't erase Casey's payment from the ledger. Then let's establish what those group commands actually promise before we choose how to store them. First, the functional requirements: create the roommates' group. Add dinner with equal, exact or percentage shares, edit it without hiding history, and show each person's balance by currency. Then propose fewer repayments. For example, Casey reports 30 dollars handed to Alex, but the confirmation never reaches the phone. What identifies that one report when the phone retries?
1:34 Its command ID. An unchanged retry gets the saved report; another real payment needs a different ID. We record Casey's claim, not bank confirmation, and don't move money ourselves. Yes. Splitwise's official help says simplification reruns after new expenses or payments. Paths change, each person's total stays intact, and currencies stay separate. The source links are in the description. Right, a redraw isn't a new payment. But what stops that accepted report from disappearing if the phone loses its connection? Now the non-functional requirements: Casey's accepted report must survive a failure.
2:10 Amounts must be exact. Read one committed group state, not half of Blair's edit. Only members can inspect their group. Suppose Casey checks before handing over cash. We want reads quick enough for that decision, without waiting behind every unrelated group's dinner edit. Casey can't wait on everybody else's dinner. But two edits to this dinner still need a winner. I'd rather return an honest conflict than quietly accept both. Yeah. Show Casey's report as pending until the server confirms it saved it.
2:41 Acceptance is a durable record, not a phone animation. Before we solve concurrent edits, let's calculate the amounts those facts are supposed to preserve. Next, calculate dinner: Alex pays 60 dollars, split equally among three roommates. Each owes 20. Alex's contribution is positive 40; the other two each contribute negative 20. Positive means money is owed to you. Negative means you owe money. That's paid minus your allocated share, not the whole receipt charged to somebody else. Then Blair pays 30 for a taxi, 10 per person.
3:13 That adds 20 for Blair and subtracts 10 from each partner. Wait, Blair's 20 in credit cancels the dinner share. So Alex is owed 30, Casey owes 30, and Blair is out of the collection business. That allocation raises a rounding question. Imagine dividing 10 dollars among three members. One gets 334 cents; both others get 333. Changing the order of the same three members shouldn't change their shares. So who eats that extra cent? Use stable member-ID order for the remainder, then persist those actual shares.
3:49 This is our policy for the dollar example, not a claim about every currency. Yes. A new roommate can't time-travel into last month's dinner. Save its actual shares and currency; joining later doesn't redivide an old bill. With exact shares fixed, save the bills and reported repayments separately. Blair should be able to inspect dinner's original shares next to the correction. Blair says dinner is wrong. We can rebuild from the current bills and repayments. Why keep the old shares too? Current bills explain today's totals, but not what Blair saw before the edit.
4:23 Keep Blair's original 20-dollar share beside the corrected 30-dollar share, including who changed it. Repayments stay separate. Right. Blair can compare the earlier bill with what changed, rather than being told to trust a new number. Calculate today's amount from the latest bills and the payment history. Now we can reduce the payment paths without pretending that reduction is a new expense. What information does the planner need? Then combine expense shares with payment reports into one net position: what each member still owes or is owed in this group and currency.
4:57 Before Casey pays, Alex is plus 30, Blair zero, Casey minus 30. Blair disappears from the repayment plan, but not from the history. The taxi still happened, and Blair's dinner share still exists. Exactly. This plan sends Casey's 30 straight to Alex and keeps everyone's net amount intact. Blair doesn't need to collect cash and send it on. Yeah, I can see why that change feels suspicious. Let users inspect the underlying expenses, rather than asking them to trust a rearranged arrow. Now act on our dinner-and-taxi proposal: Casey records a 30-dollar payment to Alex.
5:33 That becomes a separate fact, not just a checkbox attached to today's suggested transfer. Recording it raises Casey's position by 30 and lowers Alex's by 30. Both reach zero, as does Blair. Now the group is settled under the recorded facts. Why not just delete the suggested arrow once Casey says it's done? That would make the screen empty without another kind of record. Because recomputing suggestions would resurrect it. The payment changed what remains owed. It must survive when we discard a cache or use a different planning algorithm.
6:07 Yep. A disappearing arrow isn't a receipt. That settled payment must remain when someone corrects dinner tomorrow. Let's run the corrected dinner with Casey's payment still recorded. It becomes 90 dollars, covered by Alex and split equally. Replace dinner's current calculation, but keep its earlier version and the payment. The increase is 30 total. Alex covered it, but owes 10 of the extra cost. Alex's net position rises 20; Blair's and Casey's each fall 10. So the retained repayment leaves Alex owed 20, with Blair and Casey each owing 10.
6:41 Recommend those two payments, not the original 30 again. Oh, Casey owing money again doesn't prove we forgot the earlier payment. Casey owes a new 10-dollar share from the corrected bill. The history explains the difference. Yes. Either recompute from the current facts, or update dinner's contribution alone. For Alex, replace dinner's old 40-dollar credit with 60, while Casey's cash report stays put. Next, build those arrows. For example, Alex needs 20, while the other roommates owe 10 apiece. What does largest-first actually pick here?
7:13 It repeatedly pairs the biggest debtor with the biggest creditor, subtracting the smaller amount from both. Here that pairs Blair's 10 with Alex's 20. Alex still needs 10, so Casey fills it. So Alex would receive two 10-dollar payments, one from Blair and one from Casey. Incoming counts positive, outgoing negative. Exactly. Add them for each person; the proposal must reproduce that person's saved balance. These are scratch amounts in a planner, not records of paid bills. The amounts reconcile. But does choosing the largest amounts always give us the fewest arrows?
7:48 A valid plan gets everyone's amount right. A minimal plan uses the fewest transfers. Amounts versus handoffs. Consider two collectors: one needs 8 dollars, the other five. Imagine those collectors holding cash envelopes marked eight and five. Three people owe five, four and 4 dollars. How would largest-first fill the envelopes? First, the 5-dollar payer puts five into the envelope marked eight. That collector still needs three. So the untouched 5-dollar envelope is now the bigger target. One 4-dollar payer goes there, leaving one.
8:20 Two handovers, two unfinished envelopes. Is that where the last payer gets split? Exactly. The last four splits: three into the first envelope, one into the second. Two more handovers, four payments total. Both envelopes end full. Wait, four. Pair the two fives first. Then the two 4-dollar debtors each pay the 8-dollar creditor. Three payments, with everyone's amount intact. Oh, you're right. I think I was treating largest-first as the only sensible route. Your five-to-five pairing beats that. We can use greedy without promising a minimum.
8:56 Right. If fewest possible transfers is a hard product requirement, solving that is additional work. We aren't claiming this greedy method is Splitwise's private optimizer. With either matching strategy, Casey's payment must survive Blair's edit. Suppose a backend engineer in review says, "Just lock dinner." Blair's edit arrives first. Walk me through where Casey's payment waits. Give both commands one turnstile: a database control row for one group-currency pair. Every bill edit and payment report locks it.
9:26 Blair enters first; Casey waits outside. Then Blair's corrected dinner, balances and revision commit together. Only then does Casey enter, using that result. The row controls entry; it doesn't store or move their cash. Right. Two edits based on the same old bill version still can't both win. After the first commits, reject the second's stale version for review. So the gate orders different writes; the version check rejects an outdated edit. PostgreSQL row locks support the gate; ordinary readers don't automatically wait on them.
9:59 So writers don't step on each other. But I could read dinner before one commits, then read repayments after. That's a mixed plan. How do we prevent it? For that read boundary, PostgreSQL Repeatable Read keeps the planner's reads on one snapshot. Every balance together. Return its revision with the plan; include it in the cache key. So consistency means one coherent photo; freshness means how recent it is. Casey may still see the old 30-dollar plan while the latest facts leave 10. No collage of different revisions.
10:30 Exactly. Refresh advice before acting on it. But if Casey already handed over cash, saving that actual payment report isn't the same as accepting old advice. Yes. Give that report its own identity and actual amount, then show the resulting balances. A new plan can't undo money handed over outside our app. Next, scale that group boundary. Another group gets its own gate, so its taxi edit needn't wait for Blair. But separating dinner from repayments creates a different problem. Suppose dinner and Casey's payment live on different machines.
11:05 What would Casey see if dinner's side missed the report? Dinner plus the taxi leave Casey owing 40. Retain the recorded 30-dollar repayment and only 10 remains. Missing that report manufactures another 30. Keeping this group's facts together avoids that coordination. Whoa, that's a phantom 30-dollar debt. I'd keep the group together until measured contention justifies a split. Check membership, preserve old shares and keep each currency separate. Yes. Casey leaving doesn't forgive the bill. Nor can Alex's group reroute its debts through a stranger in another group.
11:38 Next, turn Casey's complaint into a test. Rebuild each member's balance using today's expense versions and saved repayments. Does Casey still owe 30, or only 10? Compare that result with the stored balances, then check each proposed transfer. The group's total could be zero while the wrong roommate pays. How would that slip through? For example, a buggy correction shifts 10 dollars from Blair to Casey. The total stays unchanged, but Casey pays too much. Our person-by-person comparison catches that error.
12:09 Yeah, the total passes while Casey gets overcharged. Next resend Casey's original report with the same ID and contents. No second repayment, no balance change. Check the saved cent allocation too. In production, if Casey still sees 30, inspect that plan's revision and payment history. A stale proposal and a missing repayment need different fixes. Finally, our complete map joins those checks: the group API accepts dinner's correction into durable facts. It retains Casey's payment and updates all three balances in the same transaction.
12:41 The planner reads that revision and proposes 10 from Blair and 10 from Casey, both to Alex. It doesn't restore an old arrow or erase a receipt. That's why a recipient can change without changing anyone's net debt. The proposal is flexible; each person's amount must still be explained by the recorded history. Keep expense facts, net balances and payment suggestions separate. Then revising dinner changes today's obligations without pretending an earlier payment never happened. Thanks for listening to Learning Podcasts.