Setting Expiry in Redis

Joseph Khan
tajawal
Published in
3 min readMay 22, 2020

This article features a video on Setting Expiry in Redis. So, we will learn how you can set an expiry time to your Redis keys.

Setting Expiry in Redis

What is Redis?

Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. It is highly reliable, scalable, and has high availability.

Redis can be used to cache content — database queries that are supposed to be used by users, for eg. Flight Search Results (of course with an expiry time), static content like HTML, JS, CSS. Redis is also highly used as a Session Store. Unique user sessions are stored in Redis. Rather than making roundtrips to Databases on the disk, reading and writing user sessions in Redis is faster.

Setting Expiry to Redis keys

Some useful commands

Here are a few useful commands that you will be using very commonly,

  1. Get All Keys
keys *

2. Get a particular key’s value

get key_name

3. Set a key with a value

set key_name value

4. Delete a key

del key_name

5. Set key with expiry in seconds. (Expire after 60secs)

set key_name value EX 60

You can also use ex in place of EX.

6. Set key with expiry in milliseconds. (Expire after 6secs = 6000ms)

set key_name value PX 6000

You can also use px in place of PX.

7. Flush the Database. Kill all keys.

flushdb

8. Get Database size. Total no of active keys

dbsize

9. Check expiry time left for a key. In seconds.

ttl key_name

Setting expiry in Redis

You can use the EX and PX modifiers in your Redis commands. Watch the video below where I cover it in detail.

In case you are using a Redis client in a Node Express server, then you can set the expiry to your keys in pretty much the same way.

So, for the example shown below, I am using node-redis module, which is a high-performance Node.js Redis client.

Once you have your Node Redis client connected to your Redis instance,

//connect to Redis 
const redisClient = redis.createClient({
port: REDIS_PORT,
host: REDIS_HOST,
});

You can set keys in Redis with expiry as shown below, I am setting an expiry time of 10mins to my key users.

redisClient.set('users', JSON.stringify(users), 'EX', 10*60, (err) => { 
//cache for 10mins
if(err) {
return res.status(500).send('Server error');
}

//other operations will go here
//probably respond back to the request
});

Anyways watch the video which will give you an idea of the topic that I am discussing in this article.

Have a Good Day! Cheers!

Reference

Official Redis CLI Commands — link.

Originally published at https://josephkhan.me on May 22, 2020.

--

--

Joseph Khan
tajawal
Writer for

Engineering Manager | Author & Speaker. I work with one of the largest OTA (Online Travel Agencies) in the Middle East https://josephkhan.me/