A lock holder updates a database row and then publishes a message. Both resources check fencing tokens. The holder is paused between the two steps, loses the lock, and wakes up. What state is left, and how do you design the operation so this is harmless?
Sketch your own answer first, then compare it with the one below.
A strong answer
The database accepted the first write under token 33. During the pause a new holder took token 34. When the first holder wakes and publishes, the message broker sees 34 already and rejects the stale message. The result is a half-finished change: the row is updated and the message never went out. Each resource enforced fencing correctly, and the pair still ended in a state that neither writer intended.
Fencing makes each resource safe against stale writes. It does not make two resources change together. That needs a transaction or a design that does without one.
Options: make the second step derivable from the first. The new holder reads the row, sees the update with token 33 and no matching message, and republishes. This is the outbox pattern: write the row and an outbox record in one local transaction, and let a separate relay publish from the outbox, idempotently keyed by the record id. Then there is one resource with a commit point, and fencing guards that one. The broker step can be repeated safely, because duplicates are ignored.
Avoid designs where a lock is expected to give atomicity across stores. It only orders holders, and recovery has to be built into the data.
Sources
- Martin Kleppmann (2016). How to do distributed locking.