Backend Development 2 min read 757 views

API Rate Limiting: Strategies and Implementation Guide

Protect your APIs with effective rate limiting. Learn about algorithms, Redis implementation, and response headers.

E
API rate limiting

API Rate Limiting Implementation

Protect your APIs from abuse with effective rate limiting.

Rate Limiting Algorithms

  • Fixed Window: Simple, but allows bursts at window edges
  • Sliding Window: Smoother distribution
  • Token Bucket: Allows controlled bursts
  • Leaky Bucket: Constant rate output

Laravel Rate Limiting

// app/Providers/RouteServiceProvider.php
RateLimiter::for('api', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

// Different limits for different endpoints
RateLimiter::for('uploads', function (Request $request) {
    return $request->user()->isPremium()
        ? Limit::none()
        : Limit::perHour(10)->by($request->user()->id);
});

Redis Implementation

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

async function rateLimit(key, limit, windowSec) {
    const current = await redis.incr(key);

    if (current === 1) {
        await redis.expire(key, windowSec);
    }

    if (current > limit) {
        const ttl = await redis.ttl(key);
        throw new RateLimitError(`Rate limit exceeded. Retry after ${ttl}s`);
    }

    return { remaining: limit - current, reset: windowSec };
}

// Middleware
app.use(async (req, res, next) => {
    try {
        const key = `rate:${req.ip}`;
        const { remaining, reset } = await rateLimit(key, 100, 60);

        res.set('X-RateLimit-Remaining', remaining);
        res.set('X-RateLimit-Reset', reset);
        next();
    } catch (error) {
        res.status(429).json({ error: error.message });
    }
});

Response Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1640000000
Retry-After: 30

Best Practices

  • Use different limits for authenticated vs anonymous users
  • Implement graduated responses (warn before blocking)
  • Whitelist trusted IPs or API keys
  • Log rate limit violations for analysis

Rate limiting is essential for API stability and fair resource allocation.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!