Node.js API Security, Rate Limiting, Redis and Deployment

Node.js Backend Architecture API Security, Rate Limiting, Redis Caching

Kavya, a backend developer in Madurai, has just launched the API for a small event-ticket booking site: concerts, Carnatic music nights and college fests across Tamil Nadu. Login works, booking works, and she goes to sleep happy. In the morning, the logs are full of the same two lines, repeated from a handful of IP addresses all night long:

POST /api/login     401 Invalid email or password
POST /api/send-otp  200 {"sent":true}

A bot has been guessing passwords and asking for OTPs non-stop. Every OTP is a paid SMS, so the SMS provider's bill has jumped. Two days later, on the morning the tickets for a big concert go on sale, the event page takes several seconds to load because thousands of people are asking the database for the same event details at once. Kavya's code works. What it lacks is protection and planning: who may call which endpoint, how often, which answers can be served from memory, and how the app runs on a real server. That is what this post covers, in four parts: API security, rate limiting, caching with Redis and deployment, all with tested Express 5 code.

Part 1: API Security in Node.js and Express

API security means making sure only the right people can do the right things through your API, that the data they send cannot trick your server, and that the data you send back leaks nothing it should not. A useful picture is a warehouse. It has a gate with a guard (HTTPS and rate limits), identity checks (authentication), access cards that open only some rooms (authorization), rules about what may be carried in (input validation), and cameras with a visitor log (security logging). Your backend is the warehouse, each endpoint is a room, and each request is a visitor.

Many beginners think "nobody will attack my small app". In reality, automated bots scan the internet all day, looking for login forms, OTP endpoints, open admin panels, file uploads and known framework bugs. They do not care how big your site is. Kavya's bot did not choose her because her site was famous; it found an endpoint that answered.

The Common Threats

ThreatWhat it looks like on a ticket siteMain defence
Unauthorized accessA logged-in customer calls GET /api/bookings/1043 and sees someone else's booking, or GET /api/admin/payouts works for anyoneAuthorization checks on every route, including ownership checks
Stolen accounts (brute force, credential stuffing)A bot tries 123456, password, admin123 and leaked email/password pairs against /api/loginRate limiting, strong password hashing, optional 2FA
Data manipulationA request body changes "seats": 2 to "seats": -1000 or "price": 0Server-side validation; never trust prices sent by the client
Injection (SQL, NoSQL)A search box receives x' OR 1=1 -- Parameterised queries and type checks
Information disclosureAn error response says connect ECONNREFUSED 10.0.3.7:3306, revealing a private IP and that you use MySQLGeneric error messages to clients, details only in server logs
Abuse and overloadThousands of OTP requests, scraping every event pageRate limiting (Part 2), caching (Part 3)

Authentication and Authorization: Two Different Layers

Authentication answers "who are you?": the user proves their identity with a password, an OTP or a token. Authorization answers "what are you allowed to do?". They fail in different ways. A site can have perfect login and still let any logged-in customer read any booking, simply because the booking route never checks that booking.userId equals the logged-in user's ID. This kind of bug, called Broken Access Control, sits at the top of the OWASP Top 10 list mentioned later.

Role on the ticket siteCan doMust not do
CustomerBrowse events, book seats, see and cancel own bookingsSee other customers' bookings, change prices
OrganiserCreate and edit own events, see sales for themEdit another organiser's event, see payouts of others
AdminApprove events, issue refundsShould still use a separate, stricter login (and ideally 2FA)

How passwords are hashed with bcrypt, how JWTs are signed and verified, and how the auth and requireRole middleware work are covered step by step in Authentication, Authorization, JWT & Password Hashing Explained, so they are not repeated here. The rule to carry from this post is simple: every route that touches private data needs both checks, and the ownership check belongs in the query itself, such as WHERE id = ? AND user_id = ?.

Input Validation: Never Trust the Request

Treat every request as if it might be written by an attacker, because some will be. The front end's form checks do not protect your API: anyone can send a request with curl, Postman or a script and skip your React form entirely. Validation on the server must check the type (a number is a number, not the string "free"), the range (seats from 1 to 10, not -1000), the format (a 10-digit mobile number, a 6-digit PIN code) and the size (a 10 KB body limit, a maximum string length). Here is a booking route with a size limit and two checks, plus an error handler that hides internal details:

const express = require('express');
const app = express();

app.use(express.json({ limit: '10kb' })); // bigger bodies get 413

app.post('/api/bookings', (req, res) => {
  const { eventId, seats } = req.body ?? {};
  if (!Number.isInteger(eventId) || eventId <= 0) {
    return res.status(400).json({ error: 'eventId must be a positive integer' });
  }
  if (!Number.isInteger(seats) || seats < 1 || seats > 10) {
    return res.status(400).json({ error: 'seats must be an integer from 1 to 10' });
  }
  // The price is read from the database, never from req.body
  res.status(201).json({ bookingId: 501, eventId, seats });
});

app.get('/api/boom', () => { throw new Error('connect ECONNREFUSED 10.0.3.7:3306'); });

// Error handler: full detail in server logs, a generic message for the client
app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status >= 500) console.error('[error]', err.message);
  res.status(status).json({ error: status >= 500 ? 'Something went wrong' : err.message });
});

// Tested with fetch:
// POST {"eventId":7,"seats":2}           -> 201 {"bookingId":501,"eventId":7,"seats":2}
// POST {"eventId":7,"seats":-1000}       -> 400 {"error":"seats must be an integer from 1 to 10"}
// POST a 20 KB body                      -> 413 {"error":"request entity too large"}
// GET /api/boom                          -> 500 {"error":"Something went wrong"}
//   server log: [error] connect ECONNREFUSED 10.0.3.7:3306

For real projects, a schema library such as Joi, Zod or express-validator saves you from writing these if checks by hand, and lets you reuse one schema for create and update. Two details matter more than the library you pick. First, copy only the fields you expect (never spread req.body straight into a database insert, or a client can set role: "admin"). Second, values like price and discount must come from your database, not from the request.

SQL Injection: Unsafe vs Parameterised Queries

SQL injection happens when user input is joined into the text of a SQL query, so the input can change the meaning of the query. It is one of the oldest attacks on the web and still one of the most damaging. The two examples below build queries for the mysql2 driver; they only print the SQL text, so you do not need a database to run them.

// UNSAFE: do not do this. User input is glued into the SQL text.
function unsafeSearch(city) {
  return "SELECT id, name, price FROM events WHERE city = '" + city + "' AND is_published = 1";
}
console.log(unsafeSearch('Madurai'));
// SELECT id, name, price FROM events WHERE city = 'Madurai' AND is_published = 1
console.log(unsafeSearch("x' OR 1=1 -- "));
// SELECT id, name, price FROM events WHERE city = 'x' OR 1=1 -- ' AND is_published = 1

Look at the second query. The quote in the input closes the string early, OR 1=1 makes the condition true for every row, and -- turns the rest of the line into a comment, so AND is_published = 1 is gone. The attacker now sees every event, including unpublished ones. With other inputs (such as UNION SELECT) they could read other tables. The fix is a parameterised query: write a ? where the value goes and pass the values separately.

// SAFE: placeholders. The driver treats the input as a value, never as SQL.
const mysql = require('mysql2/promise');
const pool = mysql.createPool({ /* host, user, password from env variables */ });

async function searchEvents(city) {
  const [rows] = await pool.execute(
    'SELECT id, name, price FROM events WHERE city = ? AND is_published = 1',
    [city]
  );
  return rows;
}

// To see what the escaping does without a database:
const { format } = require('mysql2');
console.log(format('SELECT id, name, price FROM events WHERE city = ? AND is_published = 1', ["x' OR 1=1 -- "]));
// SELECT id, name, price FROM events WHERE city = 'x\' OR 1=1 -- ' AND is_published = 1

The quote is escaped, so the whole input is just a strange city name that matches nothing. pool.execute() goes one step further and sends the values separately from the SQL as a prepared statement; pool.query() with ? escapes them on the client side. Both are safe; string concatenation is not. Two related notes: mysql2 does not run several statements in one call unless you set multipleStatements: true, which is why the classic '; DROP TABLE events; -- usually fails, but the OR 1=1 style shown above still works on unsafe code. And placeholders cannot be used for column names in ORDER BY; for those, check the value against an allow-list such as ['price', 'date']. The MySQL Performance Tuning, Security & Backup post covers database-side protection such as limited user privileges.

NoSQL Injection

MongoDB and other document databases do not use SQL text, but they have their own version of the problem. MongoDB queries are objects, and operators start with $. If your login code passes req.body.email straight into users.findOne({ email, password }), an attacker can send an object instead of a string:

const body = JSON.parse('{"email":{"$ne":null},"password":{"$ne":null}}');
console.log(typeof body.email, body.email); // object { '$ne': null }
// findOne({ email: { $ne: null }, ... }) means "email is not null": it matches a real user

function validateLogin(b) {
  if (typeof b.email !== 'string' || typeof b.password !== 'string') {
    return { ok: false, error: 'email and password must be strings' };
  }
  return { ok: true };
}
console.log(validateLogin(body));
// { ok: false, error: 'email and password must be strings' }
console.log(validateLogin({ email: 'kavya@example.com', password: 'secret' }));
// { ok: true }

A simple type check closes this hole. Schema validation with Joi or Zod does it automatically, and Mongoose casts fields to their schema type. Storing plain passwords in the query is wrong anyway: look the user up by email, then compare the password hash in code.

XSS: Escape on Output

Cross-site scripting (XSS) happens when text from one user is shown to other users as HTML, so a script inside it runs in their browsers. On a ticket site, an organiser might put this in an event description: <img src=x onerror="alert(document.cookie)">. If the page inserts the description with innerHTML, the browser tries to load the image, fails, and runs the attacker's code with the visitor's session. The fix is to escape special characters when you put text into HTML:

function escapeHtml(s) {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
console.log(escapeHtml('<img src=x onerror="alert(document.cookie)">'));
// &lt;img src=x onerror=&quot;alert(document.cookie)&quot;&gt;

Now the browser shows the text instead of running it. In practice, React, Vue, Angular and template engines like EJS (with <%= %>) escape by default; the danger is in the escape hatches: innerHTML, React's dangerouslySetInnerHTML, EJS's <%- %>. If you must allow some formatting, sanitise with a library such as DOMPurify. A JSON API should return data as JSON with Content-Type: application/json, and the Content-Security-Policy header that helmet sets (shown below) is a second safety net that blocks inline scripts.

CSRF: Only When the Browser Sends Credentials for You

Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request to your site from another site. It works only when the browser attaches the credentials automatically, which means cookie-based sessions. If Kavya's front end sends a JWT in the Authorization header from JavaScript, a different site cannot make the browser add that header, so classic CSRF does not apply. If she stores the session in a cookie, she needs protection, and the first layer is the SameSite cookie attribute:

res.cookie('sid', sessionId, {
  httpOnly: true,  // page JavaScript cannot read it, which limits XSS damage
  secure: true,    // only sent over HTTPS
  sameSite: 'lax', // not sent on cross-site POSTs, which blocks classic CSRF
  maxAge: 2 * 60 * 60 * 1000, // 2 hours
});
// Set-Cookie: sid=...; Max-Age=7200; Path=/; Expires=...; HttpOnly; Secure; SameSite=Lax

With SameSite=Lax the cookie still travels when a user clicks a normal link to your site, but not on a POST that another site submits in the background. Strict is tighter but logs users out when they arrive from a link in an email. Never change data with a GET request, because Lax still sends cookies on top-level GET navigation. For stronger protection, add a CSRF token (a random value the page must send back in a header) or check the Origin header on state-changing requests.

HTTPS Everywhere

Without HTTPS, everything between the user and your server travels as plain text. On public Wi-Fi at a bus stand or a college canteen, anyone on the same network with the right tools can read the password or the token. HTTPS (HTTP over TLS) encrypts the connection and proves the server is really yours. Every production API should use HTTPS only, redirect HTTP to HTTPS, and send the Strict-Transport-Security header so browsers refuse plain HTTP next time. Certificates are free from Let's Encrypt; Part 4 shows how to set them up with Nginx.

JWT Secrets and Environment Variables

Two mistakes show up again and again with JWTs. The first is putting private data in the payload. A JWT is signed, not encrypted: anyone can base64-decode the payload and read it. Keep it to IDs and roles, such as { "userId": 101, "role": "organiser" }, never a password, phone number or Aadhaar number. The second is a weak or hard-coded secret. A secret like secret123, or one typed by a person, can be guessed offline from any token, after which an attacker can sign their own admin tokens. Generate it instead:

node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"
# prints a 43-character random string; put it in JWT_SECRET

Secrets belong in environment variables, never in code or Git. A small config.js that reads them once and refuses to start when something is missing turns a confusing runtime bug into a clear start-up error:

// config.js: read every setting once, fail fast if a secret is missing
const required = ['JWT_SECRET', 'DB_PASSWORD'];
const missing = required.filter((name) => !process.env[name]);
if (missing.length) {
  console.error(`Missing environment variables: ${missing.join(', ')}`);
  process.exit(1);
}
if (process.env.JWT_SECRET.length < 32) {
  console.error('JWT_SECRET must be at least 32 characters');
  process.exit(1);
}
module.exports = {
  port: Number(process.env.PORT) || 3000,
  jwtSecret: process.env.JWT_SECRET,
  db: { password: process.env.DB_PASSWORD },
};

// node config.js                                     -> Missing environment variables: JWT_SECRET, DB_PASSWORD (exit code 1)
// JWT_SECRET=secret123 DB_PASSWORD=x node config.js  -> JWT_SECRET must be at least 32 characters (exit code 1)

Also make sure API responses never include fields like password_hash, internal IDs of other users, tokens or database errors. Select only the columns you need instead of SELECT *, and write the response object field by field.

Security Headers with helmet

Browsers understand a set of response headers that switch on extra protection: block the page from being framed by other sites (clickjacking), stop the browser from guessing content types, force HTTPS, and restrict where scripts may load from. The helmet package sets sensible defaults for all of them in one line. These are the headers helmet 8 added to the booking response in our test:

const helmet = require('helmet');
app.use(helmet());
app.disable('x-powered-by'); // helmet also removes it; this is belt and braces

// content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;
//   form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';
//   script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';
//   upgrade-insecure-requests
// strict-transport-security: max-age=31536000; includeSubDomains
// x-content-type-options: nosniff
// x-frame-options: SAMEORIGIN
// referrer-policy: no-referrer
// cross-origin-opener-policy: same-origin
// x-powered-by: null   (Express no longer advertises itself)
HeaderWhat it stops
Content-Security-PolicyScripts from unexpected places, inline scripts injected through XSS
Strict-Transport-SecurityDowngrade to plain HTTP after the first HTTPS visit (here, for 365 days)
X-Content-Type-Options: nosniffThe browser treating an uploaded "image" as a script
X-Frame-Options / frame-ancestorsYour pages being shown inside an invisible iframe on another site
Referrer-PolicyFull URLs (which may contain tokens or IDs) leaking to other sites

Helmet's CSP default matters most for pages that serve HTML. For a pure JSON API it does little harm, and if your admin pages load scripts from a CDN, you will need to add that domain to script-src instead of turning CSP off.

CORS: Wildcard With Credentials vs an Allow-List

CORS (Cross-Origin Resource Sharing) decides which other websites may read your API's responses in a browser. The Express.js Complete Guide explains the basics and the preflight request; here the focus is the security mistake. Two "make the error go away" settings are common, and both are wrong for an API that uses cookies or logged-in users:

// UNSAFE 1: wildcard plus credentials
app.use(cors({ origin: '*', credentials: true }));
// Origin: https://evil.example -> access-control-allow-origin: *   access-control-allow-credentials: true
// Browsers refuse this combination, so logged-in calls from your own front end break too.

// UNSAFE 2: reflect any origin plus credentials (the "fix" people reach for next)
app.use(cors({ origin: true, credentials: true }));
// Origin: https://evil.example -> access-control-allow-origin: https://evil.example
//                                 access-control-allow-credentials: true
// Now ANY website can make logged-in requests and read the answers.

The second one is the dangerous one, because it looks like it works. Use an explicit allow-list instead:

const cors = require('cors');
const ALLOWED_ORIGINS = ['https://tickets.example.com', 'http://localhost:5173'];

app.use(cors({
  origin(origin, cb) {
    // No Origin header = curl, Postman or server-to-server; CORS does not apply to them
    if (!origin || ALLOWED_ORIGINS.includes(origin)) return cb(null, true);
    return cb(null, false); // no CORS headers, so the browser blocks the read
  },
  credentials: true,
}));

// Origin: https://tickets.example.com -> access-control-allow-origin: https://tickets.example.com
//                                        access-control-allow-credentials: true
// Origin: https://evil.example        -> access-control-allow-origin: null (header absent)

Remember what CORS is not. In our test, the request from https://evil.example still reached the route and got a 400 for its bad body; the server just did not send the header that lets a browser read the answer. Curl and scripts ignore CORS completely. So CORS protects your users' browsers; authentication, authorization and rate limits protect your API.

File Uploads

Upload endpoints are a favourite target because they accept large, binary, attacker-chosen content. An organiser's "poster image" could be a 2 GB file, an HTML file with a script, or a file named poster.jpg.exe. The basics: set a size limit, check the real file type (the first bytes, not just the extension or the Content-Type header the client sent), rename files to a random name, store them outside the web root or in object storage such as S3, never execute them, and rate-limit the upload route. The Node.js Error Handling, Logging & File Upload Architecture post builds a full Multer upload with these checks.

Security Logging, Least Privilege and OWASP

Log security events, not just errors: failed logins (with email and IP, never the password), password resets, OTP requests, 403 responses, rate-limit blocks, and admin actions such as refunds. With these logs Kavya could see the bot within minutes instead of the next morning. Send them to a central place with alerts on spikes; the Error Handling post linked above shows structured logging with levels.

The principle of least privilege says every user, service and key gets only the access it needs. A customer cannot reach organiser routes. The Node.js app connects to MySQL with a user that can SELECT, INSERT and UPDATE its own tables but not DROP them. An S3 key for uploads can write to one bucket only. When something leaks, least privilege decides how bad the damage is.

The OWASP Top 10 is a regularly updated list of the most common web application risks, published by the Open Worldwide Application Security Project. Its categories include Broken Access Control, Injection, Security Misconfiguration, cryptographic failures, authentication failures, and risks from outdated or compromised third-party packages; check the current edition for the exact names and order. Reading it once and checking your API against each item is one of the best hours a backend developer can spend. A layered request flow puts all of this together:

Request
  → HTTPS (Nginx or load balancer terminates TLS)
  → rate limiter          (Part 2)
  → helmet headers, CORS allow-list
  → body size limit, JSON parsing
  → authentication        (who are you?)
  → authorization         (may you do this, on this record?)
  → input validation
  → controller → service → database (parameterised queries, least-privilege DB user)
  → response (only the fields the client needs; generic errors)

Part 2: Rate Limiting and API Protection

Rate limiting restricts how many requests a client may make in a period of time. Think of a toll plaza on a highway. A few cars a minute pass smoothly. If a huge number arrive at once, the plaza meters them through the lanes so the road behind does not jam. Rate limiting is that plaza for your API: normal users never notice it, but one client cannot send thousands of requests and slow down or bankrupt everyone else.

Abuse Scenarios Rate Limiting Helps With

  • Brute-force login: a bot tries thousands of passwords for one account, or one common password across thousands of accounts (credential stuffing). A limit of a few attempts per 15 minutes makes this impractically slow.
  • OTP abuse: every POST /api/send-otp costs real money for the SMS, and attackers sometimes use your OTP endpoint to flood a victim's phone ("SMS bombing"). This is exactly what hit Kavya.
  • Scraping: a bot walks /api/events?page=1, page=2, page=3 to copy your whole catalogue or watch prices. Limits slow it down and make it visible in logs.
  • Accidental overload: a buggy mobile app release that retries in a tight loop can look exactly like an attack.
  • DDoS (distributed denial of service): a large number of machines flood your server at once. Rate limiting alone does not stop a DDoS: by the time the request reaches your Node.js process, it has already used network bandwidth and a connection, and with enough machines each one stays under your per-IP limit. Real DDoS protection happens in front of your server, at a CDN or a cloud provider's edge (for example AWS Shield with CloudFront, or Cloudflare). Application-level limits are one layer, not the shield.

How Rate-Limiting Algorithms Work

Every limiter tracks three things: who is calling (the key, usually the IP address or user ID), how many requests they made, and when. The algorithms differ in how they count time:

AlgorithmHow it countsStrengthWeakness
Fixed windowA counter per key that resets at the end of each window (for example, every 15 minutes)Very simple and cheap; one counter per key (this is what express-rate-limit's built-in store does)A burst at the edge of two windows can allow nearly double the limit in a short time
Sliding windowCounts requests in the last N minutes from "now", either by keeping timestamps (log) or by weighting the previous window (counter)Smooth and fair; no edge burstMore memory (log) or slightly approximate (counter)
Token bucketA bucket refills at a steady rate (say 1 token per second, up to 10); each request takes a tokenAllows short bursts but limits the long-run rate; good for public APIsTwo numbers to tune (refill rate and bucket size)

A related idea, the leaky bucket, processes requests at a fixed rate and queues or drops the rest; Nginx's limit_req works this way. For most Express apps, the fixed window of express-rate-limit is enough, as long as the limits are sensible.

express-rate-limit: A Login Limiter With a Real 429

Install it with npm install express-rate-limit. The option names changed over the versions, so older tutorials (including the original version of this post) use max. In version 7 and later the option is limit; max still works as an alias, but new code should use limit. This test used Express 5.3 and express-rate-limit 8.7:

const express = require('express');
const { rateLimit, ipKeyGenerator } = require('express-rate-limit');

const app = express();
app.use(express.json());

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,   // 15 minutes
  limit: 5,                   // 5 attempts per window per IP (called "max" before v7)
  standardHeaders: 'draft-8', // send the standard RateLimit and RateLimit-Policy headers
  legacyHeaders: false,       // do not send the old X-RateLimit-* headers
  handler(req, res, next, options) {
    console.warn(`[rate-limit] login blocked ip=${req.ip}`); // security log
    res.status(options.statusCode).json({
      error: 'Too many login attempts. Please try again later.',
    });
  },
});

app.post('/api/login', loginLimiter, (req, res) =>
  res.status(401).json({ error: 'Invalid email or password' })); // stand-in for the real check

The test script started the server on port 3153 and sent six wrong logins with fetch:

login #1: 401 "5-in-15min"; r=4; t=900 {"error":"Invalid email or password"}
login #2: 401 "5-in-15min"; r=3; t=900 {"error":"Invalid email or password"}
login #3: 401 "5-in-15min"; r=2; t=900 {"error":"Invalid email or password"}
login #4: 401 "5-in-15min"; r=1; t=900 {"error":"Invalid email or password"}
login #5: 401 "5-in-15min"; r=0; t=900 {"error":"Invalid email or password"}
[rate-limit] login blocked ip=::1
login #6: 429 "5-in-15min"; r=0; t=900 {"error":"Too many login attempts. Please try again later."}

// Headers on a blocked response:
// ratelimit-policy: "5-in-15min"; q=5; w=900; pk=:YmIwY2Q1MTM2YWU1:
// retry-after: 900
// x-ratelimit-limit: null   (legacy headers switched off)

The middle column is the RateLimit header in the IETF draft-8 format: the policy name, r (requests remaining) and t (seconds until the window resets). RateLimit-Policy describes the rule: quota q=5 per window w=900 seconds, plus a hashed partition key pk. Choose 'draft-7' instead if your clients expect the older combined format. Most important for clients is the status 429 Too Many Requests with a Retry-After header, which express-rate-limit adds automatically when the limit is hit. A well-behaved mobile app reads Retry-After and waits instead of retrying at once. If you only need a message, the message option (a string or an object, sent as JSON) is simpler than a custom handler; use the handler when you also want to log, as above.

For login specifically, the option skipSuccessfulRequests: true counts only failed attempts, so a user who logs in correctly is not punished for logging in several times from a shared office IP.

Different Limits for Different Endpoints

One global number for every route is either too strict for browsing or too loose for login. Set limits by risk and cost. The numbers below are starting points to tune against your own traffic, not rules:

EndpointExample limitKeyWhy
POST /api/login5 failed attempts / 15 minIP, plus a second limiter per emailBrute force and credential stuffing
POST /api/send-otp3 / 10 minPhone number, plus IPEach OTP is a paid SMS; SMS bombing
POST /api/password-reset3 / hourEmail, plus IPInbox spam and account probing
POST /api/payments10 / hourUser IDCard testing (bots trying stolen cards), duplicate charges
POST /api/uploads20 / hourUser IDStorage and bandwidth cost
GET /api/eventsGenerous, such as 300 / 15 minIPScraping, while normal browsing stays smooth
Everything elseA global safety netIPCatches runaway clients and buggy apps

Apply a limiter to one route by putting it before the handler, as with loginLimiter above, or to a group with app.use('/api/auth', authLimiter). A request can pass through several limiters (the global one and the route one), and the strictest one decides.

IP-Based vs User-Based Keys

By default the key is the client's IP address. That is the only option before login, but it has weaknesses: many users can share one IP (a college hostel, an office, or a mobile network that puts many phones behind one address), and one attacker can rotate through many IPs. For logged-in routes, key by user ID; for OTP, key by the phone number being targeted. Kavya's OTP limiter does exactly that:

const otpLimiter = rateLimit({
  windowMs: 10 * 60 * 1000,
  limit: 3,
  standardHeaders: 'draft-8',
  legacyHeaders: false,
  // One bucket per phone number, so rotating IPs does not help the bot
  keyGenerator: (req) => req.body?.phone || ipKeyGenerator(req.ip),
  message: { error: 'Too many OTP requests for this number. Try again in 10 minutes.' },
});
app.post('/api/send-otp', otpLimiter, (req, res) => res.json({ sent: true }));

// otp #1: 200 {"sent":true}
// otp #2: 200 {"sent":true}
// otp #3: 200 {"sent":true}
// otp #4: 429 {"error":"Too many OTP requests for this number. Try again in 10 minutes."}
// other number: 200 {"sent":true}

Two details. When you fall back to the IP in a custom key, wrap it in ipKeyGenerator(): version 8 groups IPv6 addresses by subnet (a single user often controls a whole block of IPv6 addresses) and warns if you use a raw req.ip. And normalise the phone number (strip spaces, add the +91 country code) before using it as a key, or 98000 00001 and +919800000001 become two separate buckets. Because the limiter reads req.body, express.json() must run before it.

Kavya's fix, part one: she adds the login limiter (5 failed attempts per 15 minutes per IP) and the OTP limiter keyed by phone number. The bot's next OTP burst gets 429 after the third request for each number, her logs show the blocked IPs, and the SMS bill stops growing. Real users who mistype a password once or twice never see the limit.

trust proxy: Why Getting It Wrong Is Dangerous

In production, your Node.js app usually sits behind Nginx or a cloud load balancer. Then every TCP connection comes from the proxy, and the real visitor's IP arrives only in the X-Forwarded-For header that the proxy adds. Express decides whether to believe that header through the trust proxy setting, and both wrong choices break rate limiting. We tested three settings with a limit of 3 requests per minute, sending X-Forwarded-For headers the way a proxy would:

// A. trust proxy not set (default), four DIFFERENT real users behind Nginx:
// 200 ::1 | 200 ::1 | 200 ::1 | 429
//   req.ip is the proxy's address for everyone, so all users share ONE bucket.
//   express-rate-limit also logs: ValidationError ... ERR_ERL_UNEXPECTED_X_FORWARDED_FOR

// B. app.set('trust proxy', true), ONE attacker sending a fake X-Forwarded-For each time:
// 200 1.1.1.1 | 200 2.2.2.2 | 200 3.3.3.3 | 200 4.4.4.4 | 200 5.5.5.5
//   Express believes whatever the client wrote, so every request gets a new bucket: never limited.
//   express-rate-limit logs: ERR_ERL_PERMISSIVE_TRUST_PROXY

// C. app.set('trust proxy', 1), same attacker; Nginx appends the real IP 49.36.9.9:
//   X-Forwarded-For: "1.1.1.1, 49.36.9.9"
// 200 49.36.9.9 | 200 49.36.9.9 | 200 49.36.9.9 | 429 | 429
//   Express trusts exactly one hop (your proxy) and takes the address that proxy added.

Setting A is the "my whole site got locked out at once" bug: on a busy day, the first few users use up the limit for everybody. Setting B is worse because it fails silently in the attacker's favour: any limiter, IP ban or audit log based on req.ip can be bypassed by sending one made-up header. The right value is the number of proxies you control between the internet and Node.js: app.set('trust proxy', 1) for one Nginx or one load balancer, 2 for a CDN plus a load balancer. You can also give the proxy's IP ranges instead of a number. Check it once after deployment with a temporary route that returns req.ip.

Multiple Instances Need a Shared Store (Redis)

express-rate-limit keeps its counters in the memory of the Node.js process by default. That is fine for one process. As soon as you run several, such as PM2 cluster mode on a 4-core server or two servers behind a load balancer, each process has its own counters. With 4 processes and a login limit of 5, an attacker whose requests are spread across them gets up to 20 attempts, and every restart or deploy resets the counts to zero. The fix is a shared store, and Redis is the usual choice because it can increment a counter and set its expiry in one fast operation. With the rate-limit-redis package (this code needs a running Redis server; it was syntax-checked, not run):

// Needs a running Redis server (REDIS_URL, for example redis://localhost:6379)
const express = require('express');
const { rateLimit } = require('express-rate-limit');
const { RedisStore } = require('rate-limit-redis');
const { createClient } = require('redis');

const app = express();
const redis = createClient({ url: process.env.REDIS_URL });

async function main() {
  await redis.connect(); // connect before creating the store

  const loginLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    limit: 5,
    standardHeaders: 'draft-8',
    legacyHeaders: false,
    store: new RedisStore({
      prefix: 'rl:login:',
      sendCommand: (...args) => redis.sendCommand(args),
    }),
  });

  app.post('/api/login', loginLimiter, loginController);
  app.listen(3000);
}
main();

Now every process shares one counter per key, and counts survive restarts. Logging blocked requests (the handler above) and watching them on a dashboard tells you when a limit is too strict for real users, or when an attack is in progress. Nginx, CloudFront, AWS WAF or an API gateway can also rate-limit before traffic reaches Node.js, which saves your server the work; keep the application limits too, because only the app knows things like "this is the same phone number".

Part 3: Caching and Redis

Back to Kavya's sale morning. Thousands of people open the same concert page. Each request runs the same database query for the same event details, which change maybe once a week. The database does the same work again and again, its CPU climbs, and every page waits in line. Caching means keeping a copy of data that is expensive to fetch in a faster place, so most requests skip the slow work. Think of an office clerk who keeps the few files used every day on the desk instead of walking to the archive room each time. The archive room is the database; the desk is the cache.

Cache Hits, Misses and the Cache-Aside Pattern

A cache hit means the data was in the cache, so you return it without touching the database. A cache miss means it was not, so you query the database, store the result in the cache, and return it. The most common way to organise this is the cache-aside pattern (also called lazy loading): the application checks the cache first, and fills it only on a miss. Each cached item gets a TTL (time to live) so it disappears automatically after a while and cannot stay stale forever.

GET /api/events/7
  → look in cache for "event:7:details"
      found?  yes → return it                          (hit)
              no  → query MySQL → save in cache with TTL → return it   (miss)

Redis is not installed on the machine used for this post, so the example below uses a small in-memory cache with TTL that behaves the same way and runs anywhere. The fake database counts how often it is asked. The Redis version follows right after.

// A tiny cache with TTL, standing in for Redis so this runs anywhere
class TtlCache {
  #store = new Map();
  hits = 0;
  misses = 0;

  get(key) {
    const entry = this.#store.get(key);
    if (!entry || entry.expiresAt <= Date.now()) {
      this.#store.delete(key);
      this.misses++;
      return null;
    }
    this.hits++;
    return entry.value;
  }
  set(key, value, ttlSeconds) {
    this.#store.set(key, { value, expiresAt: Date.now() + ttlSeconds * 1000 });
  }
  del(key) {
    this.#store.delete(key);
  }
}

// Fake database that counts its queries
let dbQueries = 0;
const eventsTable = new Map([[7, { id: 7, name: 'Carnatic Night', city: 'Madurai', price: 499 }]]);
const db = {
  async findEvent(id) {
    dbQueries++;
    await new Promise((r) => setTimeout(r, 30)); // pretend the query takes time
    const row = eventsTable.get(id);
    return row ? { ...row } : null;
  },
  async updatePrice(id, price) {
    dbQueries++;
    eventsTable.get(id).price = price;
  },
};

const cache = new TtlCache();
const eventKey = (id) => `event:${id}:details`;

// Cache-aside read
async function getEvent(id) {
  const cached = cache.get(eventKey(id));
  if (cached) return { source: 'cache', event: JSON.parse(cached) };
  const event = await db.findEvent(id);
  if (event) cache.set(eventKey(id), JSON.stringify(event), 60); // 60-second TTL
  return { source: 'db', event };
}

// Write: update the database first, then delete the cached copy
async function updateEventPrice(id, price) {
  await db.updatePrice(id, price);
  cache.del(eventKey(id));
}

(async () => {
  console.log(await getEvent(7));
  // { source: 'db', event: { id: 7, name: 'Carnatic Night', city: 'Madurai', price: 499 } }
  console.log((await getEvent(7)).source); // cache
  console.log((await getEvent(7)).source); // cache
  await updateEventPrice(7, 599);
  console.log(await getEvent(7));
  // { source: 'db', event: { id: 7, name: 'Carnatic Night', city: 'Madurai', price: 599 } }
  console.log((await getEvent(7)).source); // cache

  const ratio = cache.hits / (cache.hits + cache.misses);
  console.log({ hits: cache.hits, misses: cache.misses, hitRatio: ratio.toFixed(2), dbQueries });
  // { hits: 3, misses: 2, hitRatio: '0.60', dbQueries: 3 }

  cache.set('demo', 'x', 0.05);   // 50 ms TTL
  console.log(cache.get('demo')); // x
  await new Promise((r) => setTimeout(r, 80));
  console.log(cache.get('demo')); // null (expired)
})();

Five reads cost only two database reads (plus one write), and the price change showed up immediately because the update deleted the cached copy. In a real sale, where the same event page is read thousands of times between changes, the share of requests that reach the database becomes very small. This in-memory version is fine inside one process, but each process has its own copy and it is lost on restart, which is why production apps use Redis.

The Same Pattern With Redis (node-redis v4+)

Redis (REmote DIctionary Server) is an in-memory data store: it keeps data in RAM, so reads and writes are very fast, and every app server can share it over the network. Install the client with npm install redis. The code below needs a running Redis server; it was syntax-checked with redis 6.3 (the current major version of the package), not run against a server.

// Needs a running Redis server (REDIS_URL, for example redis://localhost:6379)
const { createClient } = require('redis');

const redis = createClient({ url: process.env.REDIS_URL });
redis.on('error', (err) => console.error('[redis]', err.message));

async function getEvent(id) {
  const key = `event:${id}:details`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached); // hit

  const event = await db.findEvent(id); // miss: ask MySQL
  if (event) await redis.set(key, JSON.stringify(event), { EX: 60 }); // expires in 60 s
  return event;
}

async function updateEventPrice(id, price) {
  await db.updatePrice(id, price);
  await redis.del(`event:${id}:details`); // invalidate after the write
}

async function main() {
  await redis.connect(); // since v4, the client must connect before any command
  // ... then start Express
}
main();

Older tutorials use client.setEx(key, 3600, value), which still works. set(key, value, { EX: 60 }) is the same thing as an option. In node-redis v5 and later, EX is marked as deprecated in favour of { expiration: { type: 'EX', value: 60 } }, but both forms work. Always attach the 'error' listener: without it, a dropped Redis connection raises an unhandled 'error' event that crashes the process.

Naming Cache Keys

Good keys are predictable, so the code that writes data knows exactly which key to delete. The common convention is colon-separated parts from general to specific: event:7:details, event:7:seats, city:madurai:events:page:1, user:101:profile, rl:login:49.36.9.9. Put a version in the key (v2:event:7:details) when you change the shape of the cached object, so new code never reads old shapes. Keep keys short and never put secrets or full tokens in them, because keys show up in monitoring tools.

Invalidation: Keeping the Cache Honest

TTL alone means users can see old data until the key expires. If an organiser changes the price from ₹499 to ₹599 and the cache keeps ₹499 for an hour, customers see the wrong price. So on every update: write to the database first, then delete the cache key, as updateEventPrice does. The next read is a miss and loads the fresh value. Deleting is safer than writing the new value into the cache, because two updates racing each other can leave the older value in the cache, while a delete just forces a fresh read. Keep the TTL anyway as a safety net for any update path that forgets to delete. Lists are harder: when one event changes, the cached pages of city:madurai:events that contain it are also stale, so either delete those keys too or give list caches a short TTL.

One more risk on a sale morning is the cache stampede: a popular key expires and hundreds of requests miss at the same moment, all hitting the database together. Common fixes are adding a little random jitter to TTLs so keys do not expire together, and letting only one request rebuild a key (a short lock with SET key value NX EX 5) while others wait briefly or use the old value.

What Not to Cache

Good candidatesCache with careDo not cache
Event details, venue info, categories, city lists, organiser public profiles, popular search resultsPer-user data such as "my bookings": key it by user ID (user:101:bookings), never by URL alone, and delete on change. A cache key without the user ID can show one user's bookings to another.Seats left for a live sale, payment status, OTPs (except as short-lived values with their own TTL), anything where a stale value causes a wrong booking or a wrong charge

For a fast-changing number like seats remaining, read it from the database (or keep it in Redis as the single source of truth with atomic DECR, which is a design decision, not a cache). The booking itself must always be checked against the database inside a transaction, even if the page showed a cached count.

Redis Data Structures

Redis is more than a key-value string store. Picking the right structure often removes code from your app:

StructureWhat it holdsExample on the ticket site
StringText, JSON or a number; supports INCR and TTLCached event JSON; rate-limit counters; OTP with a 5-minute TTL
HashA small object with fieldsSession data session:abc with userId, role
ListAn ordered list, push and pop at both endsA simple job queue for confirmation emails; recent activity feed
SetUnique members, no orderIDs of users who saved an event; blocked IPs
Sorted setUnique members with a score, kept in order"Trending events" ranked by bookings; a sliding-window rate limiter using timestamps as scores

Sessions and Rate Limiting in Redis

If you use cookie sessions with express-session, its default store is in process memory: sessions vanish on every restart and are not shared between servers, so a user logged in on server A looks logged out on server B. A Redis store (the connect-redis package) fixes both, and each session expires on its own TTL. Rate-limit counters, as shown in Part 2, are another perfect fit: INCR plus EXPIRE is exactly a fixed-window counter, and all servers see the same count. One Redis instance often serves caching, sessions and rate limiting together, separated by key prefixes.

Monitoring the Hit Ratio

The hit ratio is hits divided by (hits + misses). If it is low, the cache is costing memory without saving much work: maybe TTLs are too short, keys include something that changes on every request (like a timestamp), or you are caching data nobody reads twice. Redis reports totals in INFO stats as keyspace_hits and keyspace_misses; to see the ratio per feature, count hits and misses in your own code as TtlCache does. Also watch memory use and evictions (evicted_keys), and set maxmemory with an eviction policy such as allkeys-lru for a pure cache, so Redis drops the least recently used keys instead of failing when it fills up. A cache is a copy, never the only home of data that matters: the database must always be able to rebuild it.

Kavya's fix, part two: the event details endpoint now uses cache-aside with a 60-second TTL and deletes the key whenever the organiser edits the event. On the next sale morning, nearly all event-page reads are cache hits, the database handles bookings instead of repeated reads, and the "seats left" number is still read live, so nobody books a seat that is already gone.

Part 4: Deployment, From Laptop to the Real World

An API running on localhost:3000 is not a product: nobody else can reach it, and it stops when the laptop sleeps. Deployment moves it to a server that runs all the time, at a domain name, over HTTPS, with restarts, logs and updates handled safely. A restaurant comparison helps: development is the test kitchen where mistakes are private; production is service time, where every slow dish is noticed.

Development vs Production

DevelopmentProduction
Addresshttp://localhost:3000https://api.example.com
NODE_ENVdevelopmentproduction (Express and many libraries then skip debug work and hide stack traces)
SecretsA local .env file, never committedServer environment variables or a secrets manager
ErrorsFull stack traces in the response are handyGeneric messages to clients, details in logs
DataSmall test data, can be resetReal customers' data, backed up and protected
Processnode --watch or nodemon, restarts on file changeA process manager that restarts on crash and on reboot

VPS vs Cloud

A VPS (virtual private server) is a rented virtual machine with a fixed size, from providers such as DigitalOcean, Linode (now part of Akamai) or Vultr. You get root access and install everything yourself: Node.js, MySQL, Redis, Nginx. It is simple, predictable and a great way to learn, and one VPS can run a small app entirely. A cloud platform such as AWS, Microsoft Azure or Google Cloud offers the same virtual machines plus managed services (databases, storage, load balancers, CDNs) that you can add and scale as needed, at the cost of more concepts to learn. Many projects start on a single VPS or a single cloud VM and move pieces to managed services as they grow. The AWS services most backend developers meet first are:

AWS serviceWhat it isUse on the ticket site
EC2Virtual serversRun the Node.js API (and Nginx)
RDSManaged relational databases (MySQL, PostgreSQL, MariaDB and others) with automated backups and patchingThe MySQL database, without managing the database server yourself
S3Object storage for filesEvent posters, ticket PDFs, invoices
CloudFrontCDN: caches content at edge locations near usersServe posters and the front end quickly across India; absorb traffic spikes
Route 53DNS servicePoint api.example.com at the load balancer or server
ElastiCacheManaged Redis-compatible cacheCaching, sessions, rate-limit counters

AWS's Mumbai region is ap-south-1, and keeping the server and database close to Indian users reduces network delay. Pricing varies by region and changes over time, so check the provider's own calculator rather than any number in a blog post.

Domain, DNS and HTTPS Certificates

A domain is the name users type, and DNS (the Domain Name System) is the internet's phone book that turns it into the server's IP address. You buy the domain from a registrar, then create DNS records: an A record pointing api.example.com to the server's IP, or a CNAME/alias pointing to a load balancer's name. Changes can take some time to spread because resolvers cache answers for the record's TTL. The Backend Development Explained post walks through a DNS lookup step by step.

For HTTPS you need a TLS certificate for the domain. Let's Encrypt issues them free, and its certbot tool can configure Nginx for you with sudo certbot --nginx -d api.example.com; its certificates are short-lived (90 days at the time of writing, and Let's Encrypt has announced plans to shorten that), so certbot sets up automatic renewal. On AWS, AWS Certificate Manager issues free certificates for load balancers and CloudFront. Modern browsers no longer show a big padlock as a "secure" badge, but they do warn loudly about plain HTTP pages with forms, which is another reason to use HTTPS everywhere.

Environment Variables in Production

On the server, set variables such as NODE_ENV=production, PORT, JWT_SECRET, DB_HOST, DB_PASSWORD and REDIS_URL outside the code: in the PM2 ecosystem file kept only on the server, in a systemd unit, or in a secrets manager such as AWS Secrets Manager or SSM Parameter Store. Node.js 20.6 and later can read a file directly with node --env-file=.env src/server.js. Keep a .env.example with the names but no values in Git, use different secrets for development and production, and the fail-fast config.js from Part 1 will stop a deploy that forgot one.

A Process Manager: PM2

If you start the app with node server.js over SSH, it stops when you log out, when it crashes, and when the server reboots. A process manager keeps it running. PM2 is the common choice for Node.js:

npm install -g pm2

pm2 start src/server.js --name tickets-api -i max   # cluster mode: one process per CPU core
pm2 list                  # status, restarts, memory of each process
pm2 logs tickets-api      # live logs
pm2 reload tickets-api    # zero-downtime restart after a deploy (cluster mode)
pm2 save                  # remember the current process list
pm2 startup               # print the command that starts PM2 on boot

PM2 is like a backup generator in a mall: when the app crashes, it starts it again within a moment. But a restart is not a fix; if the app crashes in a loop, the logs tell you why. Cluster mode (-i max) runs several processes to use all CPU cores, which is exactly when the in-memory rate limiter and cache stop being shared and Redis becomes necessary. In Docker or Kubernetes setups, the container platform restarts the process instead, so PM2 is often not used there.

Nginx as a Reverse Proxy

A reverse proxy sits in front of your app: it receives requests on ports 80 and 443, handles HTTPS, and forwards them to Node.js on a private port. Nginx is the usual choice; it also serves static files efficiently, can compress responses, limit request sizes and rate-limit at the edge. A minimal config (in /etc/nginx/sites-available/tickets-api, before certbot adds the HTTPS parts):

server {
    listen 80;
    server_name api.example.com;

    client_max_body_size 5m;          # reject huge uploads before they reach Node.js

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

$proxy_add_x_forwarded_for appends the real client IP to whatever X-Forwarded-For the client sent, which is exactly the "1.1.1.1, 49.36.9.9" case from Part 2, and why app.set('trust proxy', 1) is the matching Express setting. Bind Node.js to 127.0.0.1 or block port 3000 in the firewall so nobody can skip Nginx. Test the config with sudo nginx -t before sudo systemctl reload nginx.

Kavya's deployment callback: on her new server she runs the API with pm2 start ... -i max behind Nginx. On the first day, a friend testing from a hostel Wi-Fi reports a 429 after just a few logins, and her logs show every request coming from 127.0.0.1: trust proxy was not set, so all users shared one bucket. She adds app.set('trust proxy', 1), moves the limiter store and cache to Redis so all PM2 processes share them, and checks req.ip with a temporary route before removing it.

Logging and Monitoring

Deployment is the starting line, not the finish. In production you cannot attach a debugger, so logs and metrics are your eyes. Write structured logs (JSON lines with a level, timestamp, request ID, route, status and duration), send them to a central service such as CloudWatch Logs, Grafana Loki or the ELK stack, and rotate files on disk (pm2 install pm2-logrotate). Then monitor a few signals with alerts: error rate (5xx responses), response time per route (watch the slow tail, such as the 95th percentile, not just the average), CPU and memory, database connections and slow queries, Redis memory and hit ratio, and the number of 429 responses. Add a GET /health route that checks the database and Redis, for uptime monitors and load balancers. The aim is to learn that something is slow from an alert before customers tell you.

CI/CD With GitHub Actions

Manual deployment (zip the code, upload it, restart, hope) is slow and easy to get wrong. CI (continuous integration) runs your tests automatically on every push; CD (continuous delivery or deployment) ships the tested code to the server automatically or with one click. GitHub Actions, GitLab CI/CD and Jenkins are common tools. A minimal GitHub Actions workflow in .github/workflows/deploy.yml that tests every push to main and, only if the tests pass, deploys over SSH:

name: Test and deploy

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: npm
      - run: npm ci
      - run: npm test

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: Deploy over SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SERVER_SSH_KEY }}
          script: |
            cd /var/www/tickets-api
            git pull --ff-only
            npm ci --omit=dev
            pm2 reload tickets-api

needs: test is the important line: a failing test blocks the deploy. The server address and SSH key live in the repository's encrypted secrets, never in the file. npm ci installs exactly what package-lock.json says, and pm2 reload restarts processes one at a time so the API stays up. As the team grows, add a staging server that gets every change first, and database migrations as a separate, reviewed step.

High Availability and Scaling

High availability means the service keeps working when one part fails. With one server, a crash, a full disk or a provider outage takes the whole site down. With two or more app servers behind a load balancer (in different availability zones, which are separate data centres in the same region), the load balancer's health checks stop sending traffic to a broken server. The database needs the same thinking: managed services such as RDS offer a standby copy in another zone that takes over automatically, plus automated backups that you should test restoring.

Vertical scaling (scale up)Horizontal scaling (scale out)
WhatA bigger server: more CPU and RAMMore servers sharing the load
EffortEasiest: often a resize and a restartThe app must be stateless: sessions, rate-limit counters and cache in Redis, files in S3, not on local disk or in memory
LimitsThere is a largest machine, and one server is still one point of failureCan keep adding servers; also gives high availability
Good forThe first growth step; databases often scale up firstStateless API servers behind a load balancer

Put together, a typical growing setup looks like this. You do not need all of it on day one, but every piece in this post has a place in it:

Users (browser, mobile app)
  → Route 53 (DNS)
  → CloudFront (CDN, static files, edge protection)
  → Load balancer (HTTPS, health checks)
  → 2+ Node.js servers (Nginx or ALB in front, PM2 or containers, trust proxy set)
       ├─ Redis (cache, sessions, rate-limit counters)
       ├─ MySQL on RDS (primary + standby, automated backups)
       └─ S3 (posters, ticket PDFs)
  → Logs, metrics and alerts for everything above

Deployment best practices in short: HTTPS only; secrets in environment variables; NODE_ENV=production; a process manager; Nginx or a load balancer in front, with the right trust proxy; automated tests and deploys; database backups that you have actually restored once; logs and alerts; and a stateless app so you can add a second server the day you need it.

Common Mistakes (and the Fix)

MistakeWhat happensFix
Building SQL with string concatenationx' OR 1=1 -- returns every row, including private onesParameterised queries with ?; allow-list column names for sorting
cors({ origin: true, credentials: true })Any website can make logged-in requests and read the answersAn explicit allow-list of your own front-end origins
Hard-coded or human-typed JWT_SECRETSecret leaks via Git or is guessed; attackers sign their own tokens32+ random bytes from crypto.randomBytes, in an environment variable, checked at start-up
Wrong trust proxy behind NginxNot set: all users share one rate-limit bucket. true: attackers bypass limits with a fake headerapp.set('trust proxy', 1) (the number of proxies you control), then verify req.ip
In-memory limiter or cache with several processesLimits multiplied by the number of processes; cache not shared; everything reset on deployRedis store for rate limits, sessions and cache
Caching without invalidation, or per-user data under a shared keyOld prices shown; one user sees another user's bookingsDelete the key after every write; include the user ID in per-user keys; keep a TTL

My Opinion

Add helmet, an allow-list CORS config, a body limit and a login limiter on day one. Together they are about twenty lines, they block the attacks bots try first, and adding them after launch means doing it in a hurry after something has already gone wrong.

Put a dedicated limiter on every endpoint that costs money. OTP, email, payments and uploads cost you something per call. Key them by the thing being abused (phone number, email, user ID), not only by IP, and log every block.

Set trust proxy deliberately and test it. It is one line, but getting it wrong silently breaks rate limiting, IP logs and any IP-based ban. Never use true in production.

Cache only what you have measured as hot, and delete on write. Start with a few read-heavy, rarely changing endpoints and a short TTL. Caching everything early brings stale-data bugs that are harder to find than a slow query.

Start deployment simple, but stateless. One server with Nginx, PM2, HTTPS and automated deploys is enough for many projects. What matters is keeping sessions, counters and files out of process memory and local disk, so adding a second server later is a configuration change, not a rewrite.

Try It Yourself

Answer these first, then check. For question 4, run the trust proxy experiment yourself with two small Express apps and fetch.

1. A route runs: "SELECT * FROM bookings WHERE id = " + req.params.id
   Name two problems with it and rewrite it safely for a logged-in user.
2. Your API uses a JWT in the Authorization header, not cookies. Do you need CSRF tokens? Why?
3. Assign a limit and a key (IP, user ID, phone or email) to each endpoint:
   login, send-otp, password reset, payments, event search.
4. Your app runs behind one Nginx server. What does req.ip show with trust proxy
   (a) not set, (b) true, (c) 1? Which one is safe?
5. Why does a login limit of 5 per 15 minutes allow about 20 attempts when the app
   runs as 4 PM2 processes, and how do you fix it?
6. For each item decide: cache or not, and a TTL if yes.
   event details, list of categories, seats left during a live sale,
   a user's own bookings, payment status.
7. An organiser changes an event's price but customers still see the old one.
   What did the code forget, and in what order should it do the two steps?
8. Design a deployment for the ticket API that survives one server failing.
   Which parts must move out of the Node.js process first?
Show answers
1. It is open to SQL injection, and it has no ownership check (any user can read any
   booking by changing the ID). Safe version:
   pool.execute('SELECT id, event_id, seats FROM bookings WHERE id = ? AND user_id = ?',
                [Number(req.params.id), req.user.id])
2. Not classic CSRF tokens: another site cannot make the browser add your Authorization
   header. CSRF matters when the browser sends credentials automatically (cookies).
   You still need XSS protection, because a script on your own page can read the token.
3. One reasonable answer: login 5 failed / 15 min by IP (plus per email); send-otp
   3 / 10 min by phone number; password reset 3 / hour by email; payments 10 / hour by
   user ID; event search a generous limit by IP.
4. (a) the proxy's address (127.0.0.1) for everyone, so all users share one bucket;
   (b) whatever the client wrote in X-Forwarded-For, so it can be faked;
   (c) the address Nginx added: the real client IP. Only (c) is safe.
5. The default store keeps counters in each process's memory, so each of the 4
   processes allows 5. Use a shared store such as Redis (rate-limit-redis).
6. Event details: yes, about 60 s to a few minutes, delete on edit. Categories: yes,
   longer TTL. Seats left during a sale: no, read live. A user's own bookings: only
   under a key with the user ID, short TTL, delete on change. Payment status: no.
7. It updated the database but did not delete (invalidate) the cache key. Order:
   write to the database first, then delete the key; the next read loads fresh data.
8. Two or more app servers in different availability zones behind a load balancer
   with health checks; Redis for sessions, rate-limit counters and cache; files in S3;
   a managed database with a standby and tested backups. First move state out of the
   process: sessions, counters, cache and uploaded files.

Frequently Asked Questions

Is rate limiting enough to stop a DDoS attack?

No. A large distributed attack can saturate your network or connections before Node.js even sees the requests, and each attacking machine can stay under a per-IP limit. Use a CDN or provider-level protection (such as CloudFront with AWS Shield, or Cloudflare) in front, and keep application rate limits as an extra layer for login, OTP and other sensitive routes.

Should I use max or limit in express-rate-limit?

Use limit. It replaced max in version 7; max is still accepted as an alias, so older code keeps working, but new code and documentation use limit. Also set standardHeaders to 'draft-7' or 'draft-8' and legacyHeaders: false.

Do I need Redis for a small project?

Not on day one. With one Node.js process, the built-in memory store for rate limiting and a small in-memory cache work fine. You need Redis (or another shared store) once you run more than one process or server, or when you want sessions and counters to survive restarts.

Is helmet enough to secure an Express app?

No. Helmet sets browser security headers, which help against clickjacking, content sniffing and some XSS. It does nothing for SQL injection, broken authorization, weak secrets, missing validation or brute force. It is one useful layer among the many in this post.

VPS or AWS for my first deployment?

A single VPS, or a single EC2 instance, is the easiest way to learn the full path: Linux, Nginx, PM2, HTTPS and DNS. Move to managed services (RDS, S3, a load balancer) when you need backups you do not manage yourself, more than one server, or high availability.

Key Takeaways

  • Security is layers: HTTPS, rate limits, helmet, a CORS allow-list, body limits, authentication, authorization with ownership checks, validation, parameterised queries and generic error messages.
  • Never concatenate user input into SQL; check types to stop NoSQL operator injection; escape output to stop XSS; think about CSRF whenever cookies carry the login.
  • Secrets come from environment variables, are long and random, and the app refuses to start without them.
  • Use express-rate-limit with limit, standard headers and stricter per-route limits on login, OTP, password reset and payments; blocked clients get 429 with Retry-After.
  • Behind Nginx or a load balancer, set trust proxy to the number of proxies you control, never true; with several processes, keep counters in Redis.
  • Cache-aside with a TTL, clear key names and delete-on-write gives fast reads without stale prices; never cache live seat counts or other users' private data under shared keys.
  • Deploy with HTTPS (Let's Encrypt), Nginx, PM2, environment variables, logs, alerts and a CI/CD pipeline; keep the app stateless so it can scale horizontally.

Next, see how databases hold up under this kind of traffic in MySQL Performance Tuning, Database Security & Backup Guide for Beginners, or revisit login and tokens in Authentication, Authorization, JWT & Password Hashing Explained.

References

Related Articles

Post a Comment

0 Comments