0
0
RedisHow-ToBeginner · 4 min read

How to Implement Rate Limiter Using Redis Efficiently

You can implement a rate limiter in Redis by using commands like INCR and EXPIRE to count requests per user within a time window. Increment a key for each request and set an expiration to reset the count after the time window, blocking requests when the count exceeds the limit.
📐

Syntax

To implement a rate limiter, use these Redis commands:

  • INCR key: Increments the count for the given key.
  • EXPIRE key seconds: Sets a time-to-live for the key to reset the count.
  • GET key: Retrieves the current count.

The key usually combines user ID and time window to track requests per user per period.

redis
INCR user:123:requests
EXPIRE user:123:requests 60
GET user:123:requests
Output
1 OK 1
💻

Example

This example shows a simple Lua script in Redis that increments a request count and blocks requests exceeding 5 per minute.

lua
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local current = redis.call('INCR', key)
if current == 1 then
  redis.call('EXPIRE', key, 60)
end
if current > limit then
  return 0
else
  return 1
end
Output
1
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting EXPIRE, causing counts to never reset.
  • Using a global key instead of per-user keys, blocking all users together.
  • Not handling race conditions in high concurrency; Lua scripts help atomicity.
redis
Wrong:
INCR requests

Right:
INCR user:123:requests
EXPIRE user:123:requests 60
📊

Quick Reference

Rate Limiter Commands Cheat Sheet:

CommandPurpose
INCR keyIncrement request count for the key
EXPIRE key secondsSet expiration time to reset count
GET keyGet current request count
DEL keyDelete key to reset manually
Lua ScriptAtomic check and increment

Key Takeaways

Use INCR and EXPIRE commands to count and reset requests per user.
Always set expiration on keys to avoid permanent blocking.
Use per-user keys to track limits individually.
Lua scripts ensure atomic increments and checks under concurrency.
Test your rate limiter to avoid blocking legitimate users.