search
HomeWeb Front-endJS TutorialThe Basics of Rate Limiting: How It Works and How to Use It

Rate limiting is a vital concept in web development. It ensures server stability, efficient resource allocation, and protection against malicious attacks. So In this article, we’ll delve into the essence of rate limiting, its importance, various implementation methods, and practical examples to demonstrate its functionality. let’s dive right in ?

What is Rate Limiting?

Rate limiting is a strategy that is used to control the amount of incoming requests or traffic to a web service or to a server. it helps protect your applications from abuse, ensures fair resource distribution, and maintains service stability.

Why Use Rate Limiting?

Here are some of the reasons why you should use rate limiting ??

  • Preventing Abuse: Stops bots or malicious users from overwhelming the server with requests.
  • Resource Management: Ensures fair usage of resources across all users.
  • Security: Helps prevent brute-force attacks by limiting attempts of some endpoints in your application.
  • Cost Control: Helps prevent unexpected charges due to excessive API calls.
  • Performance: Keeps your server responsive and reduces the risk of downtimes.

Types of Rate Limiting

  1. Fixed Window (or Simple) Rate Limiting: This method limits requests within a fixed time window. For example, "100 requests per minute.""
  2. Sliding Window Rate Limiting: A dynamic time frame that tracks and limits requests over a recent period, such as the last few minutes or seconds.
  3. Token Bucket Algorithm: This method uses a "bucket" filled with tokens to manage requests. Each incoming request consumes a token, and the bucket is refilled at set intervals. This approach allows for bursts of traffic while maintaining an overall rate limit.
  4. Leaky Bucket Algorithm: Similar to the token bucket, but with a twist. When the bucket is full, excess requests "leak" out or are discarded, maintaining a steady flow.

? I'm not even going to lie because I don't know much about the Token Bucket and Leaky Bucket algorithms, as I haven't needed them for my current projects. However, Fixed Window and Sliding Window are the most common types you'll encounter. For instance, OpenAI's GPT-4 uses Fixed Window rate limiting with tiered limits—their first tier allows 500 requests per minute This approach can lead to burst traffic, as users might hit their limit just before the window resets.

How Rate Limiting Works

The process typically involves:

  1. Tracking: Monitoring how many requests a user (mostly the userId) or IP has made within a specific timeframe.
  2. Threshold: Defining a limit (e.g., 100 requests per hour).
  3. Response: Sending a warning or blocking further requests when the limit is exceeded (usually with a 429 Too Many Requests HTTP status code).

Implementing Rate Limiting: Practical Examples

Now that you have a basic understanding of rate limiting and how it works, let's get our hands dirty by implementing it in a project we'll be creating.

We'll create two projects demonstrating rate limiting:

  1. A GET request example
  2. A POST request example

Tech Stack

  • Frontend: React (using Vite)
  • Backend: Express (Node.js framework)

GET request example

Create a folder with any name of your choice and open it on VS code or whatever code editor you use.

Inside that folder you've created, create two more folders called frontend and backend.

After that, cd into the backend folders and enter this command npm init -y to initialize a package.json file

After that install the follow npm packages inside the backend folder ??

npm install express cors express-rate-limit

npm install -D nodemon

What these do:

  • express: Creates your web server and handles API routes
  • cors: Allows frontend to communicate with backend safely
  • express-rate-limit: Protects your API from too many requests
  • nodemon: Auto-restarts server during development (that's why we use D)

After that, create an index.js (you can this whatever you want) file because we’ll be using it to set up the rate limiter.

After you’ve done copy and paste this code that I am going to explain in a bit

const express = require("express");
const rateLimit = require("express-rate-limit");

const app = express();

// Set up rate limiter: 100 requests per 15 minutes
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // Limit each IP to 5 requests per `window` (here, per 15 minutes)
  message: "Too many requests from this IP, please try again later.",
});

// Apply the rate limiting middleware to all requests
app.use(limiter);

app.get("/api/data", (req, res) => {
  res.send("Welcome to the API!");
});

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

Here's what each part does:

  1. First two lines import our needed packages
  2. app = express() creates our server
  3. The limiter is configured with:
    • windowMs: Sets a 15-minute time window (15 × 60 × 1000 milliseconds)
    • max: Allows 5 requests per IP address in that window
    • message: The error message users see when they exceed the limit

Then:

  1. app.use(limiter) applies our rate limit to all routes
  2. We create a simple test route at '/api/data' that sends a welcome message
  3. Finally, we start the server on port 5000

When users hit your API more than 100 times in 15 minutes from the same IP, they'll get the error message instead of accessing the API.

Now that you know how it works, we want to enable auto-restart by adding to package.json ??

 {
  "scripts": {
    "dev": "nodemon index.js"
  }
}

That’s all for the backend.

It’s time to set up the frontend.

  • Open a new terminal and cd into the frontend folder and run ??
npm install express cors express-rate-limit

npm install -D nodemon
  • Go through the following instructions and I’ll advise you select JavaScript if you don’t know typescript
  • You can do a little clean up by getting rid of some files you won’t need. here is how mine looks

The Basics of Rate Limiting: How It Works and How to Use It

  • Once you are done, open the App.jsx and paste this code that I’ll explain ??
const express = require("express");
const rateLimit = require("express-rate-limit");

const app = express();

// Set up rate limiter: 100 requests per 15 minutes
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // Limit each IP to 5 requests per `window` (here, per 15 minutes)
  message: "Too many requests from this IP, please try again later.",
});

// Apply the rate limiting middleware to all requests
app.use(limiter);

app.get("/api/data", (req, res) => {
  res.send("Welcome to the API!");
});

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

Here's what's happening:

  1. We import useState for managing data and axios for making API requests
  2. We create two state variables:
    • response: Stores successful API responses
    • error: Stores any error messages
  3. The fetchData function:
    • Gets called when button is clicked
    • Tries to fetch data from our API
    • Updates either response or error state
    • Uses try/catch to handle success and errors
  4. The UI shows:
    • A title
    • A button to trigger requests
    • The API response (if successful)
    • Error messages in red (if request fails) When you click the button too many times within 15 minutes, you'll see the rate limit error message because of our backend restrictions!

That’s all about the GET request example. Let’s move on to the next example

POST request example

For this example, you can decide to comment out the code of the first example and paste this code ??

 {
  "scripts": {
    "dev": "nodemon index.js"
  }
}

You can see that most of the code are the same with the first example but here are just some key difference ??

  • Added bodyParser to handle form data
  • Creates a POST endpoint that processes form submissions

Also paste this code on the frontend as well

  npm create vite@latest .

Here, we're simply making a request to the server through a form. Let's look at how this differs from the GET example:

  1. Uses a form instead of a single button
  2. Manages form state with formData
  3. Handles input changes with handleInputChange
  4. Uses POST request instead of GET
  5. Shows success message in green

The form allows 5 submissions in 15 minutes - after that, users see the rate limit error message.

Conclusion

Alright guys, congrats on getting to the end of this article ?. I hope you now have an idea on how rate limiting works and why you should use it on your projects especially if you are working on bigger projects that involves money. If you have any questions, feel free to ask in the comment. Happy coding ?

The above is the detailed content of The Basics of Rate Limiting: How It Works and How to Use It. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.