0
0
Redisquery~30 mins

Rate limiter with INCR and EXPIRE in Redis - Mini Project: Build & Apply

Choose your learning style9 modes available
Rate limiter with INCR and EXPIRE
📖 Scenario: Your API is getting hammered by bots. You need to limit each user to 100 requests per minute using Redis. You'll build a rate limiter that uses INCR to count requests and EXPIRE to reset the window.
🎯 Goal: Build an atomic rate limiter using Redis INCR, EXPIRE, and a Lua script to prevent race conditions.
📋 What You'll Learn
Create a rate limit key for a user
Increment the counter and set expiry
Check if the user exceeded the limit
Make the operation atomic with a Lua script
💡 Why This Matters
🌍 Real World
Redis rate limiters protect APIs at companies like GitHub, Stripe, and Cloudflare from abuse and ensure fair usage across clients.
💼 Career
Backend engineers implement rate limiting in almost every production API to prevent abuse, manage costs, and ensure service stability.
Progress0 / 4 steps
1
Increment the rate limit counter
Use INCR to increment the key rate_limit:user:42. This creates the key with value 1 if it doesn't exist, or increments it if it does.
Redis
Need a hint?

INCR creates the key with value 1 if it doesn't exist, or adds 1 to the current value.

2
Set the expiry window
Use EXPIRE to set a 60-second TTL on the key rate_limit:user:42 so the counter resets every minute.
Redis
Need a hint?

EXPIRE key seconds — sets the key to auto-delete after the given number of seconds.

3
Check if limit exceeded
Use GET to read the current count from rate_limit:user:42. In your application, you would compare this value against the limit of 100.
Redis
Need a hint?

GET returns the current value of the key as a string.

4
Make it atomic with Lua
Write an EVAL Lua script that: calls redis.call('INCR', KEYS[1]) and stores in local count, then if count == 1 calls redis.call('EXPIRE', KEYS[1], ARGV[1]), and returns count. Pass 1 key rate_limit:user:42 and 1 arg 60.
Redis
Need a hint?

EVAL runs a Lua script atomically. KEYS[1] is the first key argument, ARGV[1] is the first non-key argument.