Managing Key Expiration

Managing Key Expiration

Welcome back! In this lesson, we will explore a crucial feature of Redis: key expiration. This topic builds on our Redis knowledge and adds another tool to our kit for managing data efficiently in high-performance applications.

Understanding Key Expiration

Key expiration allows you to set a time limit on how long data remains in Redis. After the specified time elapses, Redis automatically removes the key and its value—you set it once, and Redis handles the cleanup for you.

Time-to-Live (TTL) is the amount of time (in seconds) that a key has left before it expires. You can check a key's TTL at any time to see how much longer it will exist.

This automatic cleanup is valuable for:

  • Session Management: User sessions expire after inactivity
  • Caching: Stale data refreshes periodically
  • Rate Limiting: API counters reset after time windows
  • Memory Management: Prevents Redis from filling up with outdated data

What You'll Learn

In this lesson, you will learn how to:

  • Set keys with automatic expiration using the SET command with the EX option
  • Check the remaining time-to-live (TTL) of a key and interpret the results
  • Apply expiration to existing keys using the EXPIRE command
  • Verify that keys expire automatically after the specified time

Let's dive in and see how to implement these concepts using Boost.Redis's asynchronous interface.

Step 1: Setting Up the Connection

First, let's establish our connection to Redis:

C++
#include <boost/redis.hpp>
#include <boost/redis/src.hpp> 
#include <boost/asio.hpp>
#include <chrono>
#include <iostream>
#include <memory>

namespace net = boost::asio;
using boost::redis::connection;
using boost::redis::config;
using boost::redis::request;
using boost::redis::logger;

int main()
{
    net::io_context ioc;
    auto conn = std::make_shared<connection>(ioc);

    config cfg;
    cfg.addr.host = "127.0.0.1";
    cfg.addr.port = "6379";

    // Start the connection
    conn->async_run(cfg, logger{logger::level::disabled},
                    net::consign(net::detached, conn));

This establishes a connection to Redis running on localhost at port 6379.

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