Learnitweb

Setting and Managing Key Expiration in Redis

In this lecture, we will explore how to set an expiration time (or TTL — Time To Live) for a key in Redis. We will also see how to extend the expiry and how to retrieve the remaining lifetime of a key programmatically.


1. Setting Expiration for a Key

So far, we have been creating keys and storing values in Redis without specifying how long they should live. By default, any key you create in Redis persists until you explicitly delete it. However, in many real-world scenarios — such as session management, cache data, or temporary tokens — we want the key to automatically expire after a certain period.

Let’s modify our earlier test to add an expiry.

Example: Setting Key Expiry

We can start by copying our earlier test that creates a simple key-value pair and then update it to include an expiration time.

@Test
public void expiryTest() {
    RBucket<String> bucket = redisson.getBucket("user:1:name", StringCodec.INSTANCE);
    bucket.set("Sam", 10, TimeUnit.SECONDS);
}

Here’s what’s happening:

  • We are setting the key "user:1:name" with a value of "Sam".
  • We specify a TTL of 10 seconds using TimeUnit.SECONDS.

Once this code executes, the key will automatically expire after 10 seconds, and Redis will remove it from memory.


2. Verifying the Key Expiry in Redis

After running the test, we can open the Redis CLI and check whether the key exists.

127.0.0.1:6379> GET user:1:name
"Sam"

If you check immediately, you will see the value "Sam".
But after about 10 seconds, if you check again:

127.0.0.1:6379> GET user:1:name
(nil)

The key is gone — it has expired.


3. Extending Expiry Dynamically (Session Renewal Example)

Sometimes, we may need to extend the expiration time dynamically.
For example, imagine a user session token that expires after 5 minutes. If the user remains active and continues sending requests, we want to extend that session automatically. If the user becomes inactive, the session should expire naturally.

Let’s simulate that behavior.

Example: Extending Expiry of a Key

@Test
public void extendExpiryTest() throws InterruptedException {
    RBucket<String> bucket = redisson.getBucket("user:1:name", StringCodec.INSTANCE);
    
    // Step 1: Set initial expiry
    bucket.set("Sam", 10, TimeUnit.SECONDS);

    // Step 2: Sleep for 5 seconds to simulate time passing
    Thread.sleep(5000);

    // Step 3: Extend expiry by another 60 seconds
    boolean result = bucket.expire(60, TimeUnit.SECONDS);
    Assertions.assertTrue(result);

    System.out.println("Expiry extended successfully");
}

Explanation:

  • We initially set the key’s TTL to 10 seconds.
  • Then we wait for 5 seconds to simulate elapsed time.
  • Before the key expires, we call bucket.expire(60, TimeUnit.SECONDS) to extend its lifetime to 60 seconds.
  • The method returns true if the expiry update was successful.

Now, when you check the key’s TTL in Redis after this code runs, you’ll see that the expiration has been extended.


4. Checking the Key’s TTL (Time To Live)

Redis allows us to query the remaining lifetime of any key.
This can be useful if your business logic needs to check how long a session, cache entry, or temporary key will remain valid.

You can do this programmatically using:

@Test
public void timeToLiveTest() {
    RBucket<String> bucket = redisson.getBucket("user:1:name", StringCodec.INSTANCE);
    bucket.set("Sam", 30, TimeUnit.SECONDS);

    long ttl = bucket.remainTimeToLive();
    System.out.println("Time to live (ms): " + ttl);
}

Key points:

  • The remainTimeToLive() method returns the remaining TTL in milliseconds.
  • You can use this information to make decisions in your application logic.
    For example, if the TTL is below a certain threshold, you might automatically refresh or extend the session.

5. Practical Example: Session Token Management

Here’s how this concept applies in a real-world scenario:

  • When a user logs in, you generate a session token and store it in Redis with a TTL of 5 minutes.
  • Each time the user sends a valid request, you check the TTL:
    • If TTL < 1 minute → extend it by another 5 minutes.
    • If no request is received for 5 minutes → let the key expire naturally.
  • This mechanism ensures that active users remain logged in, while inactive users automatically expire without manual cleanup.

6. CLI Verification

To verify the expiration time from Redis CLI, you can use the TTL command:

127.0.0.1:6379> TTL user:1:name
53

The returned value (53) indicates the number of seconds remaining before expiration.
If the value is -1, it means the key has no expiry.
If it’s -2, it means the key has already expired or doesn’t exist.


7. Summary

In this tutorial, we learned how to:

  1. Set an expiry for a Redis key using set(value, duration, TimeUnit).
  2. Extend or modify a key’s expiry dynamically using expire().
  3. Retrieve the remaining TTL of a key programmatically using remainTimeToLive().
  4. Apply these concepts to practical use cases like user session management or cache expiration.

Understanding and controlling key expiration is a fundamental part of designing scalable and memory-efficient Redis-based systems. It allows your application to automatically manage temporary data without manual cleanup.