Skip to the page

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.

The 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

  1. How can orders be lost after a MongoDB failover?
  2. What is write concern majority and what does it cost?
  3. When do you really need a multi-document transaction in MongoDB?
  4. How do you handle a TransientTransactionError?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview