What You'll Learn

You will learn how to set expiration times on your Redis keys. This is useful for many situations, such as caching data, managing session lifetimes, or any scenario where you want data to expire automatically 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.

Here's a quick preview of what you will be doing:

To set a key with an expiration time, you can use the set command with the EX option:

import Redis from 'ioredis';

// Connect to Redis
const client = new Redis('redis://localhost:6379');

client.on('error', (err) => {
  console.error('Error connecting to Redis', err);
});

const key = 'session:12345';

async function run() {
  await client.set(key, 'data', 'EX', 2);

  const ttl = await client.ttl(key);
  console.log(`Time-to-live for session key: ${ttl} seconds`);

  setTimeout(async () => {
    const value = await client.get(key);
    console.log(`Value: ${value}`);  // null
    client.disconnect();
  }, 3000);
}

run();

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 command with the key name as the parameter.

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 return null because the key has expired.

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

import Redis from 'ioredis';

// Connect to Redis
const client = new Redis('redis://localhost:6379');

client.on('error', (err) => {
  console.error('Error connecting to Redis', err);
});

const key = 'session:12345';

async function run() {
  await client.set(key, 'data');
  await client.expire(key, 2);

  const ttl = await client.ttl(key);
  console.log(`Time-to-live for session key after setting expire: ${ttl} seconds`);

  client.disconnect();
}

run();

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

The client.expire(key, seconds) method is especially useful when you need to update or extend the TTL of an existing key after it’s been created. For example, in user session handling, if a user remains active, you might want to reset the expiration time to avoid logging them out prematurely. This pattern is common in authentication systems where each user interaction extends the session validity (often called “sliding expiration”).

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