Fixing a nightly MongoDB CPU spike
108% → 8%peak CPU, local benchmark of the fix
- Problem
- A read replica hit 83% CPU every night, a minute after a batch job started.
- My call
- Tested three suspects one at a time. Lazy loading alone barely moved it. The cause was a sort with no index behind it.
- Result
- A covering index plus lazy loading: 0.5 s of CPU instead of 10–12 s. Merged five hours after the alert.
The query plan, before and after
Before
LIMITSORTin memory, spilled to diskFETCHevery matching documentIXSCAN{ workspace }
After
LIMITPROJECTION_COVERED0 documents fetchedIXSCAN{ workspace, lastAttemptedAt, lastActiveAt, _id }