Implementing API Rate Limiting in PHP with Redis
This article explains how to implement API rate limiting in PHP by connecting to Redis, defining a RateLimiter class with limitRequests method, and demonstrates usage to restrict requests per time window, while detailing the underlying logic and code examples.
When developing APIs, to prevent malicious requests and ensure system stability, we often need to apply rate limiting. This article introduces how to implement API rate limiting using PHP.
First, we need a Redis connection to store and manage request counters. The following code establishes a connection to Redis:
<code>class RateLimiter {
private $redis; // Redis connection
public function __construct() {
// Assume a Redis connection has already been established
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
// ...
}
</code>Next, we define a limitRequests method to implement the rate‑limiting logic. The method accepts three parameters: $key (the API identifier), $limit (the maximum number of requests), and $window (the size of the time window in seconds).
<code>public function limitRequests($key, $limit, $window) {
$currentTime = time();
$keyPrefix = 'ratelimiter:' . $key;
$windowKey = $keyPrefix . ':' . floor($currentTime / $window);
$requests = $this->redis->get($windowKey);
if ($requests === false) {
// Create a new window
$this->redis->multi();
$this->redis->incr($windowKey);
$this->redis->expire($windowKey, $window + 1); // Set expiration slightly larger than window size
$this->redis->exec();
return true;
}
if ($requests < $limit) {
// Request count within the current window has not reached the limit
$this->redis->incr($windowKey);
return true;
}
// Limit reached, reject request
return false;
}
</code>In limitRequests , we compute a window key based on the current time and window size, retrieve the request count from Redis, create a new window if none exists, increment the counter, and set an expiration slightly longer than the window. The method returns true if the request is allowed, otherwise false .
If the key exists and the request count is below the limit, we increment the counter and return true ; if the limit is reached, we return false to reject the request.
Below is a usage example:
<code>$rateLimiter = new RateLimiter();
// API rate limiting: limit to 5 requests per minute
$key = 'api:example';
$limit = 5;
$window = 60;
if ($rateLimiter->limitRequests($key, $limit, $window)) {
// Execute API logic
echo "API request succeeded";
} else {
// Return error indicating request rate is too high
echo "Request rate too high, please try again later";
}
</code>In the example, we instantiate a RateLimiter object and call limitRequests ; if the request passes the rate‑limit check, we execute the API logic and output a success message, otherwise we output an error indicating the request rate is too high.
This simple implementation provides basic API rate limiting, and can be extended with IP address, user identity, or other criteria for finer‑grained control.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.