Sliding Window SMS Sending Rate Limiting Algorithm in PHP with Redis
This article explains two sliding‑window rate‑limiting methods for SMS sending—one based on IP address and another on phone number—and provides a complete PHP implementation using Redis sorted sets to enforce per‑minute, per‑10‑minute, and per‑hour limits.
There are two sliding‑window rate‑limiting strategies for SMS sending: one based on the client IP address and another based on the mobile phone number.
1. IP‑address limits
1 minute limit: 5
10 minutes limit: 30
1 hour limit: 502. Phone‑number limits
1 minute limit: 1
10 minutes limit: 5
1 hour limit: 10The following PHP code demonstrates how to enforce these limits using Redis sorted sets.
5,
600 => 30,
3600 => 50
);
// Phone rules
$phoneRules = array(
60 => 1,
600 => 5,
3600 => 10
);
// Check limits based on IP
$r = checkLimits($ipRules, $_SERVER["REMOTE_ADDR"], $_GET['tel']);
var_dump($r);
// Check limits based on phone number
$r = checkLimits($phoneRules, $_GET['tel'], $_GET['tel']);
var_dump($r);
function checkLimits($rules, $key, $tel) {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
foreach ($rules as $ruleTime => $rule) {
$redisKey = $key . "_" . $ruleTime;
$score = time();
$member = $tel . '_' . $score;
$redis->multi();
// Remove data outside the window
$redis->zRemRangeByScore($redisKey, 0, $score - $ruleTime);
$redis->zAdd($redisKey, $score, $member);
$redis->expire($redisKey, $ruleTime);
$redis->zRange($redisKey, 0, -1, true);
$members = $redis->exec();
if (empty($members[3])) {
break;
}
$nums = count($members[3]);
var_dump($nums);
if ($nums > $rule) {
return false;
}
}
return true;
}
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.