Managing Key Expiration in Redis

Managing Key Expiration

Welcome back! In this lesson, we will explore a crucial feature of Redis: key expiration. This builds on our Redis knowledge from previous lessons and adds another tool to our kit for managing data efficiently in high-performance applications. This is useful for various situations, such as caching data, managing session lifetimes, or any scenario where you want data to automatically expire after a certain period. We will learn how to set expiration times on keys and check the remaining time-to-live (TTL) for a key.

To set a key with an expiration time, you can use the setex method in PHP:

<?php

require 'vendor/autoload.php';

use Predis\Client;

$client = new Client();

// Set the key with a value and an expiration time of 2 seconds
$key = "session:12345";
$client->setex($key, 2, "data");

// Retrieve and print the time-to-live (TTL) for the key
$ttl = $client->ttl($key);
echo "Time-to-live for session key: {$ttl}s\n";

// Wait for the key to potentially expire
sleep(3);

// Attempt to retrieve the value of the key after the expiration time
$value = $client->get($key);
if ($value === null) {
    echo "Value: None\n"; // The key has expired as expected
} else {
    echo "Value: {$value}\n"; // Print the value if the key hasn't expired
}

The above code snippet shows how to set a key (session:12345) with a value (data) that expires after 2 seconds.

To check the remaining time-to-live (TTL) for a key, you can use the ttl method with the key name as the parameter. The ttl method can return negative values in certain cases:

  • -1: The key exists but does not have an expiration set.
  • -2: The key does not exist (it could have expired, be manually deleted or it never existed).

After waiting for the expiration time, you can verify that the key no longer exists. This code waits 3 seconds and then attempts to get the value of the key, which should indicate that the key has expired.

Another useful method is expire, which allows you to set the expiration time for a key after it has been created:

// Set the key with a value and no expiration initially
$key = "session:12345";
$client->set($key, "data");

// Set an expiration time of 2 seconds for the key
$client->expire($key, 2);

// Retrieve and print the time-to-live (TTL) for the key
$ttl = $client->ttl($key);
echo "Time-to-live for the key: {$ttl}s\n";

This code snippet sets the key session:12345 with a value (data) and then sets the expiration time to 2 seconds. We will explore this method in more detail in the practice section.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal