In a leaderless store using last-write-wins timestamps, users report items vanishing from their shopping carts, but only when they use the app on a phone and a laptop at the same time. Explain and fix.
Sketch your own answer first, then compare it with the one below.
A strong answer
Each device reads the cart, adds an item, and writes the whole cart back with a timestamp. Say the phone writes [milk, eggs] and the laptop, having read the old [milk], writes [milk, bread] a moment later. Last-write-wins keeps only the higher timestamp. The replicas converge on one cart and the other item is dropped. Nothing fails, so there is no error to see.
The clocks make it worse. If the phone's clock runs a second ahead, its older write beats the laptop's newer one, so even "the later edit wins" does not hold.
Fixes, from smallest to largest. Stop writing the whole cart: store each item as its own cell or key, so two adds touch different keys and cannot overwrite each other. Or use a store with version vectors, which detects that the two writes are concurrent and returns both versions, then merge them by union in the application. That is how the original Dynamo cart worked, with the known side effect that a removed item can come back, which was chosen over losing an added one. Or use a data type designed to merge, such as a set that tracks additions and removals.
Last-write-wins is fine for values where the newest overwrite is genuinely what you want, such as a profile picture, and a poor fit for collections.
Sources
- Giuseppe DeCandia and others (2007). Dynamo: Amazon's Highly Available Key-value Store.
- Martin Kleppmann (2017). Designing Data-Intensive Applications.