Lesson 5 of 7
Rate Limiting & API Throttling
Rate limiting prevents abuse - brute-force attacks, scraping, and accidental runaway scripts. The sliding window algorithm limits requests per IP or API key over a rolling time window. PHP implements this efficiently using Redis (in-memory counter) or a database fallback.
Rate Limiting - Sliding Window Implementation
<?php
declare(strict_types=1);
// ── Rate Limiter interface ────────────────────────────────────
interface RateLimiterInterface {
public function attempt(string $key, int $maxAttempts, int $windowSeconds): bool;
public function remaining(string $key, int $maxAttempts, int $windowSeconds): int;
public function resetIn(string $key, int $windowSeconds): int;
}
// ── PDO-based rate limiter (fallback without Redis) ────────────
class PdoRateLimiter implements RateLimiterInterface {
public function __construct(private readonly PDO $pdo) {
// CREATE TABLE rate_limits (
// key VARCHAR(255) NOT NULL,
// attempts INT NOT NULL DEFAULT 1,
// window_end DATETIME NOT NULL,
// INDEX idx_key (key)
// ) ENGINE=InnoDB;
}
public function attempt(string $key, int $maxAttempts, int $windowSeconds): bool {
$now = new DateTimeImmutable("now", new DateTimeZone("UTC"));
$winEnd = $now->modify("+{$windowSeconds} seconds");
$stmt = $this->pdo->prepare(
"SELECT id, attempts, window_end FROM rate_limits WHERE `key` = :key LIMIT 1"
);
$stmt->execute([":key" => $key]);
$record = $stmt->fetch();
if (!$record || new DateTimeImmutable($record["window_end"]) <= $now) {
// Reset window
$this->pdo->prepare("REPLACE INTO rate_limits (`key`, attempts, window_end) VALUES (:k, 1, :end)")
->execute([":k" => $key, ":end" => $winEnd->format("Y-m-d H:i:s")]);
return true;
}
if ($record["attempts"] >= $maxAttempts) return false;
$this->pdo->prepare("UPDATE rate_limits SET attempts = attempts + 1 WHERE `key` = :k")
->execute([":k" => $key]);
return true;
}
public function remaining(string $key, int $maxAttempts, int $windowSeconds): int {
$stmt = $this->pdo->prepare("SELECT attempts FROM rate_limits WHERE `key` = :key");
$stmt->execute([":key" => $key]);
$attempts = (int) $stmt->fetchColumn();
return max(0, $maxAttempts - $attempts);
}
public function resetIn(string $key, int $windowSeconds): int {
$stmt = $this->pdo->prepare("SELECT window_end FROM rate_limits WHERE `key` = :key");
$stmt->execute([":key" => $key]);
$end = $stmt->fetchColumn();
if (!$end) return $windowSeconds;
return max(0, (new DateTimeImmutable($end))->getTimestamp() - time());
}
}
// ── Rate limit middleware ─────────────────────────────────────
class RateLimitMiddleware {
public function __construct(
private readonly RateLimiterInterface $limiter,
private readonly int $maxAttempts = 60,
private readonly int $windowSeconds = 60,
) {}
public function handle(ApiRequest $req): void {
// Key = IP + endpoint (or user_id if authenticated)
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"] ?? $_SERVER["REMOTE_ADDR"] ?? "unknown";
$key = "api:" . md5($ip . $_SERVER["REQUEST_URI"]);
$allowed = $this->limiter->attempt($key, $this->maxAttempts, $this->windowSeconds);
$remaining = $this->limiter->remaining($key, $this->maxAttempts, $this->windowSeconds);
$resetIn = $this->limiter->resetIn($key, $this->windowSeconds);
// Standard rate limit headers - clients respect these
header("X-RateLimit-Limit: {$this->maxAttempts}");
header("X-RateLimit-Remaining: $remaining");
header("X-RateLimit-Reset: " . (time() + $resetIn));
if (!$allowed) {
header("Retry-After: $resetIn");
ApiResponse::error(
["message" => "Too many requests. Retry after {$resetIn} seconds."],
429,
"RATE_LIMITED"
)->send();
}
}
}Quick Quiz
Tip
Tip
Practice Rate Limiting API Throttling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Rate Limiting & API Throttling
Practice Task
Note
Practice Task - (1) Write a working example of Rate Limiting API Throttling from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Rate Limiting API Throttling is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?