Why is my Node.js API slow when many users hit it at once?
posée 4 months ago571 vuesen
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.
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
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().
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.