When an API in a Node.js app has high latency, the goal is to find where time is being spent—whether it’s CPU, database, external APIs, or the event loop.
1. Start with Basic Logging (Quick Win)
Measure execution time inside your API.
app.get("/users", async (req, res) => {
console.time("API /users");
// your logic
const data = await getUsers();
console.timeEnd("API /users");
res.json(data);
});
👉 Helps identify which API is slow
2. Break Down the API (Granular Timing)
Check each step:
console.time("DB");
await dbQuery();
console.timeEnd("DB");
console.time("External API");
await fetchData();
console.timeEnd("External API");
👉 Pinpoints the exact bottleneck (DB, API, logic)
3. Check Database Performance
Most latency issues come from DB.
- Slow queries
- Missing indexes
- Large data fetch
✔ Solutions:
- Add indexes
- Optimize queries
- Use pagination
4. Monitor Event Loop Blocking
If CPU-heavy code blocks the event loop → API becomes slow.
Use tools like:
clinic.jsnode --inspect
👉 Check for:
- Long loops
- Heavy calculations
- Sync code (
fs.readFileSync)
5. Use Profiling Tools
Built-in Profiler
node --inspect app.js
Open Chrome DevTools → Performance tab
Production Tools
- New Relic
- Datadog
- AppDynamics
👉 Gives real-time latency insights
6. Check External API Calls
If your API depends on another service:
- Network delay
- Slow third-party APIs
✔ Fix:
- Add timeout
- Use caching
- Retry logic
7. Add Caching
If same data is fetched repeatedly:
- Use Redis / in-memory cache
if (cache[key]) return cache[key];
👉 Reduces DB/API calls → faster response
8. Enable Logging & Monitoring
Track:
- Response time
- Error rate
- Throughput
Use middleware:
app.use((req, res, next) => {
const start = Date.now();
res.on("finish", () => {
console.log(req.url, Date.now() - start, "ms");
});
next();
});
9. Check for Memory or Resource Issues
- High memory usage
- CPU spikes
- Too many open connections
👉 Can slow down APIs indirectly
10. Load Testing
Use tools like:
- JMeter
- k6
- Artillery
👉 Helps identify how API behaves under load
Real-world Example
API is slow because:
- Fetching 10,000 records
- No pagination
✔ Fix:
- Add limit + pagination
- Response time drops significantly
Key Takeaway
To debug bad latency:
👉 Measure → Break down → Identify bottleneck → Optimize
Most issues come from DB queries, blocking code, or external APIs, so focus there first and use proper monitoring tools for deeper insights.