API Security

Design API Rate Limiting in PHP

Protect public and authenticated endpoints with predictable limits, clear HTTP responses and storage that works across application workers.

Overview

Rate limiting controls how frequently a client can call an endpoint during a defined period. It protects expensive operations from accidental loops, abusive automation and resource exhaustion. It is not a replacement for authentication, authorization or input validation.

Choose a limit key

Use a stable identity appropriate to the endpoint: an authenticated account ID, an API key ID, or a carefully normalized client IP for anonymous traffic. Do not trust arbitrary forwarding headers unless the reverse proxy is configured to overwrite them. For shared networks, IP-only limits can affect unrelated users.

A simple fixed-window model

A fixed window counts requests for a key and a time bucket. The database or cache key can be composed from the route name, client identity and current time bucket.

$windowSeconds = 60;
$limit = 60;
$bucket = intdiv(time(), $windowSeconds);
$key = hash('sha256', $route . '|' . $clientId . '|' . $bucket);

// Atomically increment this key in shared storage.
// Reject when the returned count is greater than $limit.

The increment must be atomic. A read-then-write sequence can allow concurrent requests to exceed the limit. Use a database upsert, Redis INCR with expiry, or another atomic counter. In a multi-server deployment, local PHP memory is not shared and is therefore unsuitable.

Return useful HTTP metadata

When rejecting a request, return HTTP 429 and consider Retry-After. If you publish limit headers, document their meaning and keep them consistent. Avoid revealing internal account identifiers or storage keys.

Select different policies

Login, password reset, search, file conversion and ordinary read endpoints have different cost and abuse profiles. Apply stricter limits to sensitive or expensive operations. Combine per-account limits with a broader infrastructure-level protection where appropriate.

Operational checklist

  • Use shared, atomic storage for multiple workers or servers.
  • Normalize identity only at trusted proxy boundaries.
  • Define limits per endpoint class, not one global number.
  • Return 429 and a useful retry interval.
  • Monitor rejected requests without logging secrets.
  • Test simultaneous requests and boundary conditions.

References

OWASP API Security · HTTP 429

Share this page Help other developers discover this resource.