Ch.41: System Design: Shopping Carts That Survive Login

Outline

Transcript

0:00 Ravi adds headphones on his phone. At sign-in, his laptop basket replaces them. Now he's rebuilding the cart. Yeah, or copy the guest into his account, fail before closing it, then copy it again. Signing in adds items twice. Apparently Login thinks it's another Add button. We'll make that transfer happen once, even if its reply vanishes. Then protect Ravi's later edits and checkout, with a visible quantity policy. That crash leads to this architecture's center: the Cart Authority, Ravi's basket record keeper.

0:31 Phone and laptop reach it through the Cart API. One login changes two baskets: update the account, close the guest, and save their receipt in one transaction. Together, so a crash can't leave the guest ready for another copy. And checkout? Can Ravi's purchase change while he's still shopping? Checkout freezes a copy for pricing, inventory, and payment. Ravi resumes browsing while that purchase uses its own snapshot. That separation freezes one purchase without freezing Ravi's next basket. Before checkout, does Ravi's choice of three headphones reserve three warehouse units? No. It's intended quantity versus stock held.

1:09 Selection records his wish; reservation sets stock aside. Picture Ravi's shopping list: three headphones, zero held behind the counter. Our functional requirements are four basket moves: add, remove, change quantities, and read across devices. Login combines his choices once; inventory waits for checkout. Then Ravi closes the app after Add turns green. We've all done that. If he loses his phone, are those headphones still saved? Yes. Our non-functional requirements start with durability. Green means the authority committed the edit, surviving phone loss or a failed data-center zone.

1:43 Pending means it exists only on his device. Yeah, green shouldn't mean "hope you remembered your headphones." He opens the same saved basket on another phone. Before combining those baskets, what counts as the same headphone line? For example, Ravi's blue headphones from two sellers are two separate lines. An engraving changes the choice too. Yes, exact model or option, seller, and customization identify it. Each basket also has a version, its revision number. An accepted change advances that number.

2:14 Suppose Ravi deletes the cable on the laptop. His phone uploads an older whole basket that still includes it. Does the cable come back? If we preserve every line from his outdated phone list, that cable returns with the headphones. Wait, really, he has to remove it twice because the phone was late? Amazon's original Dynamo paper describes that deleted-item comeback. That's historical behavior. Our API will reject whole-basket replacement and check which revision a small edit depended on. Good. The cable doesn't get unlimited comebacks.

2:45 First, though, how many headphones should login keep? Then sign-in meets two headphones in his guest cart, three in the account. Like two grocery notes: overlapping drafts for one order, or separate purchases? We have to choose what matching quantities mean. Separate purchases give five. Letting the guest replace the account gives two and loses the account's other lines. A product manager could say, "Keep both quantities. They're separate choices." I get that, but I'm not sure he wanted five. I see the concern. I mean, clean arithmetic doesn't reveal intent.

3:18 Our visible policy treats them as overlapping drafts: keep distinct lines and the larger matching quantity. Two and three become three. Oh, right, so he reviews three. If three falls short, he sets five deliberately. Sure. commercetools documents higher-quantity merging and separate replacement. If the combined cart is too big, show the lines that don't fit. Ravi chooses what to keep; don't silently discard them. Now apply that policy to the crash. Suppose the account saves, but the process dies before closing the guest.

3:52 How does the next login avoid copying it again? Commit three things together: the merged account, the closed guest, and a transfer receipt. Think of vehicle ownership: the new title, canceled old title, and proof have to agree. Okay, walk me through his baskets. Read the guest's two headphones and the account's three plus a cable. Keep three and the cable, advance the account version, close the source, and save the receipt under the guest's ID. Ah, that ID answers which guest we already used. So if the reply disappears, the next login finds that receipt instead of copying anything. Exactly.

4:30 Serializable means competing logins behave as if they ran one at a time. It also saves a reminder to notify his other devices. Oh, nice. The saved basket doesn't wait for that notification. A crash leaves both carts unchanged or the transfer complete. What if two login tabs both discover he has no account cart? The account stores one current-cart ID. Check and set it in that same transaction, so both tabs use one destination. No pricing or payment calls inside. Now the guest is closed and his account owns the result.

5:03 That atomic transfer raises a storage question. Why not use a saga: write the account first, then retire the source, and undo the first step if the second fails? Imagine he adds a new cable between those steps. Restoring the old account basket could erase it. Microsoft's guidance on undoing multi-step workflows flags that concurrent-write hazard. Oh, that's a recovery nightmare. A login repair wipes out new shopping. But what if our database can't transact across both cart keys? Then the account might be saved while the guest is still open.

5:38 One option is to pause edits and record which write finished, so recovery can complete it. Ravi sees Login pending. We choose one transaction for both carts. Yeah, I mean, I'd rather pay for a short coordinated commit than make Ravi wait through that repair workflow. Keep pricing outside, and test competing logins against our latency target. Yes. Ravi gets the old baskets or the merged account and closed guest. The database owns that all-or-nothing outcome. And if that success reply vanishes, the next login retrieves its receipt.

6:10 Ravi keeps the result without another copy. Now separate that transfer receipt from permission for a new guest edit. What happens when his old phone sends one? Before the merge, the old phone's last accepted edit is already in the guest cart. The transfer reads that state. Once the guest closes, a new edit is refused. Suppose someone steals that old guest token and tries to replay login into another account. Right, could that token reveal Ravi's signed-in shopping? No. The guest token can knock, but it doesn't get a tour.

6:42 Authorize Ravi's account before returning that login's receipt. Any other account gets zero destination lines. Okay, the token stays outside his account. What changes when Ravi signs out? Clear the client cache. The backend still checks whoever calls next. With Ravi's account reads protected, his cart faces another old-phone problem. He removes the cable; that account version advances. Suppose the phone sends a quantity change using the earlier version. The authority refuses it. Like two editors: once the laptop saves a newer draft, the phone's old page can't overwrite it.

7:16 That's optimistic concurrency control: an update succeeds only if the state it depended on hasn't changed. The official commercetools API uses expected resource versions and reports mismatches. My first thought is retrying automatically. Honestly, that's our muscle memory when a response disappoints us. But if the headphone quantity changed, we'd be choosing for Ravi. Right. I mean, a version conflict says his basket changed. Fetch it before deciding again. A missing response leaves his earlier Add uncertain.

7:46 Look for its saved answer. So Ravi opens the fresh basket: three headphones, but the cable is gone. Can he add a 4th? Yes, if he chooses that new Add using the revision he just fetched. If another device chose a different headphone count, show both quantities for review. Ravi decides what he wants. Next, take a genuinely lost reply. Imagine Ravi taps Add on train Wi-Fi. Three headphones become four at the server, but after it commits, the tunnel drops the response. Oof, the screen saw nothing. Walk me through the retry mechanism.

8:21 How does he ask for the result without adding a 5th? Sure, take that exact Add step by step. Before sending it, the phone gets a server-signed retry pass for this basket and Ravi, with a fixed deadline. The operation ID names the command. Commit the edit and its saved answer together. Like a claim ticket. Same ticket, same item. But the retry still expects the version from before Add. Doesn't that check fail? First, check Ravi's permission and that signed pass. Then look for his saved Add result.

8:53 It says four, so return four. Only a command without a saved result reaches the active-cart and version checks. Ah, I hadn't put that together. The version protects a new decision; the receipt answers an old one. Checking the version first rejects our own successful Add. Yeah, it really does. Same ID with changed contents is an error. A deliberate second click gets a new ID. And I'm realizing login is the same uncertainty. Its transfer receipt tells the next attempt what happened? Yes. Different receipts, same idea: retrieve the completed result instead of repeating the change.

9:31 But that saved answer can't disappear while we still permit the old retry. Now that Add needs a safe end to its retry window. After we delete its result, could the original command add a 5th? No. The ID finds its answer; the pass limits when a retry may ask. Authorize Ravi, then validate the signature and deadline before lookup. Its 24-hour window is noon today to noon tomorrow. Keep the result through it. Afterward, refuse that old Add. That ticket limits retries, not how long the basket lives.

10:07 A cleanup job was queued to delete Ravi's cart before Add committed. Why doesn't it delete the four? The cleanup job carries the cart's old expiry and version. Ravi's Add changed both, so that job stops. Closed cart IDs never reopen; altering a pass fails its signature. Ravi can read his cart and choose a fresh action. Now let a fresh server answer beat an older cache. Ravi's phone learned four headphones, version 20, from that Add retry. The cache still has three at 19. So the phone just got four, then sees three again?

10:41 That's a broken promise. Right. The phone remembers 20 and includes it in its next read. The Cart API skips a stale cache entry and fetches the authority. His 4th stays visible. His next screen won't rewind to that old snapshot. What if the laptop missed the notification? It fetches on reconnect. The outbox event is that reminder saved with the cart update; the notifier sends a hint to fetch, not the basket. Missing the hint doesn't change accepted state. Oh, right, the basket is still there. Offline additions stay pending until the authority accepts them.

11:17 Yes. Send one intended change against the fresh version, never the old whole basket. That fresh-version edit still needs a reachable authority. If Ravi's region can't reach it, the new edit stays pending. So Ravi contacts support with a spinner still running. Did his request stall, or did someone change the basket? For a valid retry, a committed Add returns its result after a lost reply. A rejected version needs a fresh read. If neither is confirmed, keep it pending. During rollout, log these outcomes; a trace follows the API and database.

11:51 Yeah. We can actually name his next step instead of asking him to press Add harder. Those four lead to checkout. Ravi presses Buy, then keeps browsing. What freezes so the purchase doesn't change underneath him? For instance, submit the accepted version with a checkout request whose ID stays the same on retry. Seal that basket into one immutable attempt, a fixed record of its purchase lines. Get a fresh price and inventory reservation separately. A changed quote needs confirmation. Don't hold a cart transaction open during those calls.

12:24 Further shopping starts in a new draft. We chose that separation to keep the purchase input fixed. Oh, right, it's kind of like a photo of his chosen lines. He can keep shopping, but a late purchase result belongs to the photo, not his new basket. Right. A failed purchase stays attached to that photo; it doesn't tear up his new draft. He can deliberately copy the old lines and review quantities. Repeating the original submission returns the same attempt. Finally, follow Ravi's sign-in on the full architecture.

12:55 The Cart API transfers the guest into the account in one transaction: three headphones, one cable, and a closed guest source. Its receipt resolves a missing transfer response. Next, the cable comes out. The authority advances its version, so an old phone can't put it back. His next add saves four headphones; repeating the same command returns the saved Add result. The notifier and cache help his devices see those accepted choices. Checkout freezes the purchase lines, then checks a fresh quote and reserved stock.

13:25 His next basket stays independent of that completion. I like the pattern: the transfer receipt answers login, the saved command result answers Add, and the checkout snapshot fixes what he's buying. The description links our public sources; quantity and expiry policies are our proposed choices. Yeah. Ravi gets to sign in without rebuilding the basket or wondering whether a retry added another pair. Thanks for listening to Learning Podcasts.