Bird
Raised Fist0
Redisquery~3 mins

Why Rate limiting with sliding window in Redis? - Purpose & Use Cases

Choose your learning style10 modes available
The Big Idea

What if you could stop spammy users instantly without slowing down your whole system?

The Scenario

Imagine you run a popular website where users can send messages. Without any control, some users might send too many messages in a short time, overwhelming your system and annoying others.

You try to count messages manually by checking timestamps one by one in a list, but it quickly becomes confusing and slow as the list grows.

The Problem

Manually tracking each user's message times means scanning long lists every time to see if they are allowed to send more messages.

This is slow, uses lots of memory, and can easily make mistakes if you miss cleaning old timestamps.

It also doesn't handle bursts of messages well, causing unfair blocking or letting some users flood the system.

The Solution

Rate limiting with a sliding window uses Redis to efficiently track user actions within a moving time frame.

It automatically keeps only recent timestamps and quickly counts them to decide if a user can proceed.

This method is fast, fair, and uses little memory, preventing overload and abuse smoothly.

Before vs After
✗ Before
timestamps = []
# On each message:
now = current_time()
timestamps = [t for t in timestamps if t > now - window]
if len(timestamps) < limit:
    timestamps.append(now)
    allow()
else:
    block()
✓ After
redis.zremrangebyscore(key, 0, now - window)
count = redis.zcard(key)
if count < limit:
    redis.zadd(key, {now: now})
    allow()
else:
    block()
What It Enables

This lets your system fairly and efficiently control how often users can act, protecting resources and improving user experience.

Real Life Example

A chat app uses sliding window rate limiting to stop users from sending more than 5 messages every 10 seconds, preventing spam while allowing natural conversation flow.

Key Takeaways

Manual counting of actions is slow and error-prone.

Sliding window rate limiting uses Redis sorted sets to track recent actions efficiently.

This method ensures fair, fast, and memory-friendly control of user activity.

Practice

(1/5)
1. What is the main purpose of using a sliding window in rate limiting with Redis?
easy
A. To count actions within a moving time frame for fair limits
B. To store user passwords securely
C. To permanently block users after one action
D. To sort data alphabetically

Solution

  1. Step 1: Understand sliding window concept

    Sliding window rate limiting counts actions in a recent time frame that moves forward as time passes.
  2. Step 2: Identify purpose in Redis context

    Redis uses sorted sets to track timestamps of actions to enforce limits fairly over time.
  3. Final Answer:

    To count actions within a moving time frame for fair limits -> Option A
  4. Quick Check:

    Sliding window = moving time frame count [OK]
Hint: Sliding window means counting recent actions, not all time [OK]
Common Mistakes:
  • Thinking sliding window blocks permanently
  • Confusing with password storage
  • Assuming it sorts data alphabetically
2. Which Redis command is essential to add a timestamp to a sorted set for sliding window rate limiting?
easy
A. ZADD
B. GET
C. HSET
D. LPUSH

Solution

  1. Step 1: Identify command to add to sorted set

    ZADD adds members with scores (timestamps) to a sorted set in Redis.
  2. Step 2: Confirm other commands' purpose

    GET retrieves string values, HSET sets hash fields, LPUSH adds to lists, none add to sorted sets.
  3. Final Answer:

    ZADD -> Option A
  4. Quick Check:

    ZADD adds to sorted set [OK]
Hint: Use ZADD to add timestamps to sorted sets [OK]
Common Mistakes:
  • Using GET which only reads strings
  • Confusing HSET (hashes) with sorted sets
  • Using LPUSH which is for lists
3. Given this Redis Lua script snippet for sliding window rate limiting:
local now = tonumber(redis.call('TIME')[1])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count < limit then
  redis.call('ZADD', key, now, now)
  return 1
else
  return 0
end

What will be the return value if the current count is equal to the limit?
medium
A. 1
B. nil
C. 0
D. An error

Solution

  1. Step 1: Analyze the condition count < limit

    If count is equal to limit, the condition count < limit is false.
  2. Step 2: Determine return value when condition is false

    When false, the script returns 0, indicating rate limit reached.
  3. Final Answer:

    0 -> Option C
  4. Quick Check:

    count == limit returns 0 [OK]
Hint: If count equals limit, return 0 (limit reached) [OK]
Common Mistakes:
  • Assuming count == limit returns 1
  • Expecting an error instead of 0
  • Thinking nil is returned
4. You have this Redis Lua script for sliding window rate limiting:
local now = tonumber(redis.call('TIME')[1])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count <= limit then
  redis.call('ZADD', key, now, now)
  return 1
else
  return 0
end

What is the bug in this script?
medium
A. ZREMRANGEBYSCORE is used incorrectly
B. Using <= allows one extra request beyond limit
C. ZADD should use a string member, not number
D. TIME command returns a string, not number

Solution

  1. Step 1: Check condition count <= limit

    This condition allows adding a request when count equals limit, exceeding limit by one.
  2. Step 2: Verify other commands usage

    ZREMRANGEBYSCORE usage is correct to remove old timestamps; ZADD accepts numbers as members; TIME returns array with string seconds converted to number.
  3. Final Answer:

    Using <= allows one extra request beyond limit -> Option B
  4. Quick Check:

    count <= limit allows limit+1 requests [OK]
Hint: Use < not <= to enforce strict limit [OK]
Common Mistakes:
  • Thinking ZREMRANGEBYSCORE is wrong here
  • Believing ZADD can't use numbers as members
  • Confusing TIME return type
5. You want to implement a sliding window rate limiter in Redis that allows 100 requests per 60 seconds. Which sequence of Redis commands best enforces this limit efficiently?
hard
A. HSET to store count, GET to read count, INCR to increment count
B. LPUSH to add timestamp, LLEN to count, LTRIM to remove old timestamps
C. SETNX to set a flag, EXPIRE to reset after 60 seconds
D. ZREMRANGEBYSCORE to remove old timestamps, ZCARD to count, ZADD to add current timestamp

Solution

  1. Step 1: Understand sliding window enforcement

    Use sorted sets to store timestamps, remove old ones, count current requests, and add new timestamp.
  2. Step 2: Evaluate each option's commands

    ZREMRANGEBYSCORE to remove old timestamps, ZCARD to count, ZADD to add current timestamp uses ZREMRANGEBYSCORE, ZCARD, ZADD correctly for sliding window. LPUSH to add timestamp, LLEN to count, LTRIM to remove old timestamps uses lists which are less efficient for range removals. HSET to store count, GET to read count, INCR to increment count uses hashes and counters, not suitable for sliding window. SETNX to set a flag, EXPIRE to reset after 60 seconds uses simple flags, not counting requests.
  3. Final Answer:

    ZREMRANGEBYSCORE, ZCARD, ZADD sequence -> Option D
  4. Quick Check:

    Sorted sets + remove old + count + add = correct [OK]
Hint: Use sorted sets with ZREMRANGEBYSCORE, ZCARD, ZADD [OK]
Common Mistakes:
  • Using lists which are inefficient for sliding windows
  • Using counters without timestamps
  • Using flags without counting requests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard