QA
Senior LevelPHP 8+

How do you implement distributed Sliding Window rate limiting in PHP microservices using Redis Lua scripts?

❓ Interview Prompt: Explain distributed rate limiting algorithms (Sliding Window Log), race conditions in separate Redis calls, and atomic Redis Lua script execution.

Executing separate Redis calls in PHP ('$redis->get()' followed by '$redis->set()') under 10,000 req/sec creates race conditions that allow attackers to bypass rate limits.

Atomic Redis Lua Scripts:

By executing a Lua script via '$redis->eval()', the entire rate-limiting algorithm (ZREMRANGEBYSCORE, ZADD, ZCARD, EXPIRE) runs atomically inside the Redis engine in a single execution step, guaranteeing 100% thread-safe rate limiting under high concurrency!

Code Implementation Example

php
<?php
// Atomic Sliding Window Rate Limiter using Redis Lua script
$luaScript = <<<LUA
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local clearBefore = now - window

redis.call('ZREMRANGEBYSCORE', key, 0, clearBefore)
local currentRequests = redis.call('ZCARD', key)

if currentRequests < limit then
    redis.call('ZADD', key, now, now)
    redis.call('EXPIRE', key, window)
    return 1
else
    return 0
end
LUA;

$allowed = $redis->eval($luaScript, ['rate:user_101', time(), 60, 100], 1);
💡Executing atomic Sliding Window rate limiting via Redis Lua script in PHP.
🎯 Interview Key Takeaway

Execute rate-limiting logic inside atomic Redis Lua scripts via $redis->eval() to prevent high-concurrency race condition bypasses.

#Rate Limiting#Redis#Lua Scripts#Concurrency#Senior
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?