Designing Resilient Backend APIs with Node.js & Express

Node.js is renowned for its non-blocking event-driven I/O model, making it an ideal choice for high-concurrency microservices and REST APIs. However, without structured middleware layer design, database connection management, and rate limiting, API latency can quickly degrade under heavy traffic load.

As a Freelance Solution Architect, I have built Node.js backends powering financial applications, SaaS platforms, and mobile apps. Here is my proven blueprint for enterprise Node.js API development.


1. Database Connection Pooling with PostgreSQL (`pg-pool`)

Opening a new database TCP connection for every incoming HTTP request causes severe latency spikes and quickly exhausts database resources. Always configure connection pools with explicit max connections and idle timeouts:

typescript
Snippet
import { Pool } from 'pg';

export const dbPool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20, // Maximum client pool size
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

2. Redis Caching Layer for Frequent Read Queries

Read-heavy endpoints (such as product catalogs, user profiles, or configuration metrics) should bypass relational database queries whenever cached data is available:

typescript
Snippet
export async function getCachedData<T>(key: string, fetcher: () => Promise<T>, ttlSeconds = 3600): Promise<T> {
  const cached = await redisClient.get(key);
  if (cached) return JSON.parse(cached);

  const freshData = await fetcher();
  await redisClient.setEx(key, ttlSeconds, JSON.stringify(freshData));
  return freshData;
}

3. Layered Controller-Service-Repository Pattern

Avoid cluttering route handlers with raw SQL queries or business validation. Enforce clean layer separation:

  • Routes: Enforce rate limiting, validation schemas (Zod/Joi), and HTTP routing.
  • Controllers: Handle HTTP request extraction and response formatting.
  • Services: Execute domain logic, payment gateways, and third-party API orchestration.
  • Repositories: Isolated database queries using Knex.js, Kysely, or Prisma.

  • 4. Security & Middleware Essentials

  • Helmet.js: Enforce security headers (HSTS, CSP, X-Content-Type-Options).
  • Rate Limiting: Prevent DDoS and brute force attacks using express-rate-limit backed by Redis.
  • JWT & Refresh Tokens: Store short-lived access tokens (15 mins) and HTTP-only encrypted refresh cookies.
  • Structured Logging: Use Pino or Winston with JSON outputs for instant integration into Datadog or CloudWatch.

  • Need Custom Backend API Engineering?

    Whether you need a new REST API designed from scratch or performance optimization for an existing Node.js system, [contact me today](/contact) to discuss your project requirements.