Working with Sessions
1. Starting Session
| API | Form |
|---|---|
| Node | const s = client.startSession() |
| Python | with client.start_session() as s: |
| Java | try (ClientSession s = client.startSession()) {...} |
2. Using Session with Operations
| Aspect | Detail |
|---|---|
| Option | Pass {session} to every op |
| Logical clock | Tracks per-session causal order |
3. Setting Session Options
| Option | Effect |
|---|---|
| causalConsistency | Default true |
| defaultTransactionOptions | readConcern, writeConcern, readPreference, maxCommitTimeMS |
| snapshot | Read snapshot outside transactions (5.0+) |
4. Understanding Causal Consistency
| Guarantee | Detail |
|---|---|
| Read-your-writes | See own writes |
| Monotonic reads | Never see older data than seen before |
| Monotonic writes | Writes execute in submission order |
| Writes-follow-reads | Writes happen after observed reads |
5. Implementing Read Your Writes
| Step | Detail |
|---|---|
| 1 | Use session for write |
| 2 | Read using same session (even on secondary) |
| 3 | readConcern majority + writeConcern majority |
6. Implementing Monotonic Reads
| Aspect | Detail |
|---|---|
| Mechanism | Same session token sent with each read |
| Effect | Server waits for snapshot ≥ session clusterTime |
7. Ending Session
| Method | Detail |
|---|---|
| session.endSession() | Release server-side resources |
| Auto-cleanup | Server expires idle sessions after 30 min |
8. Using Session with Transactions
| Aspect | Detail |
|---|---|
| Required | Every txn op must include session |
| One txn per session | At a time |
9. Handling Session Timeout
| Setting | Detail |
|---|---|
| logicalSessionTimeoutMinutes | 30 (server-side) |
| refresh | Driver refreshes active sessions every 5 min |
| Error | SessionExpired (code 228) |
10. Understanding Session Lifecycle
client.startSession()
│
▼
Active ──── operations ────▶ Active
│
├─ session.endSession() ──▶ Closed
└─ 30 min idle ──▶ Server-expired
| State | Detail |
|---|---|
| Active | Available for operations |
| In transaction | Cannot start another txn |
| Closed | Cannot be reused |