0
0
Redisquery~5 mins

Temporary data with TTL in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Temporary data with TTL
O(1)
Understanding Time Complexity

We want to understand how the time to set temporary data with expiration changes as we add more data.

How does Redis handle the time cost when we add keys that expire automatically?

Scenario Under Consideration

Analyze the time complexity of the following Redis commands.


SET user:1000 "Alice" EX 60
SET user:1001 "Bob" EX 60
SET user:1002 "Carol" EX 60

GET user:1000
DEL user:1001
    

This code sets keys with a time-to-live (TTL) of 60 seconds, then reads and deletes keys.

Identify Repeating Operations

Look for repeated actions that affect time.

  • Primary operation: Setting keys with expiration (SET with EX option)
  • How many times: Once per key added, each key has its own expiration timer
How Execution Grows With Input

As you add more keys with TTL, each SET command takes about the same time.

Input Size (n)Approx. Operations
1010 SET commands, each quick
100100 SET commands, each still quick
10001000 SET commands, each similar speed

Pattern observation: Time per SET stays about the same no matter how many keys exist.

Final Time Complexity

Time Complexity: O(1)

This means setting a key with TTL takes about the same time no matter how many keys are stored.

Common Mistake

[X] Wrong: "Setting a key with expiration gets slower as more keys with TTL exist."

[OK] Correct: Redis manages expirations efficiently, so each SET with TTL runs in constant time regardless of total keys.

Interview Connect

Knowing that setting temporary data with TTL is fast helps you design systems that rely on quick expiration without slowing down as data grows.

Self-Check

"What if we used a Lua script to set multiple keys with TTL in one call? How would the time complexity change?"