Middle · MongoDB with Go
Conditional updates and uniqueness
How do two Go replicas safely update the same document?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
Reveal a strong answer
Single-document writes are atomic, but a separate read followed by write is not automatically one atomic operation. Put expected version/state and tenant in the update predicate, and inspect the matched/modified result.
Use operators such as $inc when expressing an atomic increment, and use a unique index to enforce uniqueness across replicas. An application precheck can race. An upsert also needs the right unique constraint and error handling.
A zero match can mean a stale version, wrong scope or missing document; classify without leaking unauthorized existence. Decide how callers refresh/retry after a conflict instead of silently overwriting another update.
Common trap
A process-local mutex cannot enforce an invariant across several service replicas.
Try it
Two requests both read version7 and each sets a new balance. How do you avoid a lost update?
Worked solution
Update with a predicate containing the authorized identity and version7, set the new fields and increment version. One succeeds; the other gets no match and must reconcile/retry from fresh state. For pure increments, an atomic $inc may express the operation more directly.
Change the constraint
Why should a retry of a non-idempotent increment carry a stable operation ID?
How did you do?
Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.
Not marked. Progress stays on this browser, separate from course completion.
Primary references
Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.