Working with Sessions

1. Starting Session

APIForm
Nodeconst s = client.startSession()
Pythonwith client.start_session() as s:
Javatry (ClientSession s = client.startSession()) {...}

2. Using Session with Operations

AspectDetail
OptionPass {session} to every op
Logical clockTracks per-session causal order

3. Setting Session Options

OptionEffect
causalConsistencyDefault true
defaultTransactionOptionsreadConcern, writeConcern, readPreference, maxCommitTimeMS
snapshotRead snapshot outside transactions (5.0+)

4. Understanding Causal Consistency

GuaranteeDetail
Read-your-writesSee own writes
Monotonic readsNever see older data than seen before
Monotonic writesWrites execute in submission order
Writes-follow-readsWrites happen after observed reads

5. Implementing Read Your Writes

StepDetail
1Use session for write
2Read using same session (even on secondary)
3readConcern majority + writeConcern majority

6. Implementing Monotonic Reads

AspectDetail
MechanismSame session token sent with each read
EffectServer waits for snapshot ≥ session clusterTime

7. Ending Session

MethodDetail
session.endSession()Release server-side resources
Auto-cleanupServer expires idle sessions after 30 min

8. Using Session with Transactions

AspectDetail
RequiredEvery txn op must include session
One txn per sessionAt a time

9. Handling Session Timeout

SettingDetail
logicalSessionTimeoutMinutes30 (server-side)
refreshDriver refreshes active sessions every 5 min
ErrorSessionExpired (code 228)

10. Understanding Session Lifecycle

client.startSession()
        │
        ▼
Active ──── operations ────▶ Active
        │
        ├─ session.endSession() ──▶ Closed
        └─ 30 min idle ──▶ Server-expired
      
StateDetail
ActiveAvailable for operations
In transactionCannot start another txn
ClosedCannot be reused