PHP

Rate Limiter (token bucket, file-backed)

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A dirt-simple rate limiter that throttles per-key using a token bucket persisted to a JSON file. Good for single-server protection of expensive endpoints; reach for Redis when you scale out.
PHP
Raw
<?php
function rateLimit(string $key, int $burst = 10, float $refillPerSec = 1.0, string $dir = '/tmp/rl'): bool {
    if (!is_dir($dir)) mkdir($dir, 0700, true);
    $file = $dir . '/' . sha1($key) . '.json';
    $fh   = fopen($file, 'c+');
    flock($fh, LOCK_EX);
    $state = json_decode(stream_get_contents($fh) ?: '{}', true) ?: [];
    $now   = microtime(true);
    $tokens = min($burst, ($state['tokens'] ?? $burst) + ($now - ($state['ts'] ?? $now)) * $refillPerSec);
    $allow  = $tokens >= 1;
    if ($allow) $tokens -= 1;
    rewind($fh);
    ftruncate($fh, 0);
    fwrite($fh, json_encode(['tokens' => $tokens, 'ts' => $now]));
    flock($fh, LOCK_UN);
    fclose($fh);
    return $allow;
}

if (!rateLimit('login:' . $_SERVER['REMOTE_ADDR'], burst: 5, refillPerSec: 0.2)) {
    http_response_code(429); exit('Too many requests');
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.