22. Production Indexing Workflow
A disciplined indexing workflow reduces guesswork:
- Identify a slow or high-volume query from monitoring or application telemetry.
- Capture its filter, sort, projection, and representative parameters.
- Run explain with execution statistics.
- Identify whether the bottleneck is scanning, sorting, fetching, joining, or returning a large result.
- Design one or more candidate indexes.
- Test correctness and performance against realistic data.
- Evaluate write overhead and index size.
- Deploy using an appropriate operational process.
- Monitor latency, throughput, errors, cache behavior, and index usage.
- Reassess after the workload changes.
Do not compare plans only on a tiny development collection. Data distribution, selectivity, and cache behavior can change the result significantly. Avoid forcing an index with hints unless there is a specific, tested reason and a plan for future data changes.
Code Example
// 1. Inspect current indexes.
db.orders.getIndexes();
// 2. Explain the real query.
db.orders.find({ status: "delivered", customerId: 501 })
.sort({ createdAt: -1 })
.limit(20)
.explain("executionStats");
// 3. Test a candidate index in an appropriate environment.
// db.orders.createIndex({ status: 1, customerId: 1, createdAt: -1 });Key Takeaways
- Start from a measured workload problem.
- Use explain to locate the source of the cost.
- Test candidates against representative data.
- Monitor both read benefits and write costs after deployment.
Knowledge Check
What is the best first step when investigating a slow query?