Node.js Best Practices for Reliable Apps
In this article
Node.js best practices for building reliable applications center on asynchronous error handling, structured logging, and disciplined process management. This article outlines the core patterns and tools that help production Node.js services stay stable under load, recover from failures, and remain debuggable.
Why Node.js Reliability Is Different
Node.js runs a single-threaded event loop. That means one uncaught exception or unhandled promise rejection can crash the entire process. Unlike multi-threaded servers where one worker can fail independently, a Node process that throws is gone unless you explicitly catch it. This is the root reason why error handling is the #1 reliability practice in Node.js, not an optional extra.
Another unique factor is the non-blocking I/O model. Because most operations return promises or callbacks, errors can be silently swallowed if you forget to attach a rejection handler. A database query that fails but has no catch will not throw; it will just leave your app in an undefined state. Reliability in Node therefore means being deliberate about every async path.
Core Error Handling Patterns
Start with the basics: wrap your Express (or similar) route handlers in a try/catch that forwards errors to a centralized error middleware. For async functions, use a wrapper like asyncHandler that catches rejections and calls next(err). Never leave a promise without a catch, even if you think it cannot fail.
For uncaught exceptions and unhandled rejections, do not just log and continue. The process may be in an inconsistent state. The recommended pattern is:
- Log the error with full stack trace.
- Attempt a graceful shutdown: close servers, flush logs, finish in-flight requests.
- Exit with a non-zero code so the process manager (PM2, Docker, Kubernetes) restarts it.
This “fail fast” approach is far more reliable than trying to keep a corrupted process alive. A restart is cheap; a silent corruption is expensive.
Structured Logging and Monitoring
Console.log is not enough. Use a structured logging library like pino or winston that outputs JSON. Each log line should include a timestamp, level, request ID, and relevant context (user ID, route, error code). This makes it possible to filter logs in production and correlate a single request across multiple services.
Set up health check endpoints (/health and /ready) that report whether the process is alive and whether dependencies (database, cache) are reachable. Your orchestration layer should call these regularly. Also monitor memory usage: a memory leak is a common reliability killer in long-running Node processes. Track heap size and look for steady growth over time.
Process Management and Graceful Shutdown
Run Node with a process manager that restarts on crash. PM2 is a popular choice for single-server deployments; Kubernetes with a proper liveness probe works for containerized setups. But restart alone is not enough—you must handle shutdown gracefully.
When you receive a SIGTERM signal (e.g., from Docker stop), you should:
- Stop accepting new connections.
- Wait for in-flight requests to finish (with a timeout, e.g., 10 seconds).
- Close database connections and other resources.
- Exit with code 0.
This prevents dropped requests during deploys and reduces the chance of data corruption. Many reliability incidents come from abrupt termination, not from crashes.
Handling External Dependencies
Your app is only as reliable as its weakest dependency. When calling external APIs or databases, always apply timeouts. A database query that hangs forever will block your event loop and take down the whole service. Use Promise.race or a library like p-timeout to enforce a maximum wait time.
Implement retries with exponential backoff and jitter for transient failures (like network blips). But be careful: retrying a non-idempotent operation (like a payment) can cause duplicates. Only retry operations that are safe to repeat, or include an idempotency key. Also use circuit breakers: if a dependency fails 5 times in a row, stop calling it for 30 seconds and fail fast instead of timing out each time.
Common Mistakes That Kill Reliability
Several recurring mistakes undermine Node.js reliability:
- Ignoring promise rejections – always attach a catch, even if you just log it.
- Blocking the event loop – synchronous CPU-heavy work (like JSON.parse on a huge payload) freezes all requests. Offload to worker threads or split the work into chunks.
- Unbounded concurrency – firing 1000 simultaneous requests to a database will overwhelm it. Use a concurrency limiter like
p-limit. - No request timeouts – a slow client can hold a socket open forever, exhausting memory. Set server.timeout and keep-alive limits.
- Logging errors without context – a stack trace alone is useless if you don’t know which user or which request caused it.
Testing and Deployment for Reliability
Automated tests are your first defense. Write unit tests for pure logic, integration tests for routes and database calls, and a few end-to-end tests for critical user journeys. Use a test runner like Jest or Vitest. Include negative tests: what happens when the database is down, when an API returns 500, when a payload is malformed.
In deployment, use a CI pipeline that runs tests, builds a Docker image, and pushes it to a registry. Use a rolling deployment strategy (e.g., Kubernetes rolling update) so you never have zero instances. Always keep the previous version available for quick rollback. Environment variables should be injected via secrets manager, not hardcoded.
Frequently Asked Questions
Should I use cluster or pm2 for multi-core?
Both work. Node’s built-in cluster module lets you fork worker processes on each CPU core, sharing the same port. PM2 has a cluster mode that does the same with a simpler CLI. For containerized environments, run one process per container and let Kubernetes scale horizontally—that is often simpler and more reliable.
What is the best way to handle unhandled promise rejections?
In modern Node (v15+), unhandled rejections crash the process by default, which is good. Do not override that with process.on('unhandledRejection') to ignore them. Instead, use that hook to log the error, then exit gracefully. Fix the root cause by adding catch blocks to every promise.
How do I debug a memory leak in Node.js?
Use the --inspect flag and the Chrome DevTools heap profiler. Take two heap snapshots a few minutes apart and compare them to see which objects are growing. Common culprits are caches without eviction, global variables, and event listeners that are never removed. Also monitor the heapUsed metric over time.
Is it okay to use console.log in production?
It works but is not recommended. Console.log is synchronous and can slow down the event loop under high load. It also lacks structured fields, making log aggregation harder. Use a logging library that writes asynchronously and outputs JSON.
What is the difference between liveness and readiness probes?
Liveness probe tells Kubernetes whether to restart the container (e.g., is the process alive?). Readiness probe tells whether the container can serve traffic (e.g., is the database connected?). Use both: a container can be alive but not ready (e.g., during startup or after a dependency failure).
Should I use TypeScript for reliability?
TypeScript catches a whole class of errors at compile time—typos, wrong types, null references—that would otherwise crash at runtime. It does not replace error handling, but it reduces the number of unexpected runtime errors. Many production teams adopt TypeScript for exactly this reason.