Implementing API Rate Limiting with Redis in PHP

This article explains how to implement API request frequency control in PHP using Redis, detailing a function that tracks per‑user request counts within a configurable time window, removes outdated entries, and returns appropriate responses when the limit is exceeded.

php Courses
php Courses
php Courses
Implementing API Rate Limiting with Redis in PHP

Many web services impose simple request limits such as "10 requests per minute", which can cause problems when a user reaches the limit just before the window expires and then immediately hits the limit again. The article discusses why such fixed windows are often unreasonable.

To address this, a PHP function api_frequency_visits is presented that uses Redis hash structures to record timestamps of each request per user, automatically discarding entries older than the configured time window and counting the remaining requests.

The code allows customization of the maximum number of requests ( $max_frequency), the time window in seconds ( $limit_time), and the Redis key format, so it can be adapted for different identifiers such as IP addresses. It also shows how to set a key expiration if desired.

When the request count exceeds the limit, the function returns false, and the caller can respond with an error message (e.g., "操作过于频繁"). Otherwise, the request count is incremented and a success JSON payload is returned.

/**
 * @param $uid
 * @return bool|int
 * 检测用户接口访问频率
 */
function api_frequency_visits ($uid) {
    $key = "user:{$uid}:api:frequency";
    $redis = new Redis();
    $redis->connect('127.0.0.1');
    $data = $redis->hGetAll($key);
    //需要删除的key
    $del_key = [];
    //时间内访问的总次数
    $total = 0;
    //时间内最大访问次数
    $max_frequency = 10;
    //当前时间
    $now_time = time();
    //限制时间
    $limit_time = 60;
    foreach ($data as $time=>$count) {
        if ($time < $now_time - $limit_time) {
            $del_key[] = $time;
        } else {
            $total += $count;
        }
    }
    //存在需要删除的key
    if ($del_key) {
        $redis->hDel($key, ...$del_key);
    }
    if ($total >= $max_frequency) {
        return false;
    }
    return $redis->hIncrBy($key, $now_time, 1);
}
$uid = 1;
$result = api_frequency_visits($uid);
if (!$result) {
    echo json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]]);
    die;
}
echo json_encode(['code'=>1, 'msg'=>'', 'data'=>[
    'uid'=>$uid,
    'other'=>rand()
]]);
 die;

Developers can modify the limit values, switch the identifier from user ID to IP, or add key expiration to suit their specific use cases. The original article can be read for more details.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendredisPHPAPIrate limiting
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.