Python Redis Expire

09.12.2021

Intro

Expiring keys allows you to set automatic time limits for keys in Redis. When you set a TTL (time to live), Redis will clean up and remove the key when time has run out. This can be helpful for ensuring we don't waste resources on old data that is not accessed often. In this article, we will learn how to set expiration on keys in Redis with Python.

Managing TTL will save you money in the long run, so be sure to have a strategy in placed. Using redis has an LRU (Least Recently Used) cache is also a good starting palce for redis applications.

Setting up Redis

For setting up Redis, I would recommend using a service for you in prod. Azure for example, has a great redis service that scales easily. However, you will want to learn redis and eventually how to scale it yourself. This will help with debugging cloud services or eventually, saving money and not using them.

We will start our intro to redis via using docker compose. Create a docker-compose.yml file and add the following.

version: "3.2"
services:
  redis:
    image: "redis:alpine"
    command: redis-server
    ports:
      - "6379:6379"
    volumes:
      - $PWD/redis-data:/var/lib/redis
      - $PWD/redis.conf:/usr/local/etc/redis/redis.conf
    environment:
      - REDIS_REPLICATION_MODE=master

Ensure you have docker installed and run

docker-compose up

Installing Redis Modules

In python, the main used redis module is called redis-py and can be installed using the follows.

pip install redis

Writing the Code

Let's open up a new file, index.py and add an transaction example.

We start by connecting to our redis instance.

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

To start, we can set a key in redis.

r.set('my-web-page', 'web page content')

Now, to expire, we can use the expire method with our key and the number of seconds to keep it alive. Let's also import the time library to see how this is used.

import time

r.expire('my-web-page', 2) # 2 second expire time
time.sleep(2)
r.get('my-web-page') # null

If you would like to see how long a key has, you can use the ttl function.

r.expire('my-web-page', 2) # 2 second expire time
r.ttl('my-web-page') # 2

You can also remove an expire using the persist method.

r.expire('my-web-page', 2) # 2 second expire time
r.persist('my-web-page') # no long has ttl