Node Redis Expire

09.13.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 Nodejs.

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

There are two modules I see often used in nodejs. I will tend towards ioredis as it has built in support for promises and many other features in redis.

npm install ioredis

Writing the Code

Let's open up a new file, index.js. To use pipelining, we first a pipeline instance.

We start by connecting to our redis instance.

const Redis = require("ioredis")

const redis = new Redis()

To start, we can set a key in redis.

await redis.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 create a sleep function to wait the expiration time.

function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

await redis.expire('my-web-page', 2) // 2 second expire time
await sleep(2)
await redis.get('my-web-page') // null

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

await redis.set('my-web-page', 'web page content')
await redis.expire('my-web-page', 2) // 2 second expire time
await redis.ttl('my-web-page') #//2

You can also remove an expire using the persist method.

await redis.set('my-web-page', 'web page content')
await redis.expire('my-web-page', 2) // 2 second expire time
await redis.persist('my-web-page') // no long has ttl