0
0
Redisquery~5 mins

SET with expiry (EX, PX) in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SET with expiry (EX, PX)
O(1)
Understanding Time Complexity

We want to understand how the time it takes to run a Redis SET command with an expiry changes as we add more data.

Specifically, we ask: does setting a key with expiration take longer when the database grows?

Scenario Under Consideration

Analyze the time complexity of the following Redis commands.


SET mykey "Hello" EX 10
SET anotherkey "World" PX 5000
    

These commands set keys with expiration times in seconds (EX) and milliseconds (PX).

Identify Repeating Operations

Look for any repeated work inside the command execution.

  • Primary operation: Storing the key and value, and scheduling the expiration.
  • How many times: Each command runs once per key set; no loops or repeated traversals inside the command.
How Execution Grows With Input

The time to set a key with expiry stays about the same no matter how many keys are in the database.

Input Size (n)Approx. Operations
10Constant time to set and schedule expiry
100Still constant time per command
1000Still constant time per command

Pattern observation: The work does not grow with the number of keys; it stays steady.

Final Time Complexity

Time Complexity: O(1)

This means setting a key with an expiry takes the same amount of time regardless of how many keys are stored.

Common Mistake

[X] Wrong: "Setting a key with expiry takes longer as the database grows because Redis must check all keys for expiration."

[OK] Correct: Redis handles expirations efficiently using internal data structures, so setting a key with expiry is a quick, direct operation.

Interview Connect

Knowing that setting keys with expiry is fast and does not slow down as data grows helps you design efficient caching and session systems.

Self-Check

"What if we used a command that scans all keys to set expiry instead? How would the time complexity change?"