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.
Horizontal Sharding, mongos Router & Chunk Balancer
Observe mongos single-shard routing vs scatter-gather queries and automatic chunk migration across replica sets.
Stateless routing daemon. Caches routing table from Config DB. Clients connect directly to mongos on port 27017.
Stores cluster catalog, database mappings, and chunk range boundaries in config.chunks with two-phase commit lock.
Background round-robin process. Triggers migration when chunk difference between shards exceeds the migration threshold.
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.
{
"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
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();5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| Four Causal Guarantees | 1. Read Your Own Writes, 2. Monotonic Reads, 3. Monotonic Writes, 4. Writes Follow Reads. |
| Prerequisites | Requires 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) } }7. Architectural Trade-offs
- •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
- •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
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?