← Back to list

MongoDB Write Concerns and Read Preferences: A Comprehensive Guide

Introduction

Jun Seo · 2025-11-11 12:30 · 0 claps · 5.7 min read
#sre #devops #infrastructure #mongodb #database
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud

Your MongoDB will crash if you don’t do this config

Introduction

MongoDB provides flexible options for controlling write durability and read consistency through write concerns and read preferences. Understanding these concepts is crucial for designing systems that balance performance, consistency, and availability according to your application’s needs.

Write Concerns

Write Concern: w=1

Definition: The write operation returns success after being acknowledged by the primary. This means the write is confirmed as soon as it reaches the primary node, without waiting for replication to secondary nodes.

The key word here is asynchronous, replication happens independently and doesn’t block the acknowledgment back to the client. The primary doesn’t wait for the secondaries to confirm they’ve received the data before telling the client the write succeeded. This is why w=1 has a risk of data loss

Advantages:

  • Lower write latency: Minimal delay since only the primary node needs to acknowledge the write operation
  • Higher write throughput: Can process significantly more write operations per second compared to majority writes
  • Simple configuration: Default behavior in MongoDB, requires no additional configuration and is straightforward to implement
  • Reduced resource consumption: Minimizes network overhead, replication bandwidth, and CPU usage across the cluster since acknowledgment doesn’t wait for secondary replication

Disadvantages:

  • Risk of data loss: If the primary node crashes before the write is replicated to any secondary nodes, the acknowledged write will be permanently lost.
  • Eventual consistency challenges: if read config is set as read from secondary, secondary nodes may not reflect recently acknowledged writes, potentially causing confusion or application logic errors when clients see stale data

Write Concern w=majority

Definition: With w=majority, the write operation only returns a success acknowledgment after a majority of the replica set members have confirmed receipt and persistence of the data.

With w=majority, replication to secondary nodes happens asynchronously and continuously, but the key difference is when the acknowledgment is sent back to the client.

The replication process works like below.

  • The primary receives the write operation
  • The primary writes to its own oplog
  • Secondary nodes continuously pull from the primary’s oplog (this happens in the background)
  • Each secondary acknowledges when it has successfully applied the write
  • Only when a majority of nodes (primary + secondaries) have acknowledged does the client receive confirmation

Pros:

  • Enhanced data durability: Because the data is replicated to multiple nodes before acknowledgment, writes are highly resilient to failure scenarios. Even if the primary node crashes immediately after acknowledging a write, the data is preserved on secondary nodes which provides strong data guarantees.
  • Strong consistency guarantees: When w=majority is combined with appropriate read concerns such as “majority” or “linearizable”, you can achieve strong consistency guarantees. This means that once a write is acknowledged, subsequent reads (with the appropriate read concern) will reflect that write, providing a level of consistency comparable to traditional RDBMS systems.

Disadvantages:

  • Increased write latency: Since the primary node must wait for acknowledgment from a majority of replica set members before confirming the write to the client, there is an inherent latency cost.
  • Reduced write throughput: The requirement to wait for multiple nodes to acknowledge writes means the system can handle fewer write operations per second compared to w=1.
  • Network sensitivity: The performance of w=majority writes is directly tied to network quality and latency between replica set members. Any network degradation, congestion, or increased latency between nodes will directly impact write performance.
  • Availability trade-offs: If a majority of nodes become unavailable due to network partitions, hardware failures, or maintenance activities, the system cannot achieve w=majority acknowledgment, causing all write operations to fail until the majority becomes available again.

Read Preferences: Primary vs Secondary

Reading from Primary

Definition: When configured to read from the primary, all read operations are routed exclusively to the primary node in the replica set. This ensures that every read operation accesses the most authoritative and up-to-date version of the data, as the primary is the single source of truth for all write operations.

Advantages:

  • Strongest consistency guarantees: Reading from the primary ensures you always access the most recent committed data. Since all writes go through the primary first, any read from the primary reflects the absolute latest state of your database, eliminating any possibility of reading stale or outdated information.
  • Zero replication lag concerns: Because you’re reading directly from the source of all writes, there is no delay associated with data propagation to secondary nodes. This means you can immediately see the results of your own writes.

Disadvantages:

  • Primary node becomes a bottleneck: Since all read traffic is concentrated on a single node, the primary can become overwhelmed when serving both write operations and read operations simultaneously.
  • Resource contention between reads and writes: The primary node must allocate its CPU, memory, and I/O resources to handle both incoming write operations and read queries. During periods of high read activity, this contention can slow down write operations, and conversely, heavy write loads can degrade read performance.

Reading from Secondaries

Definition: Read operations are directed to secondary nodes in the replica set rather than the primary. MongoDB offers several read preference modes to control this behavior, including secondary (always read from secondaries), secondaryPreferred (prefer secondaries but fall back to primary if none available), and nearest (route to the node with lowest network latency regardless of type).

Advantages:

  • Read scalability: By distributing read operations across multiple secondary nodes, you can significantly increase the overall read capacity of your cluster. This horizontal scaling approach allows you to handle substantially more concurrent read requests.
  • Primary offloading: By directing read traffic to secondary nodes, you free up the primary node’s resources to focus exclusively on write operations and maintain optimal write performance.
  • Higher availability during failover: If the primary node becomes unavailable due to failure or maintenance, read operations can continue uninterrupted by using secondary nodes. This maintains read availability even during replica set elections when a new primary is being selected.

Disadvantages:

  • Replication lag: Secondary nodes replicate data asynchronously from the primary, which means there is always some delay between when data is written to the primary and when it appears on secondaries.
  • Inconsistent reads across secondaries: At any given moment, different secondary nodes may be at different points in the replication process. This means that consecutive reads from different secondaries could return different versions of the same data
  • Application complexity: Applications that read from secondaries must be designed to handle the possibility of reading stale data.

Architecture Examples and Use Cases

1. Financial Transactions System

Configuration:

  • w=majority for all writes
  • Read from primary
  • Read concern: majority or linearizable

Rationale:

Financial data requires absolute consistency and durability. Cannot afford data loss or reading stale balances. The trade-off of higher latency is acceptable for correctness.

2. Real-time Analytics Dashboard

Configuration:

  • w=1 for metric ingestion
  • Read from secondaryPreferred or nearest
  • Read concern: local

Rationale:

High write throughput is critical for ingesting metrics. Slight staleness in dashboard is acceptable.

3. E-commerce Product Catalog

Configuration:

  • w=majority for inventory updates and orders
  • w=1 for product views, reviews (can be eventually consistent)
  • Read from nearest for product browsing
  • Read from primary for checkout and inventory checks

Rationale:

Mixed approach: critical operations (orders, inventory) require durability, while non-critical operations (views, reviews) prioritize performance. Product browsing can tolerate slight staleness for better geographic distribution.

4. Social Media Feed

Configuration:

  • w=1 for posts, likes, comments
  • Read from secondaryPreferred
  • Read concern: local

Rationale:

Social media prioritizes speed and availability over perfect consistency. Users accept eventual consistency (seeing posts/likes appear after brief delay). High read/write throughput is essential.

Decision Framework

Choose w=majority when:

  • Data loss is unacceptable
  • Consistency is more important than throughput

Choose w=1 when:

  • High write throughput is critical
  • Data is non-critical
  • Performance is prioritized over absolute durability

Read from Primary when:

  • Strong consistency required
  • Must read your own writes immediately
  • Critical business logic depends on current data

Read from Secondary when:

  • Read-heavy workload needs scaling
  • Stale data is acceptable

Best Practices

  1. Mix strategies: Use different configurations for different collections or operations based on their criticality.
  2. Monitor replication lag: If reading from secondaries, actively monitor lag to ensure acceptable staleness.
  3. Set appropriate timeouts: Use timeout to prevent indefinite blocking on write concerns.

Conclusion

Choosing the right write concern and read preference requires understanding your application’s requirements and making informed trade-offs between consistency, durability, performance, and availability. There is no perfect solution — only the best decision you can make to design a MongoDB deployment that balances these competing concerns effectively.


메타데이터
post_id
eb0ca4a9fedd
slug
mongodb-write-concerns-and-read-preferences-a-comprehensive-guide-eb0ca4a9fedd
url
https://medium.com/@jun.seo/mongodb-write-concerns-and-read-preferences-a-comprehensive-guide-eb0ca4a9fedd
canonical_url
https://medium.com/@jun.seo/mongodb-write-concerns-and-read-preferences-a-comprehensive-guide-eb0ca4a9fedd
author_url
https://medium.com/@jun.seo
status
ok
fetched_at
2026-06-16 19:09:56