Why is my Node.js API slow when many users hit it at once?
poze 4 months ago565 gadeen
My endpoint resizes an uploaded image with a pure-JS library. With 20 concurrent users, every request (even /health) becomes slow. CPU is at 100% on one core.
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
Node runs your JavaScript on one thread. CPU-heavy work (image resizing, big JSON parsing, crypto in JS, sync loops) blocks the event loop, so every other request waits, including /health.
Fixes, from easiest to most scalable:
1. Use a native library: sharp does the work in libvips on a thread pool and doesn't block the loop. 2. Move CPU work to worker threads (node:worker_threads, or piscina for a pool). 3. Move it off the request path: accept the upload, enqueue a job (BullMQ + Redis), return 202, and process it in a separate worker process. 4. Run multiple processes (the cluster module, PM2, or several containers) to use all cores.
To confirm the diagnosis, measure event-loop lag with perf_hooks.monitorEventLoopDelay().
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.