What is Rate Limiting? API Protection

Share

TL;DR

Rate limiting restricts how many requests a user can make in a given time period. Without it, attackers can brute force passwords, scrape your data, or overwhelm your servers. Common limits: 100 requests per minute for APIs, 5 login attempts per hour for auth endpoints. Return HTTP 429 when limits are exceeded.

The Simple Explanation

Imagine your API as a coffee shop. Without rate limiting, one person could order 10,000 coffees per minute, blocking everyone else and exhausting your resources. Rate limiting says "you can only order 10 coffees per minute, then you have to wait."

Why Rate Limiting Matters

  • Brute force protection: Limit login attempts to prevent password guessing
  • DDoS mitigation: Prevent single sources from overwhelming your server
  • Cost control: Limit expensive operations (AI calls, SMS)
  • Fair usage: Ensure all users get reasonable access
  • Scraping prevention: Make bulk data extraction impractical

Implementation Example

Express.js with express-rate-limit

import rateLimit from 'express-rate-limit';

const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // 100 requests per window message: { error: 'Too many requests, try again later' } });

app.use('/api/', limiter);

// Stricter limit for auth endpoints const authLimiter = rateLimit({ windowMs: 60 * 60 * 1000, // 1 hour max: 5, // 5 attempts per hour });

app.use('/api/login', authLimiter);

Common Rate Limits

Endpoint TypeSuggested LimitReason
Login5/hour per IPPrevent brute force
Password reset3/hour per emailPrevent email bombing
API endpoints100/minute per userFair usage
Signup10/hour per IPPrevent spam accounts

Response Headers

Rate limit response headers

HTTP/1.1 429 Too Many Requests Retry-After: 3600 X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1706140800

What endpoints need rate limiting?

Prioritize login endpoints, password reset, signup, payment endpoints, and any endpoint that sends emails or SMS. These are targets for brute force attacks and abuse. Also rate limit expensive operations like search, file uploads, and AI API calls that cost money.

Should I rate limit by IP or by user?

Use both. IP-based limits protect public endpoints before login. User-based limits protect authenticated endpoints and prevent abuse by logged-in users. IP limiting alone fails when attackers use many IPs or when users share an IP (like corporate networks or VPNs).

What HTTP status code should rate limiting return?

Return 429 Too Many Requests when rate limited. Include a Retry-After header telling clients when they can try again. Good clients will respect this. Also consider returning X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers so clients can track their usage.

Check Your Rate Limiting

Scan your API for missing rate limits on sensitive endpoints.

Start Free Scan
Security Glossary

What is Rate Limiting? API Protection