How do you optimize a slow Node.js API endpoint?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Node.js deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Optimizing a slow Node.js API endpoint requires systematic profiling before making changes. Steps: (1) Profile first: use Node.js's built-in profiler (node --prof + node --prof-process), Chrome DevTools (attach via node --inspect), or clinic.js to identify the actual bottleneck — don't guess; (2) Database queries: most slowness is here — add indexes on frequently queried fields, use EXPLAIN/EXPLAIN ANALYZE to understand query plans, batch queries (eliminate N+1), add caching for expensive queries; (3) Caching: cache database results in Redis with appropriate TTL — const cached = await redis.get(key) || await db.fetch(key); (4) Async optimization: run independent async operations in parallel with Promise.all() instead of sequential awaits; (5) Payload size: paginate large lists, select only needed fields, use compression (gzip/brotli with compression middleware); (6) CPU-bound code: offload to Worker Threads; (7) HTTP caching: set Cache-Control headers for public data; (8) CDN: serve static assets via CDN; (9) Connection pooling: ensure database pool is properly sized; (10) Load test: use k6, Artillery, or autocannon to verify improvements under load.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Node.js experience.