Implement Rate Limiting for API Endpoints

Implement Rate Limiting for API Endpoints

Rate limiting is crucial for protecting your API from abuse and ensuring fair usage. Here's a simple example using Redis:

function checkRateLimit($userId, $limit = 100, $period = 3600) {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    $key = "rate_limit:$userId";
    $current = $redis->get($key);

    if (!$current) {
        $redis->setex($key, $period, 1);
        return true;
    }

    if ($current > $limit) {
        return false;
    }

    $redis->incr($key);
    return true;
}

// Usage
if (!checkRateLimit('user123')) {
    header('HTTP/1.1 429 Too Many Requests');
    exit('Rate limit exceeded. Please try again later.');
}

This function checks if a user has exceeded their rate limit. Adjust the limit and period as needed for your application.

← Back to Tips List