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.

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
SDE & Team Lead specializing in scalable Node.js microservices, distributed systems, and rapid startup MVP delivery.
More Articles

Building Sprintly: Background Workers, 2FA, Notifications & Cost-Efficient SaaS Deployment
A deep engineering case study of building Sprintly, covering independent background workers, web notifications, TOTP security, task management, Docker, and cost-efficient deployment with Render and Vercel.

Designing Production RAG Pipelines with LangChain, Pinecone & OpenAI in Node.js
A complete guide to building low-latency, contextual Retrieval-Augmented Generation workflows in Node.js and TypeScript.

Building High-Concurrency Node.js Workflows Processing 1M+ Records with AWS SQS
Architectural patterns for scaling asynchronous Node.js data pipelines, event-driven queues with AWS SQS, and preventing memory leaks under high throughput.