Skip to content
API Latency Optimisation: How I Cut Response Times by 60%

API Latency Optimisation: How I Cut Response Times by 60%

A
Adarsh Sharma
2 min read0 views
PerformanceNode.jsMongoDBRedisOptimisation

A practical walkthrough of diagnosing and fixing API performance bottlenecks in a production Node.js application — the tools, the culprits, and the fixes.

Six months into a production deployment, the client flagged that the application was "feeling slow." The frontend was fast; the culprit was the API layer. Response times on some endpoints had crept above 800ms. Here's how I brought them below 300ms.

The first step was measurement. You cannot optimise what you cannot see. I added structured logging to every API route capturing request duration, database query count, and database query duration. Within an hour, patterns emerged: two endpoints accounted for 80% of the latency problem — classic 80/20.

The primary culprit was N+1 queries. One endpoint was fetching a list of records and then making a separate database query for each record to fetch related data. For a list of 50 items that's 51 queries. The fix was straightforward: a single aggregation query with a $lookup stage replaced the loop. Latency on that endpoint dropped from 620ms to 45ms.

The second culprit was missing indexes. MongoDB without indexes does full collection scans for every query. Two of our frequently-queried fields had no index. Adding compound indexes on the most common query patterns — taking about 10 minutes to implement — reduced those query times from ~200ms to ~8ms.

The third optimisation was response caching for read-heavy endpoints that serve relatively static data. A Redis cache with a 60-second TTL eliminated the database round-trip for our most frequently called endpoints entirely.

Total result: average API response time from 480ms to 190ms. The lesson: measure first, optimise second. Most performance problems are obvious once you can see where time is actually being spent.

Stay in the loop

New articles straight to your inbox.

Reactions…
Share