- Compound indexes ordered by Equality -> Sort -> Range (ESR) avoid in-memory blocking sorts and slash MongoDB collection scans.
- TTL indexes on expiresAt fields purge expired refresh tokens, OTP challenges, and webhook idempotency keys automatically with zero cron jobs.
- Bounded bucketing beats unbounded embedded document arrays once per-channel telemetry or household ledger entries cross hundreds of rows.
1. Designing Multi-App MongoDB Collections Without Cross-Tenant Leaks
Across our .NET 10 ecosystem, MongoDB backs workloads with sharply different read/write profiles: high-frequency OAuth token rotation in `id.keshavsingh.in`, hierarchical storyboard documents in `AnimStudio AI`, date-indexed household vendor ledgers in `Ghar Ledger`, and burst-read competition leaderboards in `Pratiyogita`.
Whether isolating apps by dedicated database (`IdentityDb`, `AnimStudioDb`, `GharLedgerDb`, `PratiyogitaDb`) on a shared Atlas/replica cluster or scoping documents by `householdId` / `workspaceId`, every repository query enforces tenant partition keys as the leading predicate so no endpoint can ever scan across unrelated user workspaces.
2. Mastering the ESR (Equality -> Sort -> Range) Compound Index Rule
The most common performance bug in MongoDB applications is creating compound indexes in the order fields appear in a C# method signature rather than following the **ESR Rule (Equality, Sort, Range)**. Suppose Pratiyogita queries active topper scores for a specific exam, sorted by highest score descending, filtered to submissions within a time window:
If you index `{ examId: 1, submittedAt: 1, score: -1 }` (Equality -> Range -> Sort), MongoDB must scan every matching range entry and perform an in-memory blocking sort (`SORT` stage in `explain("executionStats")`), risking the 100 MB RAM sort limit under load. Reordering the index strictly to `{ examId: 1, score: -1, submittedAt: 1 }` (Equality -> Sort -> Range) lets WiredTiger walk B-tree leaves already in descending score order with zero in-memory sort!
public static async Task EnsureEcosystemIndexesAsync(IMongoDatabase db, CancellationToken ct)
{
// 1. ESR Compound Index: Equality (ExamId, Status) -> Sort (Score DESC) -> Range (SubmittedAt)
var scores = db.GetCollection<ExamScoreDoc>("exam_scores");
var esrKeys = Builders<ExamScoreDoc>.IndexKeys
.Ascending(x => x.ExamId)
.Ascending(x => x.Status)
.Descending(x => x.Score)
.Ascending(x => x.SubmittedAtUtc);
await scores.Indexes.CreateOneAsync(
new CreateIndexModel<ExamScoreDoc>(esrKeys, new CreateIndexOptions { Name = "ix_exam_status_score_submitted" }),
cancellationToken: ct);
// 2. Self-Purging TTL Index for Ephemeral OTP & Refresh Families
var otps = db.GetCollection<OtpChallengeDoc>("otp_challenges");
await otps.Indexes.CreateOneAsync(
new CreateIndexModel<OtpChallengeDoc>(
Builders<OtpChallengeDoc>.IndexKeys.Ascending(x => x.ExpiresAtUtc),
new CreateIndexOptions { ExpireAfter = TimeSpan.Zero, Name = "ttl_expires_at" }),
cancellationToken: ct);
}3. Atomic Compare-And-Swap Token Rotation via FindOneAndUpdateAsync
Never implement single-use token consumption, seat reservation, or UTR claim locking with a `FindAsync` followed by `ReplaceOneAsync` in C#. Between those two round-trips, two concurrent requests both observe `ConsumedAt == null` and both succeed! Using a single atomic `FindOneAndUpdateAsync` filter containing `{ tokenHash, consumedAt: null }` guarantees WiredTiger document-level atomicity:
| Scenario | Fragile Anti-Pattern | Hardened Production Pattern |
|---|---|---|
| Daily Ledger Entries | Unbounded array inside 1 Household doc | Monthly bucket doc `{ householdId, yearMonth: "2026-11", days: [...] }` |
| Token / Seat Claim | Read-in-C# then UpdateOne (TOCTOU race) | Single atomic `FindOneAndUpdate` with state guard in filter |
| Expired Session Cleanup | Nightly C# delete cron locking primary | Native MongoDB TTL index (`ExpireAfter = TimeSpan.Zero`) |
| List Pagination | `.Skip(50000).Limit(20)` deep offset scan | Keyset cursor pagination (`_id < lastSeenId`) in O(log N) |
4. Monthly Bucketing in Ghar Ledger for Predictable 16 MB Document Headroom
In Ghar Ledger, a family tracks 5 to 10 daily vendors (milk, newspaper, tiffin, maid) every day for years. Embedding an unbounded `Entries[]` array inside one `Household` document causes continuous document reallocation on disk, index bloat, and eventual proximity to BSON’s 16 MB limit. Partitioning documents into deterministic monthly buckets (`_id = "{householdId}:{vendorId}:2026-11"`) caps every document cleanly at <= 31 daily slots—allowing an entire month’s calendar UI to load in one single-kilobyte point read!
- Project only required fields (`.Project(...)`) on high-RPS list endpoints so network egress stays lean.
- Register `CamelCaseElementNameConvention` and `IgnoreExtraElementsConvention` globally at startup so schema evolution never throws deserialization exceptions during rolling deploys.
- Model your read/cache ratios in our Microservices Capacity Planner at /tools/api-latency-capacity-planner.
Frequently Asked Questions
Does MongoDB’s background TTL monitor delete expired documents at the exact millisecond?
MongoDB’s TTL background thread runs once every 60 seconds, so always include `&& x.ExpiresAtUtc > DateTime.UtcNow` in your read filter for security-critical tokens while letting TTL handle storage reclamation automatically.
When do I need multi-document ACID transactions in MongoDB?
Whenever an invariant spans two separate collections (such as crediting a tournament tally while archiving a ledger state); however, modeling atomic aggregates (like monthly ledger buckets) avoids 90% of multi-document lock overhead.
Why does Skip(N) degrade linearly at high page numbers?
Even with an index, `Skip(50000)` forces MongoDB to walk and discard 50,000 index entries before returning 20 rows, whereas range cursor pagination (`CreatedAt < cursor`) jumps straight to the target B-tree leaf.