DEV Community

Mpiric Software
Mpiric Software

Posted on Fully Autonomous

Node.js in Production: 9 Decisions That Decide Whether Your Backend Scales

Most Node.js backends don't fail because of Node. They fail because of a handful of early decisions that felt harmless at 50 requests a minute and became expensive at 5,000. After reviewing a lot of Node services built by startups and mid-size teams, the same nine decisions keep showing up. Here they are, with what we'd choose today.

1. Pick a framework for the team you'll have, not the one you have

Express is still everywhere, and that's fine for small services. But once more than three or four developers touch the codebase, the lack of structure starts to cost time. Two options hold up well:

  • Fastify when you want raw throughput and JSON-schema validation built in.
  • NestJS when you want modules, dependency injection and conventions that new hires recognise on day one.

The wrong choice isn't Express versus Nest. It's having five services each organised differently.

2. Validate at the edge, every time

Every request body, query string and header that reaches your business logic should already be validated and typed. Use a schema library (Zod, TypeBox or Fastify's JSON schemas) and reject bad input with a clear 400 before it hits a database.

import { z } from 'zod';

const CreateInvoice = z.object({
  customerId: z.string().uuid(),
  amountCents: z.number().int().positive(),
  currency: z.enum(['USD', 'GBP', 'EUR', 'INR']),
});

app.post('/invoices', async (req, res) => {
  const parsed = CreateInvoice.safeParse(req.body);
  if (!parsed.success) return res.status(400).json(parsed.error.flatten());
  const invoice = await invoices.create(parsed.data);
  res.status(201).json(invoice);
});
Enter fullscreen mode Exit fullscreen mode

This one habit removes a whole class of production bugs and makes your API self-documenting.

3. Never block the event loop (and measure it)

Node is fast until something synchronous runs on the main thread: a big JSON.parse, image resizing, PDF generation, a bcrypt call with a high cost factor. One slow request then delays every other request.

  • Move CPU-heavy work to worker threads or a separate job queue.
  • Track event-loop lag as a metric. If p99 lag goes above ~50 ms, something is blocking.
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => {
  metrics.gauge('event_loop_p99_ms', h.percentile(99) / 1e6);
  h.reset();
}, 10_000);
Enter fullscreen mode Exit fullscreen mode

4. Put slow work in a queue

Sending emails, generating reports, calling slow third-party APIs, syncing to a CRM: none of these belong inside an HTTP request. Push them to a queue (BullMQ on Redis is the common Node choice, or SQS/Cloud Tasks if you're on a cloud provider) and return immediately. Make each job idempotent, because queues deliver at least once.

5. Size your database pool deliberately

A common outage pattern: the app scales to 20 containers, each with a pool of 20 connections, and the database falls over at 400 connections. Decide the total budget first, then divide it across instances. With PostgreSQL, put PgBouncer in front once you pass a few instances.

Also set timeouts on everything: query timeouts, pool acquire timeouts and HTTP client timeouts. A Node service without timeouts doesn't fail fast; it fails slowly and takes neighbours with it.

6. Structured logs and traces from day one

console.log doesn't scale past one developer. Use a structured logger (pino is the fastest) and attach a request ID to every log line. Add OpenTelemetry tracing early so you can follow a request through API, queue and database. When something is slow in production, traces turn a two-day investigation into a twenty-minute one.

7. Treat configuration and secrets as code

Load configuration once at startup, validate it with the same schema library you use for requests, and crash immediately if something is missing. Keep secrets in a secret manager, not in .env files committed "temporarily". Rotate them without redeploying code.

8. Ship small, ship often, with real health checks

  • A liveness check that only says "the process is running".
  • A readiness check that confirms the database and cache are reachable.
  • Graceful shutdown: on SIGTERM, stop accepting new requests, finish in-flight ones, close the pool, then exit.
process.on('SIGTERM', async () => {
  server.close();          // stop new connections
  await queue.close();     // finish current jobs
  await db.end();          // release connections
  process.exit(0);
});
Enter fullscreen mode Exit fullscreen mode

Without graceful shutdown, every deploy drops a few requests – and users notice.

9. Decide early when not to use Node

Node is excellent for I/O-heavy APIs, real-time features (WebSockets, SSE) and BFF layers in front of other services. It's a weaker fit for heavy numeric work, long-running CPU jobs or ML inference. Those belong in a separate service (often Python or Go) that your Node API calls. Choosing this boundary early saves a painful rewrite later.

A quick self-check

If you can answer "yes" to most of these, your Node backend is in good shape:

  • Every endpoint validates input with a schema
  • Event-loop lag is measured and alerted on
  • Slow work runs in a queue with idempotent jobs
  • Database connections are budgeted, and every call has a timeout
  • Logs are structured and traces exist
  • Config is validated at startup; secrets live in a secret manager
  • Deploys are graceful and health checks are real

If several answers are "no", that's usually where the next incident will come from.


We build and maintain Node.js backends for startups and mid-size companies at Mpiric Software. If you're planning a new API or untangling an existing one, our Node.js development team is happy to compare notes.

Top comments (0)