Learnitweb

Redis Expiry and TTL (Time-To-Live)

In this session, we will explore one of Redis’s most powerful features — key expiration.
Expiration allows Redis to automatically remove keys after a specified duration, so you don’t have to delete them manually.
This feature is widely used in session management, caching, and temporary data handling in distributed applications.


1. Setting Expiry for Keys

Redis allows you to assign an expiry time when creating a key. Once that time elapses, Redis automatically deletes the key.

Syntax:

SET key value EX <seconds>

Example:

SET a "b" EX 10

This sets a key a with the value b, and Redis will automatically remove this key after 10 seconds.

Verification:

GET a

If you check immediately after setting it, you’ll get:

"b"

But if you check after 10 seconds:

(nil)

The key has expired and has been deleted by Redis automatically.


2. Checking Key Expiry Time (TTL)

You can check how much time is left before a key expires using the TTL (Time-To-Live) command.

Example:

SET d "test" EX 5
TTL d

Possible results:

  • A positive number → remaining time (in seconds) before expiration
  • -2 → key has already expired
  • -1 → key exists but has no expiry set

For example:

TTL d
(integer) 5
TTL d
(integer) 2
TTL d
(integer) -2  # means key no longer exists

3. Extending or Modifying Expiry Time

You can extend the lifetime of a key using the EXPIRE command.

Example:

SET a "b" EX 10
EXPIRE a 60

Now, key a will expire in 60 seconds instead of 10.

You can keep extending it:

EXPIRE a 600

Now the key will last 600 seconds (10 minutes).

You can verify the remaining lifetime again using:

TTL a

4. Using Expiry for Session Management

One of the most common use cases for Redis expiry is user session management in web applications.

Example Scenario:

Suppose your application has multiple instances behind a load balancer:

  • When a user logs in, the application generates a token.
  • You store that token in Redis: SET user:Sam:token <token_value> EX 180 (valid for 3 minutes)

Any application instance can then:

  • Check Redis to validate the token for subsequent requests.
  • Once the expiry time is reached, Redis automatically removes the token.
  • The user session becomes invalid, and the application prompts for re-login.

This ensures consistent session management across multiple servers without manual cleanup.


5. Real-World Example: Expiry in Action

Redis expiration is not just for sessions — it is also useful in many time-bound scenarios.

Example 1: Movie Rental System

Suppose a user rents a movie for 6 hours.

  • You store this information in Redis: SET user:Sam:movie "Inception" EX 21600 (6 hours = 21,600 seconds)
  • Once the time expires, Redis removes the key automatically, and the user’s access to the movie is revoked.

Example 2: Seat Booking System

Imagine an online cinema booking system:

  • When a user selects a seat, you temporarily reserve it: SET seat:D10 "booked" EX 300 (reserved for 5 minutes)
  • During that time, other users cannot select the same seat.
  • If the user does not complete the payment within 5 minutes, the key expires, and the seat becomes available again.

This behavior prevents conflicts and ensures fairness.


6. Expiry Using Unix Timestamps

Instead of specifying seconds, you can set expiry using a specific timestamp using the EXAT option.

Example:

SET a "b" EXAT 1733940000

This means the key will expire exactly at the given Unix timestamp.

You can confirm this by checking:

TTL a

Redis will show the remaining seconds until expiration.


7. Expiry in Milliseconds Precision

Redis also supports millisecond-level expiration for higher precision.

Syntax:

SET key value PX <milliseconds>

Example:

SET b "c" PX 3000

This sets key b to expire after 3 seconds (3000 milliseconds).

After 3 seconds, if you check:

GET b

You will get (nil) because the key has expired.


8. Effect of Updating a Key on Expiry

When you update a key’s value, Redis removes any existing expiry unless you explicitly tell it to keep it.

Example (without keeping expiry):

SET a "b" EX 60
SET a "c"
TTL a

You’ll get:

(integer) -1

This means the key no longer has an expiry — it will persist indefinitely.

Why?

Because by default, Redis treats the SET command as a full replacement of the key and removes any previously set expiry.


9. Preserving Expiry When Updating Keys

To retain the expiry while updating a key’s value, use the KEEPTTL option.

Example:

SET a "b" EX 60
SET a "c" KEEPTTL
TTL a

Output:

(integer) 41

The expiry remains intact, but the value has been updated to "c".

This is very useful when you want to update a cached value but still respect the original expiration policy.


10. Summary of Expiry Commands

CommandDescriptionExample
SET key value EX secondsSets a key with expiry in secondsSET a b EX 10
SET key value PX millisecondsSets expiry in millisecondsSET b c PX 3000
SET key value EXAT timestampExpires at an exact Unix timestampSET a b EXAT 1733940000
EXPIRE key secondsUpdates expiry in secondsEXPIRE a 60
TTL keyShows remaining timeTTL a
SET key value KEEPTTLUpdates value without removing expirySET a c KEEPTTL

11. Conclusion

Redis expiration is an essential feature that allows you to:

  • Automatically clean up temporary data
  • Manage sessions efficiently across distributed systems
  • Implement real-world scenarios like booking systems or limited-time offers

By combining EX, PX, EXAT, TTL, and KEEPTTL, you can precisely control data lifetime, reduce manual cleanup, and maintain predictable application behavior.