SoFunction
Updated on 2025-04-05

Redis Example code for implementing counters and speed limiters

Redis is a very suitable tool for implementing counters and speed limiters because it provides efficient atomic operations such as self-increase, self-decrease, etc. Here are detailed examples of how to implement counters and speed limiters using Redis.

1. Implement the counter using Redis

Counters are usually used to count the number of times a certain event occurs, such as the number of user likes, page visits, etc. Provided by RedisINCRandINCRBYCommands can help us implement this function easily.

Example: Statistics of user likes

<?php
class LikeCounter {
    private $redis;

    public function __construct() {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    public function incrementLike($postId) {
        $key = "post_likes:$postId";
        return $this->redis->incr($key);
    }

    public function getLikeCount($postId) {
        $key = "post_likes:$postId";
        return $this->redis->get($key);
    }
}

// Example usage$likeCounter = new LikeCounter();
$postId = 123; // Assume this is the ID of a post
// User likes the post$newCount = $likeCounter->incrementLike($postId);
echo "Post $postId has $newCount likes.";

// Get the number of likes on the post$currentLikes = $likeCounter->getLikeCount($postId);
echo "Current like count for post $postId: $currentLikes";

2. Use Redis to implement speed limiter

Speed ​​limiters are used to control the frequency of an operation. Typical scenarios include limiting the frequency of users accessing the API, preventing users from frequently clicking in the snap-up system, etc. Redis'sINCRandEXPIREThis function can be easily achieved by combining it.

Example: Limiting the frequency of user API access

<?php
class RateLimiter {
    private $redis;
    private $maxRequests;
    private $timeWindow;

    public function __construct($maxRequests, $timeWindow) {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->maxRequests = $maxRequests;
        $this->timeWindow = $timeWindow;
    }

    public function isAllowed($userId, $apiEndpoint) {
        $key = "rate_limit:$userId:$apiEndpoint";
        $count = $this->redis->incr($key);

        if ($count == 1) {
            // Set expiration time            $this->redis->expire($key, $this->timeWindow);
        }

        if ($count > $this->maxRequests) {
            // Maximum number of requests exceeded            return false;
        }

        return true;
    }
}

// Example usage: Allow users to access the API up to 10 times per minute$rateLimiter = new RateLimiter(10, 60); // 10 requests, 60 seconds in time window
$userId = 123; // Assume this is the ID of a certain user$apiEndpoint = "/api/buy"; // API endpoint
if ($rateLimiter->isAllowed($userId, $apiEndpoint)) {
    echo "Request allowed.";
    // Perform API operations} else {
    echo "Too many requests. Please try again later.";
    // Reject request}

advantage

  • Efficiency: Redis's atomic operation ensures security in high concurrency environments without race conditions.
  • Scalability: Can be easily scaled to multiple servers to support larger users and operations.
  • Simplicity: Through Redis’sINCRandEXPIRECommands can easily implement complex counting and speed limit logic.

Summarize

Implementing counters and speed limiters through Redis not only improves the performance of the system, but also reduces the pressure on the database, especially in high concurrency scenarios, such as snap-ups, likes and other operations.

3. Give examples to restrict sending SMS

Restricting the frequency of SMS sending is a common mechanism to prevent abuse and avoid users being harassed. This function can be realized through Redis, and the number of times the same user sends text messages within a specific time can be effectively controlled.

Implementation ideas

We can use Redis' counter and expiration time functions to implement the function of limiting the frequency of SMS sending. The specific steps are as follows:

  • Create a unique Redis Key: The key can contain the user's ID and SMS type (such as verification code).
  • Using RedisINCRCommand increment counter: Increment the counter every time the user requests to send a SMS.
  • Set expiration time: If this is the first increment operation of the counter, set an expiration time for the Key (for example, 60 seconds).
  • Check the counter value: If the counter value exceeds the maximum allowed number of times, the SMS request is denied.

Sample code

Here is a PHP sample code that uses Redis to limit the frequency of SMS sending:

<?php
class SmsRateLimiter {
    private $redis;
    private $maxSmsRequests;
    private $timeWindow;

    public function __construct($maxSmsRequests, $timeWindow) {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->maxSmsRequests = $maxSmsRequests; // Maximum number of allowed SMS messages        $this->timeWindow = $timeWindow; // Time window (seconds)    }

    public function canSendSms($userId) {
        $key = "sms_limit:$userId";
        $count = $this->redis->incr($key);

        if ($count == 1) {
            // Set the expiration time during the first operation            $this->redis->expire($key, $this->timeWindow);
        }

        if ($count > $this->maxSmsRequests) {
            // The maximum allowed number of sends exceeds            return false;
        }

        return true;
    }
}

// Example usage: Limit each user to send up to 3 text messages every 60 seconds$smsLimiter = new SmsRateLimiter(3, 60); // 3 requests, 60 seconds in the time window
$userId = 123; // Assume this is the ID of a certain user
if ($smsLimiter->canSendSms($userId)) {
    echo "Send text message successfully";
    // Call the API for sending text messages} else {
    echo "The sending frequency is too high, please try again later";
    // Reject SMS}

This is the article about the example code of Redis to implement counters and speed limiters. For more related Redis counters and speed limiters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!