0
0
Redisquery~5 mins

EXPIRE and TTL for time-to-live in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: EXPIRE and TTL for time-to-live
O(1)
Understanding Time Complexity

When using Redis commands like EXPIRE and TTL, it's important to know how their speed changes as your data grows.

We want to understand how long these commands take when you have many keys or set many expirations.

Scenario Under Consideration

Analyze the time complexity of the following Redis commands.


SET session:user123 "data"
EXPIRE session:user123 3600
TTL session:user123
    

This code sets a key, assigns it a time-to-live of one hour, and then checks how much time is left before it expires.

Identify Repeating Operations

Look for any repeated steps or loops inside these commands.

  • Primary operation: Checking or setting expiration on a single key.
  • How many times: Each command works on one key at a time, no loops over multiple keys.
How Execution Grows With Input

These commands handle one key at a time, so their work does not increase with the total number of keys.

Input Size (n)Approx. Operations
10 keysSame small number of steps per command
100 keysStill same small number of steps per command
1000 keysNo increase in steps per command

Pattern observation: The time to run EXPIRE or TTL stays about the same no matter how many keys exist.

Final Time Complexity

Time Complexity: O(1)

This means setting or checking expiration takes the same short time regardless of how many keys you have.

Common Mistake

[X] Wrong: "Checking TTL gets slower as I add more keys because Redis must look through all keys."

[OK] Correct: Redis stores expiration info efficiently, so TTL only checks one key directly without scanning others.

Interview Connect

Knowing that EXPIRE and TTL run in constant time helps you explain how Redis handles time-based data efficiently, a useful skill in many real projects.

Self-Check

"What if we wanted to set expiration on many keys at once? How would that affect the time complexity?"