DEV Community

Rishi Raj Jain
Rishi Raj Jain

Posted on

Tackle DDOS attacks with Redis Rate Limiting

In this tutorial, we'll explore how to effectively defend against Distributed Denial of Service (DDoS) attacks using Redis Rate Limiting with Upstash Redis. By the end, you'll have a powerful mechanism to protect your application from excessive traffic, and ensure its availability.

Install Upstash Rate Limiting SDK

First, let's start by installing the necessary packages for Upstash Rate Limiting.

npm install @upstash/ratelimit @upstash/redis
Enter fullscreen mode Exit fullscreen mode

Configure Environment Variables

Create a Redis database using Upstash Console or Upstash CLI. Select the regions nearest to your deploymeny region to minimize the latency. Set the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN as environment variables in your deployment platform.

# .env

UPSTASH_REDIS_REST_URL=<YOUR_URL>
UPSTASH_REDIS_REST_TOKEN=<YOUR_TOKEN>
Enter fullscreen mode Exit fullscreen mode

Initialize the Rate Limiter SDK

We'll initialize the Rate Limiter SDK to define rate-limiting rules for incoming requests. The code below sets up a rate limiter that allows 10 requests per 10 seconds.

import { Redis } from "@upstash/redis"
import { Ratelimit } from "@upstash/ratelimit"

// Create a new ratelimiter, that allows 10 requests per 10 seconds
const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "10 s")
})
Enter fullscreen mode Exit fullscreen mode

Implement Rate Limiting with a Unique Identifier

To apply rate limiting to a specific endpoint or action, you'll need a unique identifier. In this code snippet, the identifier is set to "api". Usually, you can use the identifier as request IP Address, or the user email, for example. If the rate limit is exceeded, a message is returned to the client, preventing excessive requests. Otherwise, the application performs the intended action.

const identifier = "api"

const { success } = await ratelimit.limit(identifier)

if (!success) {
  // Return with custom message for rate limiting
}

// Perform your usual operations
Enter fullscreen mode Exit fullscreen mode

You're Done!

By following these steps, you've learned how to defend your application against DDoS attacks using Redis Rate Limiting with Upstash. This can significantly enhance the security and resilience of your web services, ensuring they remain available even during high-traffic periods.

Top comments (0)