Skip to content
LESSON 47 / 50Expertdistributed

Causal Consistency Sessions & Logical Clocks

Causal Consistency client sessions utilize Lamport logical clocks (ClusterTime) to guarantee Read-Your-Own-Writes consistency even when reading from lagging secondaries.

Interactive Engine Simulator

Horizontal Sharding, mongos Router & Chunk Balancer

Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.

mongos Query Router

Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.

Config Replica Set (CSRS)

Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.

Chunk Balancer

Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.

Shard 01 (Replica Set: rs-shard-01)3 Chunks
chunk-1Range: [MinKey .. 1000)
450 docs
chunk-2Range: [1000 .. 2000)
820 docs
chunk-3Range: [2000 .. 3000)
610 docs
Shard 02 (Replica Set: rs-shard-02)1 Chunks
chunk-4Range: [3000 .. MaxKey)
390 docs
MONGOS_LOG:Cluster balanced across 2 shards. Shard key: { user_id: 1 }.

1. Formal Definition & Architecture Intent

Causal Consistency is a consistency model in MongoDB client sessions. If operation B is causally related to operation A (e.g. an update followed by a read), causal consistency guarantees that every node in the cluster will observe operation A before observing operation B. It enables "Read-Your-Own-Writes" and "Monotonic Reads" across secondaries using Lamport logical timestamps ($clusterTime).

2. Explain Like I'm 5 (Mental Model)

Imagine posting a comment on social media and then refreshing the page. In an inconsistent system, your comment disappears because your phone read from a lagging replica. With causal consistency, your phone carries a timestamp passport saying: "I have seen up to event #500; do not answer me until you have caught up to event #500."

3. Real-World Architecture Example

A user creates a new account and immediately reads their account details from a secondary node.

Sample BSON Documents:
Collection: db.client_session_tracking
{
  "session_id": "sess_9921827",
  "operationTime": "Timestamp(1740837600, 4)",
  "clusterTime": "Timestamp(1740837600, 4)"
}

The client passes its operationTime to the secondary; the secondary pauses until its local oplog reaches that timestamp before returning.

4. MQL Implementation Steps

Step 1: Start a causally consistent client session in Node.js / mongosh
const session = db.getMongo().startSession({ causalConsistency: true });
const orders = session.getDatabase("store").orders;

// Write to Primary:
orders.insertOne({ order_id: 101, total: 250 });

// Read from Secondary with Read-Your-Own-Writes guarantee:
orders.find({ order_id: 101 }).readPref("secondary");
session.endSession();
Guarantees the newly inserted order is visible even when reading from a secondary!

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Four Causal Guarantees1. Read Your Own Writes, 2. Monotonic Reads, 3. Monotonic Writes, 4. Writes Follow Reads.
PrerequisitesRequires writeConcern: "majority" and readConcern: "majority".

6. Deep Dive: Lamport Logical Clocks ($clusterTime) Protocol

MongoDB servers maintain a global hybrid logical clock (HLC). Every response from the server includes $clusterTime and operationTime. The client driver records these timestamps. When issuing subsequent reads, the driver automatically injects afterClusterTime: operationTime into the request. The secondary node checks its local oplog: if it has not replayed up to afterClusterTime, it waits until the oplog catches up before returning results.

// Driver auto-injected payload:
// { "find": "orders", "readConcern": { "level": "majority", "afterClusterTime": Timestamp(1740837600, 4) } }
Production Warning: If a secondary has severe replication lag, waiting for afterClusterTime can add latency up to maxStalenessSeconds.

7. Architectural Trade-offs

Advantages
  • •Eliminates the #1 headache of replica sets: stale reads following recent writes
  • •Allows applications to safely offload reads to secondaries without breaking user expectations
  • •Requires zero custom application caching or synchronization logic
Disadvantages & Gotchas
  • •Requires writeConcern and readConcern set to majority
  • •Reads on a severely lagging secondary will wait until the oplog catches up or timeout

8. Technical Interview Questions

Q1: How do Causal Consistency sessions in MongoDB guarantee "Read-Your-Own-Writes" when reading from secondary nodes?

Client sessions track the cluster logical timestamp (operationTime) returned by the primary after a write. When the client executes a subsequent read against a secondary, the driver passes afterClusterTime: operationTime. The secondary node delays answering the query until its local oplog has caught up and applied all changes up to that exact timestamp, guaranteeing the write is visible.

9. Staff-Level Ready Answer

"Causal consistency sessions use Lamport logical clocks ($clusterTime) to guarantee that causally dependent operations are observed in order across all replica nodes. By passing afterClusterTime on reads, secondaries wait for their local oplog to catch up to recent writes, delivering Read-Your-Own-Writes consistency on secondaries."

10. Quick Knowledge Check

Which timestamp parameter is injected by the client driver to ensure a secondary node has caught up before executing a causally consistent read?