NoSQL and MongoDB · senior
MongoDB write concern, failover and transactions
With a weak write concern, a primary can confirm a write that a failover then loses. MongoDB also has multi-document transactions, but good modelling needs them less often.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- With w: 1 the primary confirms before any secondary has the write. If the primary crashes, the new primary may not have it. When the old primary comes back, it rolls those writes back and saves them in a rollback directory.
- w: 'majority' waits until most voting members have the write. Use it for orders. The cost is roughly one extra network round trip.
- Defaults depend on the setup. A replica set with an arbiter can fall back to w: 1, and an explicit w=1 in the connection string overrides any default. Prefer three data-bearing members over an arbiter.
- Retryable writes (on by default in modern drivers) plus an idempotent order id make retries safe. Send the confirmation SMS only after a majority-acknowledged write.
- Reads from secondaries can be old. Use read concern majority, or causally consistent sessions, where it matters.
- A write to one document is atomic, including its embedded arrays. Embedding related data (an order with its items) often removes the need for a transaction.
- Multi-document ACID transactions exist on replica sets and sharded clusters. Handle TransientTransactionError by retrying the whole transaction, and UnknownTransactionCommitResult by retrying the commit. The driver's withTransaction helper does both.
- A transaction has a lifetime limit of 60 seconds by default (transactionLifetimeLimitSeconds). Write conflicts abort one side, and cross-shard transactions cost more.
The red pen
Common traps: mistake → fix
Mistake: MongoDB lost the data at random
Fix: a weak write concern allowed an unconfirmed write to be rolled back.
Mistake: An arbiter is a cheap way to get high availability
Fix: it votes but holds no data, and it can lower the default write safety.
Mistake: MongoDB has no transactions
Fix: it has multi-document transactions; it is wise to need them rarely.
Mistake: Use a transaction for everything
Fix: it adds cost and conflicts; model so one document holds what must change together.
Easy to hard
Questions interviewers ask, easy to hard
- How can orders be lost after a MongoDB failover?
- What is write concern majority and what does it cost?
- When do you really need a multi-document transaction in MongoDB?
- How do you handle a TransientTransactionError?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.