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

  • Use it in your code:
     const _ = require('lodash');
     console.log(_.capitalize("hello world"));

Dec 10, 2024
Read More
Tutorial

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

To access and utilize the data stored in your SQLite database, you can perform SQL queries. Here's how to retrieve and display the data from the "accounts" table.

Add the following code to your app.js file within the db.serialize() block, after inserting data:

Oct 24, 2024
Read More
Tutorial
bash

How to Update Node.js and npm on Ubuntu

NodeSource provides an easy way to install and manage Node.js. To install a specific Node.js version, add the NodeSource repository for the version you want.

For Node.js 18 (LTS) (recommended):

Oct 03, 2024
Read More
Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

When you execute the addBook mutation, you'll see real-time updates in the subscription.

This tutorial has covered the basics of setting up a GraphQL API with Node.js and Apollo Server, including creating queries, mutations, and subscriptions. By leveraging GraphQL's powerful features, you can build efficient, flexible, and scalable APIs for your applications.

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

     query {
       books {
         title
         author
       }
     }
  • Add a Book

Aug 12, 2024
Read More
Tutorial
javascript css +1

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

In this tutorial, we will create a real-time chat application using Node.js and WebSockets. Real-time communication is a crucial aspect of modern web applications, allowing users to interact with each other instantaneously. By leveraging WebSockets, we can establish a persistent connection between the client and server, enabling seamless data exchange.

WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. Unlike HTTP, WebSockets maintain a persistent connection, making them ideal for applications requiring real-time updates, such as chat apps, online gaming, and live notifications.

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

// Import required modules
const moment = require('moment');
const _ = require('lodash');

// Get the current date and time using Moment.js
const now = moment();

// Example array of numbers
const numbers = [1, 2, 3, 4, 5];

// Calculate the sum of the array using Lodash
const sum = _.sum(numbers);

Jan 26, 2024
Read More
Code
javascript

Access Command-line Arguments

No preview available for this content.

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!