DeveloperBreeze

Protect your API from abuse and learn how rate limiting works under the hood.

When developing web apps or APIs, it’s critical to prevent users from overwhelming your server. That’s where rate limiting comes in. In this guide, we’ll build a custom rate limiter in Node.js using Redis—no libraries, no magic, just code you control and understand.


🚀 What You’ll Learn

  • How to use Redis to count and throttle requests
  • How to implement reusable middleware in Express
  • How to rate limit by IP or API key
  • Why this method is better for learning and customization

🛠 Prerequisites

  • Node.js installed
  • Redis running locally (or via Docker)
  • Basic Express.js knowledge

🧱 Step 1: Set Up the Project

mkdir node-rate-limiter
cd node-rate-limiter
npm init -y
npm install express redis dotenv

Create a .env file:

REDIS_URL=redis://localhost:6379

🔌 Step 2: Connect to Redis

// redisClient.js
const redis = require("redis");

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

client.on("error", (err) => console.error("Redis error:", err));
client.connect();

module.exports = client;

🧠 Step 3: Write the Rate Limiting Middleware

// rateLimiter.js
const client = require("./redisClient");

const rateLimiter = (limit = 100, windowSec = 3600) => {
  return async (req, res, next) => {
    const ip = req.ip;
    const key = `rate_limit:${ip}`;

    const current = await client.get(key);

    if (current !== null && parseInt(current) >= limit) {
      return res.status(429).json({ error: "Too many requests. Try later." });
    }

    const multi = client.multi();
    multi.incr(key);
    if (!current) {
      multi.expire(key, windowSec);
    }
    await multi.exec();

    next();
  };
};

module.exports = rateLimiter;

🌐 Step 4: Use It in Your Express App

// server.js
require("dotenv").config();
const express = require("express");
const rateLimiter = require("./rateLimiter");

const app = express();
const PORT = 3000;

app.use(rateLimiter(100, 3600)); // 100 requests/hour per IP

app.get("/", (req, res) => {
  res.send("Welcome! You're within rate limit.");
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

🧪 Step 5: Test It

Use Postman or curl:

curl http://localhost:3000

After 100 requests within an hour, you’ll get:

{
  "error": "Too many requests. Try later."
}

🧩 Bonus: Rate Limit by API Key

Instead of IP address, use API keys for user-specific limits:

const userKey = req.headers['x-api-key'] || req.ip;
const key = `rate_limit:${userKey}`;

You can now:

  • Offer different limits for free vs paid users
  • Log or monitor usage per user

🎓 Why This Is Valuable

This isn’t just a quick fix—it’s a deep dive into:

  • Atomic operations with Redis
  • Manual request tracking logic
  • Flexibility to customize based on business rules

You’re no longer blindly relying on a package—you understand and control the system.


✅ What’s Next?

Want to extend this?

  • Implement sliding windows
  • Use Redis tokens (token bucket)
  • Add real-time dashboards or admin controls

If you're building any kind of real API, this knowledge will serve you well.


Have questions or want a follow-up tutorial? Leave a comment or reach out—we’d love to help.

🔗 More practical Node.js guides →


Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Using Node.js to Run JavaScript

  • Save the file and run it with Node.js:
     node example.js

Dec 10, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

  • Encryption: Store sensitive data, such as private keys, in an encrypted format.
  • Access Controls: Limit who and what can access the database.
  • Use environment variables or configuration files to manage sensitive information instead of hardcoding them in your source code.

Oct 24, 2024
Read More
Tutorial
bash

How to Update Node.js and npm on Ubuntu

   npm install

Updating Node.js and npm is an essential task for keeping your development environment up to date. Following this tutorial ensures that you’re running the latest, most secure, and feature-rich versions of Node.js and npm.

Oct 03, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

{
  "title": "1984"
}

Subscriptions enable real-time updates to clients. They are commonly used for features like notifications and live data feeds.

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

   node index.js

Open a browser and go to http://localhost:4000/graphql. You'll see the Apollo GraphQL Playground, where you can test your queries and mutations.

Aug 12, 2024
Read More
Tutorial
javascript css +1

Building a Real-Time Chat Application with WebSockets in Node.js

npm init -y
npm install express socket.io

Aug 03, 2024
Read More
Code
php

JWT Token Creation and Verification in Node.js using 'jsonwebtoken'

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Simple HTTP Server in Node.js

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Read and Write Files in Node.js using 'fs' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Simple RESTful API in Node.js using Express

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Date Manipulation and Sum Calculation

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Access Command-line Arguments

// Access command-line arguments excluding the first two elements (node and script path)
const args = process.argv.slice(2);

// Log the command-line arguments
console.log('Command-line arguments:', args);

Jan 26, 2024
Read More
Code
javascript

Set and Access Environment Variable

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Event Emitter using 'events' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Construct File Path using 'path' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Basic Authentication using 'express-basic-auth' middleware

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Create and Print Buffer

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Hashing Password with SHA-256 using 'crypto' module

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Parse URL and Query Parameters

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Execute Shell Command using 'child_process' module

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!