Building Scalable APIs with Node.js
Scaling a Node.js API isn't about adding more servers — it starts with architecture, patterns, and the right abstractions.
Architecture Layers
A well-structured API has clear separation of concerns:
src/
├── routes/ # HTTP layer — request parsing, response formatting
├── controllers/ # Business logic orchestration
├── services/ # Core business rules
├── repositories/ # Data access layer
├── middleware/ # Auth, validation, error handling
└── config/ # Environment, database, secrets
Connection Pooling
Never create a new database connection per request:
import mysql from 'mysql2/promise';
const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, waitForConnections: true, connectionLimit: 10, queueLimit: 0,});
export async function query(sql, params) { const [rows] = await pool.execute(sql, params); return rows;}Rate Limiting
Protect your API from abuse:
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, standardHeaders: true, legacyHeaders: false, message: { error: 'Too many requests, please try again later' },});
app.use('/api/', limiter);Caching Strategy
| Data Type | Cache Duration | Strategy |
|---|---|---|
User profiles | 5 minutes | Redis with invalidation |
Blog posts | 2 minutes | HTTP cache-control |
Static assets | 1 year | CDN with immutable headers |
Search results | 30 seconds | In-memory LRU |
Error Handling
Create a consistent error format:
class AppError extends Error { constructor(message, statusCode = 500, isOperational = true) { super(message); this.statusCode = statusCode; this.isOperational = isOperational; }}
// Global error handlerapp.use((err, req, res, next) => { const status = err.statusCode || 500; res.status(status).json({ success: false, message: err.isOperational ? err.message : 'Internal server error', });});Summary
Building a scalable Node.js API requires thoughtful architecture, proper connection management, caching, rate limiting, and consistent error handling. These patterns will serve you from 100 to 100,000 requests per second.
Want more from ScriptHill in Google? Add us as a preferred source



