22. Production Indexing Workflow

A disciplined indexing workflow reduces guesswork:

  1. Identify a slow or high-volume query from monitoring or application telemetry.
  2. Capture its filter, sort, projection, and representative parameters.
  3. Run explain with execution statistics.
  4. Identify whether the bottleneck is scanning, sorting, fetching, joining, or returning a large result.
  5. Design one or more candidate indexes.
  6. Test correctness and performance against realistic data.
  7. Evaluate write overhead and index size.
  8. Deploy using an appropriate operational process.
  9. Monitor latency, throughput, errors, cache behavior, and index usage.
  10. 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?