High Availability & Consistency

Distributed systems force you to choose between consistency and latency. MongoDB gives you granular control over this trade-off via Write Concern and Read Concern.

1. Write Concern

Write Concern determines when a write is considered “successful”.

  • w: 1 (Default): Acknowledge as soon as the Primary applies the write. Fast, but data is lost if Primary crashes before replicating.
  • w: "majority": Acknowledge only after the write propagates to a majority of nodes (e.g., 2 out of 3). Safe against rollback.
  • j: true: Wait for the write to be flushed to the on-disk Journal. Ensures durability even if the server loses power immediately.
Primary Secondary Secondary w: 1 (Fast) w: majority (Safe)

2. Read Concern

Read Concern determines how “fresh” or “safe” the data you read is.

  • local: Return the most recent data available on the node. May be rolled back.
  • majority: Return data that has been acknowledged by a majority of the replica set. Durable.
  • linearizable: Guarantees that the read returns the absolute latest data, reflecting all successful writes that completed before the read started. Expensive.

3. Interactive: Consistency vs. Latency

Simulate the trade-off between write speed and data safety.

w: 1 (Primary Ack) w: majority (Replica Ack) j: true (Disk Flush)
Latency Impact
2 ms
Durability Guarantee
Low
System Ready. Adjust slider to simulate.

4. Multi-Region Strategies

For global applications, you deploy Replica Set members across different geographical regions (e.g., US, EU, Asia).

Zone Sharding

Zone Sharding allows you to pin data to specific regions.

  1. Tag Shard A as “EU”.
  2. Define a range of shard keys (e.g., country: "DE" to country: "FR") for the “EU” zone.
  3. The Balancer moves all matching chunks to Shard A.
    • Compliance: Keep GDPR data in Europe.
    • Locality: Users in Europe read/write to local servers.

5. Coding Consistency

You can set concerns at the Client, Database, Collection, or Operation level.

import com.mongodb.WriteConcern;
import com.mongodb.ReadConcern;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

public class ConsistencyLevels {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {

            // Get collection with Majority Write Concern
            MongoCollection<Document> safeCol = client.getDatabase("bank")
                .getCollection("transfers")
                .withWriteConcern(WriteConcern.MAJORITY)
                .withReadConcern(ReadConcern.MAJORITY);

            // This insert waits for acknowledgment from majority of nodes
            safeCol.insertOne(new Document("amount", 100));
            System.out.println("Secure write complete.");
        }
    }
}
package main

import (
    "context"
    "log"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/writeconcern"
    "go.mongodb.org/mongo-driver/mongo/readconcern"
)

func main() {
    // Connect
    client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))

    // Create Collection Options with Majority Concern
    wc := writeconcern.New(writeconcern.WMajority())
    rc := readconcern.Majority()

    opts := options.Collection().
        SetWriteConcern(wc).
        SetReadConcern(rc)

    coll := client.Database("bank").Collection("transfers", opts)

    // This insert is durable
    _, err := coll.InsertOne(context.TODO(), map[string]interface{}{"amount": 100})
    if err != nil {
        log.Fatal("Write failed to replicate:", err)
    }

    log.Println("Secure write complete.")
}

6. Summary

  • Write Concern controls durability (w:majority is the gold standard for safety).
  • Read Concern controls isolation (majority avoids reading rolled-back data).
  • Multi-Region clusters use Zone Sharding for compliance and low latency.
  • Always balance Latency requirements against Data Safety.