Skip to content

Backend Rate Limiting — Protecting APIs with Rate Limiting

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Rate Limiting. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Rate limiting protects backend services from abuse, brute-force attacks, and resource exhaustion.

// Distributed rate limiter with Redis
class RedisRateLimiter {
  constructor(options = {}) {
    this.windowMs = options.windowMs || 60000;
    this.maxRequests = options.maxRequests || 100;
    this.redis = new Redis(process.env.REDIS_URL);
  }

  async check(key) {
    const now = Date.now();
    const windowKey = `ratelimit:${key}:${Math.floor(now / this.windowMs)}`;

    const multi = this.redis.multi();
    multi.incr(windowKey);
    multi.pttl(windowKey);

    const [count, ttl] = await multi.exec();

    // Set expiry on first request
    if (count[1] === 1) {
      await this.redis.pexpire(windowKey, this.windowMs);
    }

    return {
      remaining: Math.max(0, this.maxRequests - count[1]),
      total: this.maxRequests,
      resetMs: ttl[1] > 0 ? ttl[1] : this.windowMs
    };
  }

  async isRateLimited(key) {
    const status = await this.check(key);
    return {
      limited: status.remaining === 0,
      headers: {
        'X-RateLimit-Limit': status.total,
        'X-RateLimit-Remaining': status.remaining,
        'X-RateLimit-Reset': Math.ceil((Date.now() + status.resetMs) / 1000)
      }
    };
  }
}

// Rate limiting middleware
const rateLimiter = new RedisRateLimiter({ maxRequests: 100, windowMs: 60000 });

app.use('/api', async (req, res, next) => {
  const key = req.user?.id || req.ip;
  const result = await rateLimiter.isRateLimited(key);

  res.set(result.headers);

  if (result.limited) {
    return res.status(429).json({
      error: 'RATE_LIMITED',
      message: 'Too many requests, please try again later',
      retryAfter: Math.ceil(result.headers['X-RateLimit-Reset'] - Date.now() / 1000)
    });
  }

  next();
});

Distributed rate limiting provides consistent protection across multiple application instances.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro