Designing Scalable APIs with Node.js and Express: Best Practices at Scale

Designing Scalable APIs with Node.js and Express: Best Practices at Scale

Learn production-grade API design patterns for Node.js: request validation, error handling, monitoring, versioning, and performance optimization for enterprise applications.

Designing Scalable APIs with Node.js and Express: Best Practices at Scale

Building an API is easy. Building one that scales gracefully under load while maintaining data integrity, security, and developer sanity—that's the challenge. This guide covers production-grade patterns for Node.js and Express.

The Foundation: Middleware & Request Pipeline

In Express, your API's reliability depends on middleware ordering. Get it wrong and requests bypass validation. Get it right and you have consistent, secure processing.

typescript// ✅ Correct middleware order
app.use(helmet());  // Security headers first
app.use(express.json({ limit: '1mb' }));  // Parse JSON
app.use(requestLogger);  // Log all requests
app.use(authenticate);  // Auth check
app.use(validateBody);  // Validate input

// After middleware, routes
app.post('/api/users', createUser);

Why Order Matters

  • Security headers first: Helmet sets HSTS, CSP before any processing
  • Body parsing early: You need the body before validation
  • Authentication before routes: Unauthorized requests should fail fast
  • Error handling last: Catches errors from all routes

Input Validation: The First Line of Defense

Never trust user input. Period. This is where most vulnerabilities start.

typescriptimport { z } from 'zod';  // Type-safe validation

// Define schema
const createUserSchema = z.object({
    email: z.string().email().max(255),
    name: z.string().min(2).max(100),
    password: z.string().min(12),  // Strong requirement
    role: z.enum(['user', 'admin']).default('user')
});

// Validation middleware
const validateRequest = (schema: z.ZodSchema) => {
    return (req: Request, res: Response, next: NextFunction) => {
        try {
            req.body = schema.parse(req.body);
            next();
        } catch (error) {
            res.status(400).json({ error: error.errors });
        }
    };
};

// Use it
app.post('/api/users',
    validateRequest(createUserSchema),
    createUser
);

Error Handling: Consistent, Informative, Secure

Bad error handling reveals system internals to attackers.

typescript// Create error types
class AppError extends Error {
    constructor(
        public statusCode: number,
        message: string,
        public isOperational = true
    ) {
        super(message);
    }
}

// Specific error for common cases
class ValidationError extends AppError {
    constructor(message: string) {
        super(400, message);
    }
}

// Global error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
    const statusCode = err.statusCode || 500;
    const message = err.isOperational ? err.message : 'Something went wrong';

    // Log for debugging (don't expose stack traces to client)
    console.error(err);

    res.status(statusCode).json({
        status: 'error',
        message,
        // Only include details in development
        ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
    });
});

Database Queries: Connection Pooling & Prepared Statements

Most performance problems come from the database layer.

typescriptimport pg from 'pg';

// Connection pool (reuse connections)
const pool = new pg.Pool({
    max: 20,  // Max connections
    idleTimeoutMillis: 30000,  // Close idle connections
    connectionTimeoutMillis: 2000,  // Fail fast on connection error
});

// ✅ Use prepared statements to prevent SQL injection
const getUser = async (userId: number) => {
    const query = 'SELECT * FROM users WHERE id = $1';  // $1 is placeholder
    const result = await pool.query(query, [userId]);
    return result.rows[0];
};

// ❌ NEVER do this (SQL injection vulnerability)
const badGetUser = async (userId: number) => {
    const query = `SELECT * FROM users WHERE id = ${userId}`;  // Vulnerable!
    const result = await pool.query(query);
    return result.rows[0];
};

Caching: Strategic & Measured

Caching is a powerful performance tool but needs discipline.

typescriptimport redis from 'redis';

const redisClient = redis.createClient({
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT
});

// Cache wrapper
const cached = (key: string, ttl: number = 3600) => {
    return async (req: Request, res: Response, next: NextFunction) => {
        // Check cache first
        const cached = await redisClient.get(key);
        if (cached) {
            return res.json(JSON.parse(cached));
        }

        // Intercept res.json to cache result
        const originalJson = res.json;
        res.json = function(data) {
            redisClient.setEx(key, ttl, JSON.stringify(data));
            return originalJson.call(this, data);
        };

        next();
    };
};

// Use it
app.get('/api/posts/:id',
    cached(`post:${req.params.id}`, 3600),  // 1 hour
    getPost
);

Cache Invalidation Strategy

typescript// When data changes, invalidate the cache
app.put('/api/posts/:id', async (req, res) => {
    const post = await updatePost(req.params.id, req.body);

    // Invalidate related caches
    await redisClient.del(`post:${req.params.id}`);
    await redisClient.del('posts:list');

    res.json(post);
});

Monitoring & Observability: Know What's Happening

You can't fix what you don't measure.

typescript// Log every request with timing
app.use((req: Request, res: Response, next: NextFunction) => {
    const start = Date.now();

    res.on('finish', () => {
        const duration = Date.now() - start;

        // Log in structured format for parsing
        console.log(JSON.stringify({
            timestamp: new Date().toISOString(),
            method: req.method,
            path: req.path,
            statusCode: res.statusCode,
            duration: `${duration}ms`,
            userId: req.user?.id
        }));

        // Alert on slow requests
        if (duration > 1000) {
            console.warn(`Slow request: ${req.method} ${req.path} took ${duration}ms`);
        }
    });

    next();
});

// Track database query performance
app.use((req, res, next) => {
    req.dbTiming = {
        start: Date.now(),
        queries: []
    };
    next();
});

Rate Limiting: Protect Against Abuse

A single misbehaving client shouldn't take down your service.

typescriptimport rateLimit from 'express-rate-limit';

// General API rate limiter
const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,  // 15 minutes
    max: 100,  // 100 requests per window
    message: 'Too many requests, please try again later',
    standardHeaders: true,  // Return rate limit info in headers
    skip: (req) => {
        // Don't rate limit healthcheck endpoints
        return req.path === '/health';
    }
});

// Strict limiter for auth endpoints
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5,  // Only 5 login attempts
    skipSuccessfulRequests: true  // Reset on successful login
});

app.use('/api/', apiLimiter);
app.post('/api/auth/login', authLimiter, login);

Versioning: Maintain Backwards Compatibility

Never break clients without a transition plan.

typescript// API Versioning via URL path
app.get('/api/v1/users/:id', getUserV1);
app.get('/api/v2/users/:id', getUserV2);

// Or via header
app.get('/api/users/:id', (req, res, next) => {
    const version = req.header('X-API-Version') || '1';

    if (version === '2') {
        return next('route');
    }

    getUserV1(req, res);
});

// Deprecation notice
app.use((req, res, next) => {
    if (req.path.includes('/v1/')) {
        res.set('Deprecation', 'true');
        res.set('Sunset', new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toUTCString());
    }
    next();
});

Testing: Confidence at Scale

typescriptimport supertest from 'supertest';
import { describe, it, expect } from 'vitest';

describe('User API', () => {
    it('creates user with valid data', async () => {
        const res = await supertest(app)
            .post('/api/users')
            .send({
                email: 'test@example.com',
                name: 'Test User',
                password: 'SecurePassword123!'
            });

        expect(res.status).toBe(201);
        expect(res.body).toHaveProperty('id');
        expect(res.body.email).toBe('test@example.com');
    });

    it('rejects invalid input', async () => {
        const res = await supertest(app)
            .post('/api/users')
            .send({
                email: 'invalid-email',
                name: 'X',  // Too short
                password: '123'  // Too weak
            });

        expect(res.status).toBe(400);
        expect(res.body).toHaveProperty('error');
    });
});

Production Checklist

Before shipping:

  • ✅ Input validation on all endpoints
  • ✅ Error handling with appropriate HTTP status codes
  • ✅ Rate limiting on public endpoints
  • ✅ Connection pooling configured
  • ✅ Prepared statements for all queries
  • ✅ Structured logging in place
  • ✅ Health check endpoint /health for load balancers
  • ✅ HTTPS enforced
  • ✅ CORS configured explicitly (not *)
  • ✅ Request timeout set
  • ✅ Tests for critical paths
  • ✅ Monitoring/alerting configured

Scaling Beyond Single Server

When you outgrow a single server:

typescript// Multiple instances behind load balancer
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Create worker for each CPU core
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
} else {
    // Worker process: start Express app
    app.listen(3000);
}

Building scalable APIs is about anticipating problems and building discipline early. Start with these patterns and you'll have a foundation that grows with your business.

Ready to build enterprise APIs? Let's discuss architecture for your specific scale requirements.