Course contentsShow
← Databases & SQL
Lesson 1220 of 1,95311. NoSQL and Document ModelsFree lesson

Write Concern Levels

Configure acknowledgment levels to guarantee data persistence during network partitions.

In this lesson, you will learn how to configure acknowledgment levels in distributed document stores to ensure your data survives even when network partitions occur.

Understanding Write Concern

When you send a write operation to a replica set, the "Write Concern" is the setting that defines the level of acknowledgment requested from the database. It dictates how many nodes must confirm that a write has been processed before the database reports success to your application. This is your primary defense against data loss during unexpected network partitions.

The Acknowledgment Levels

The core of Write Concern relies on a trade-off between speed and durability:

  • w: 0 (Unacknowledged): The database does not wait for any confirmation. It is the fastest option, but if a network partition occurs immediately after your request, you have no guarantee the data ever reached the primary node.
  • w: 1 (Acknowledged): The primary node acknowledges the write as soon as it is applied to its local memory or journal. While this ensures the primary has the data, if the primary crashes or becomes partitioned before replicating to secondaries, that data might be lost.
  • w: "majority": The database waits for the write to be applied to a majority of the replica set members. This is the industry standard for production systems. If a network partition isolates the primary, you can be confident that your data is already persisted on enough nodes to survive a failover, ensuring consistency across your distributed cluster.

A Practical Example

If you are updating an account balance, you want to ensure the write is safe. Using a w: "majority" concern prevents a scenario where a client receives a "success" message, but the data is wiped out because the primary node failed before the write could be replicated.

db.accounts.updateOne(
  { accountId: 123 },
  { $inc: { balance: 50 } },
  { writeConcern: { w: "majority", j: true } }
)

Note: Adding j: true ensures the write is also flushed to the on-disk journal, providing even stricter persistence during a power failure.

Key Takeaway: Use w: "majority" to ensure your data is durably replicated across your cluster, providing the necessary resilience against network partitions and node failures.