·7 min read

MongoDB Query Optimization & Redis Caching: Slashing Latency by 40%

Practical strategies for compound indexing, aggregation pipeline tuning, and cache-aside patterns with Redis in Node.js.

MongoDB Query Optimization & Redis Caching: Slashing Latency by 40%

Database latency is the most common reason web applications feel sluggish under load. Here are the exact techniques used to reduce MongoDB query latency by 40%.

1. Compound Indexing Strategy (ESR Rule)

Follow the Equality, Sort, Range (ESR) rule when building MongoDB compound indexes:

  • Place exact equality filters first (e.g., tenantId, status)
  • Place fields used for sort() second (e.g., createdAt)
  • Place range filters ($gte, $in) last

2. Aggregation Pipeline Projections

Never retrieve fields you do not render. Always use .select() or $project stages and .lean() to bypass Mongoose hydration overhead.

3. Smart Cache-Aside with Redis

Implement write-through or cache-aside caching with TTLs and tag-based cache invalidation:

async function getCachedUser(userId: string) {
  const cacheKey = `user:${userId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const user = await UserModel.findById(userId).lean();
  if (user) await redis.setex(cacheKey, 3600, JSON.stringify(user));
  return user;
}
Rahul

Rahul

Senior Principal Software Engineer & AI Systems Architect specializing in scalable Node.js microservices, distributed systems, and rapid startup MVP delivery.

More Articles

Let's talk.

Have a project or need help? Fill out the form, and we'll get back to you soon.