2.5 Hours

14. Rate Limiting & Abuse Prevention

Abuse Prevention

Rate limiting is essential for protecting APIs from abuse, brute-force attacks, and resource exhaustion. This module covers implementing rate limiting at multiple levels and using Redis for distributed rate limiting.

Why Rate Limit?

Without rate limiting, attackers can brute-force passwords, exhaust server resources, or overwhelm your API.

Text
Protects against:
- Brute-force password attacks
- DDoS attacks
- API abuse (scraping, spam)
- Resource exhaustion
- Cost spikes (paid APIs)
Rule of thumb: Rate limit EVERY public endpoint. Adjust limits based on endpoint sensitivity and cost.

Basic Rate Limiting (Node.js)

JavaScript
const rateLimit = require('express-rate-limit');

// General API: 100 requests per 15 minutes
const apiLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
    message: 'Too many requests from this IP',
    standardHeaders: true,
    legacyHeaders: false
});

// Authentication: 5 attempts per 15 minutes
const authLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 5,
    skipSuccessfulRequests: true,  // Don't count successful logins
    message: 'Too many login attempts. Please try again later.'
});

// Sensitive endpoints: 10 requests per hour
const sensitiveLimiter = rateLimit({
    windowMs: 60 * 60 * 1000,
    max: 10,
    message: 'Rate limit exceeded for this sensitive operation'
});

app.use('/api/', apiLimiter);
app.use('/api/auth/login', authLimiter);
app.use('/api/auth/register', authLimiter);
app.use('/api/password-reset', sensitiveLimiter);

Distributed Rate Limiting with Redis

For multiple server instances, use Redis for shared rate limiting state.

JavaScript
const Redis = require('ioredis');
const redis = new Redis();

async function slidingWindowLimiter(key, limit, windowSeconds) {
    const now = Date.now();
    const windowStart = now - (windowSeconds * 1000);

    const multi = redis.multi();
    multi.zremrangebyscore(key, 0, windowStart);  // Remove old entries
    multi.zadd(key, now, `${now}-${Math.random()}`);  // Add current request
    multi.zcard(key);  // Get count
    multi.expire(key, windowSeconds);  // Set TTL

    const results = await multi.exec();
    const requestCount = results[2][1];

    return requestCount <= limit;
}

// Rate limiting middleware
async function rateLimitMiddleware(req, res, next) {
    const key = `rate:${req.user?.id || req.ip}`;
    const limit = req.user?.role === 'premium' ? 1000 : 100;
    const windowSeconds = 60;

    const allowed = await slidingWindowLimiter(key, limit, windowSeconds);

    if (!allowed) {
        return res.status(429).json({ error: 'Rate limit exceeded' });
    }

    next();
}

app.use('/api/', rateLimitMiddleware);
Why Redis? In-memory rate limiting doesn't work across multiple server instances. Redis provides shared state.

Progressive Rate Limiting

As users violate limits, progressively restrict them more.

JavaScript
async function progressiveRateLimiter(req, res, next) {
    const key = `violations:${req.ip}`;
    const violations = await redis.get(key) || 0;

    let limit = 100;
    let window = 60;

    if (violations > 100) {
        limit = 10;
        window = 3600;  // 1 hour
    } else if (violations > 50) {
        limit = 30;
        window = 300;   // 5 minutes
    } else if (violations > 10) {
        limit = 50;
        window = 120;   // 2 minutes
    }

    const allowed = await slidingWindowLimiter(`rate:${req.ip}`, limit, window);

    if (!allowed) {
        await redis.incr(key);
        await redis.expire(key, 86400);
        return res.status(429).json({ error: 'Rate limit exceeded' });
    }

    next();
}

Rate Limit Headers

Inform clients about their limits using standard headers.

JavaScript
app.use(async (req, res, next) => {
    const key = `rate:${req.ip}`;
    const limit = 100;
    const remaining = await getRemainingRequests(key);
    const reset = await getResetTime(key);

    res.setHeader('X-RateLimit-Limit', limit);
    res.setHeader('X-RateLimit-Remaining', remaining);
    res.setHeader('X-RateLimit-Reset', reset);
    res.setHeader('Retry-After', Math.ceil((reset - Date.now()) / 1000));

    next();
});
Standard Headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset help clients implement backoff strategies.

Knowledge Check

Ready to test your understanding of 14. Rate Limiting & Abuse Prevention?

Back