Rate Limiting a PHP API: Per Route and Per IP, with Redis or MySQL

Rate limiting a PHP API per route and per IP with Redis or MySQL

Quick answer: A rate limit caps how many requests an IP address or user can make in a time window. Set limits per route (login much stricter than listings), count requests with a key like route + IP + window in Redis (or MySQL if you don't have Redis), and when the limit is exceeded return 429 Too Many Requests with a Retry-After header. For login, also limit attempts per account, and make sure you read the real client IP when the API sits behind a proxy or CDN.

Without a rate limit, a single script can try thousands of passwords per minute, scrape every endpoint, or overload the server and the database. A rate limit is one of the simplest and most effective protections an API can have. This guide implements it in plain PHP, per route and per IP, with Redis and with a MySQL fallback.

What a rate limit protects against

  • Brute force on login and password reset;
  • Credential stuffing with leaked email/password lists;
  • Scraping of public endpoints;
  • Overload from buggy clients stuck in loops;
  • Cost abuse of endpoints that send emails or SMS, or call paid APIs.

Limits per route

Different endpoints need different limits. A starting point:

RouteLimitWhy
POST /api/auth/login5 per minute per IP, 10 per 15 minutes per accountBrute force
POST /api/auth/forgot-password3 per hour per IPSends emails
POST /api/auth/refresh30 per hour per IPShould be rare
GET /api/posts60 per minute per IPNormal use
Everything else120 per minute per IPDefault

Adjust them by watching real traffic: limits should never bother a normal user.

The response when the limit is hit

HTTP/1.1 429 Too Many Requests
Retry-After: 42
Content-Type: application/json

{"success": false, "message": "Too many requests. Try again in 42 seconds."}

Retry-After tells well-behaved clients how long to wait. Use the same JSON format as your other errors (see error handling in a PHP API).

Getting the real client IP

Behind Cloudflare, a load balancer or a reverse proxy, $_SERVER['REMOTE_ADDR'] is the proxy's IP, and every visitor would share one limit. But headers like X-Forwarded-For can be faked by anyone, so only trust them when the request really comes from your proxy:

<?php

function clientIp(): string
{
    $remote = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

    // Only trust forwarded headers from your own proxies
    $trustedProxies = ['10.0.0.5'];   // e.g. your load balancer's private IP

    if (in_array($remote, $trustedProxies, true) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $parts = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
        $candidate = end($parts);   // the address your proxy saw
        if (filter_var($candidate, FILTER_VALIDATE_IP)) {
            return $candidate;
        }
    }

    return $remote;
}

With Cloudflare, the simplest option is Apache's mod_remoteip (or Nginx's real_ip module) configured with Cloudflare's IP ranges and the CF-Connecting-IP header, so REMOTE_ADDR is already correct when it reaches PHP.

Normalizing the route key

Don't use the raw path as the key: /api/posts/1, /api/posts/2 and so on would each get their own limit. Use the route pattern instead:

<?php
$method = $_SERVER['REQUEST_METHOD'];
$path   = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$route  = $method . ' ' . preg_replace('#/\d+(?=/|$)#', '/{id}', rtrim($path, '/'));
// "GET /api/posts/{id}"

Option 1: Redis (recommended)

Redis is fast, keeps counters in memory and expires them on its own. A fixed-window counter with the phpredis extension:

<?php

function rateLimitRedis(Redis $redis, string $key, int $max, int $window): array
{
    $windowId = intdiv(time(), $window);
    $redisKey = "rl:{$key}:{$windowId}";

    // INCR and EXPIRE together, so a crash can't leave a key without expiry
    [$count] = $redis->multi()
        ->incr($redisKey)
        ->expire($redisKey, $window)
        ->exec();

    $retryAfter = ($windowId + 1) * $window - time();

    return [
        'allowed'     => $count <= $max,
        'remaining'   => max(0, $max - $count),
        'retry_after' => max(1, $retryAfter),
    ];
}

Option 2: MySQL (no Redis needed)

For small and medium APIs, a table works well:

CREATE TABLE api_rate_limits (
    rl_key     VARCHAR(190) NOT NULL,
    window_id  BIGINT NOT NULL,
    hits       INT NOT NULL,
    expires_at DATETIME NOT NULL,
    PRIMARY KEY (rl_key, window_id),
    KEY idx_expires (expires_at)
);
<?php

function rateLimitMySQL(PDO $pdo, string $key, int $max, int $window): array
{
    $windowId  = intdiv(time(), $window);
    $windowEnd = ($windowId + 1) * $window;

    // Insert or increment in one atomic statement; LAST_INSERT_ID(expr) returns the new count
    $stmt = $pdo->prepare('
        INSERT INTO api_rate_limits (rl_key, window_id, hits, expires_at)
        VALUES (:k, :w, LAST_INSERT_ID(1), FROM_UNIXTIME(:e))
        ON DUPLICATE KEY UPDATE hits = LAST_INSERT_ID(hits + 1)
    ');
    $stmt->execute([':k' => $key, ':w' => $windowId, ':e' => $windowEnd]);
    $count = (int) $pdo->lastInsertId();

    return [
        'allowed'     => $count <= $max,
        'remaining'   => max(0, $max - $count),
        'retry_after' => max(1, $windowEnd - time()),
    ];
}

One statement does the insert, the increment and the read, with no race between them. Clean up old rows with a cron job:

DELETE FROM api_rate_limits WHERE expires_at < NOW();

Applying it as middleware

<?php

$rules = [
    'POST /api/auth/login'           => ['max' => 5,   'window' => 60],
    'POST /api/auth/forgot-password' => ['max' => 3,   'window' => 3600],
    'POST /api/auth/refresh'         => ['max' => 30,  'window' => 3600],
    'GET /api/posts'                 => ['max' => 60,  'window' => 60],
];
$rule = $rules[$route] ?? ['max' => 120, 'window' => 60];

$result = rateLimitMySQL($pdo, $route . '|' . clientIp(), $rule['max'], $rule['window']);

header('X-RateLimit-Limit: ' . $rule['max']);
header('X-RateLimit-Remaining: ' . $result['remaining']);

if (!$result['allowed']) {
    http_response_code(429);
    header('Retry-After: ' . $result['retry_after']);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => false,
        'message' => 'Too many requests. Try again in ' . $result['retry_after'] . ' seconds.',
    ]);
    exit;
}

Run it right after the CORS preflight and before authentication, so even unauthenticated requests are limited.

Login needs more than a per-IP limit

Attackers spread login attempts across many IPs. Add a second limit per account, keyed on the email:

<?php
$email = strtolower(trim((string) ($input['email'] ?? '')));
$accountKey = 'login-account|' . hash('sha256', $email);

$result = rateLimitMySQL($pdo, $accountKey, 10, 900);   // 10 attempts per 15 minutes
if (!$result['allowed']) {
    // same 429 response as above
}

Hashing the email keeps addresses out of the rate-limit table. Return the same generic message for wrong passwords and unknown emails, so the API doesn't reveal which accounts exist.

Fixed window, sliding window and token bucket

  • Fixed window (used above): simple and cheap, but a client can send the maximum at the end of one window and again at the start of the next;
  • Sliding window: counts requests in the last N seconds, smoother but needs more storage (a Redis sorted set per key);
  • Token bucket: allows short bursts while enforcing an average rate.

For most APIs, a fixed window with sensible limits is enough.

Rate limits outside PHP

You can also limit requests before they reach PHP: Nginx limit_req, Cloudflare rate limiting rules, or an API gateway. They are cheaper because the request never runs PHP, and they work well as a first, coarse layer. Keep the per-route and per-account rules in PHP, where you know the user and the endpoint.

Best practices

  • Different limits per route, strictest on login and anything that sends messages;
  • Per IP and, for login, per account;
  • 429 with Retry-After and your usual JSON error format;
  • Correct client IP behind proxies, without trusting arbitrary headers;
  • Log repeated 429s: they show attacks and misbehaving clients;
  • Higher limits for authenticated users or API keys, keyed by user ID instead of IP.

Conclusion

A rate limit takes one table (or a Redis instance) and a few lines of middleware, and it blocks brute force, scraping and runaway clients before they cause damage. Start with per-route limits per IP, add a per-account limit on login, and tune the numbers from real traffic. For the rest of the authentication flow, see refresh tokens in PHP and JWT authentication in PHP.

Frequently asked questions

What HTTP status should a rate limit return?

429 Too Many Requests, with a Retry-After header in seconds.

Do I need Redis?

No. MySQL works well for small and medium traffic. Redis is better for high traffic or many servers.

Why does everyone hit the limit at the same time?

Your API is probably behind a proxy and sees the proxy's IP for every request. Read the real client IP from a trusted proxy header.

Can attackers bypass a per-IP limit?

Partly, by using many IPs. That is why login also needs a per-account limit, and why CAPTCHAs or extra checks help after repeated failures.

Should rate limiting run before or after authentication?

Before, so unauthenticated floods are stopped too. You can add a second, per-user limit after authentication.

More in PHP