skip to Main Content

I am trying to find the best practice to use redis client with express server, for somehow I don’t know whether to create a redis client each time or reuse the global redis client.

The first method is to create only one redis client, reuse it in each request.

const redis = require("redis").createClient();
function createExample(req, res){
    try {
        await redis.connect();
        ... to do more
    } catch(err) {
        console.log("Err:", err);
    }
    await redis.disconnect();
    req.json({'msg':'success'});
}

The second example is to create redis client every time the request comes.

function createExample2(req, res){
    const redis = require("redis").createClient();
    try {
        await redis.connect();
        ... to do more
    } catch(err) {
        console.log("Err:", err);
    }
    await redis.disconnect();

    req.json({'msg':'success'});
}

which method is more reasonable, any idea?

2

Answers


  1. I always create a single connection. I have two reasons:

    1. Redis connections are not free to create. Creating one for each call is significantly slower. Keeping one around makes for faster responses.

    2. Both Node.js and Redis are single-threaded. Given Redis’ quick response times, there typically isn’t more than one thing at a time in a Node.js process trying to get to Redis. And if there is—say because your code is waiting on a response from a long-running Redis command, the type of commands that should be avoid anyhow—it couldn’t do anything anyhow as it would have to wait on the single thread in Redis.

    There are certainly exceptions to this, but I think for most cases, this is the way to go. I wouldn’t go so far as to say that this is the official stance of Redis, but I work for them as a developer advocate and this is how I build all my sample code.

    Login or Signup to reply.
  2. which method is more reasonable, any idea?

    It depends. I would suggest re-using the same single connection to Redis if the code obeys these rules:

    1. it is using non-blocking commands only;
    2. it is not changing the connection state by issuing commands which change it (e.g. SELECT and everything else mentioned here);
    3. it is not using pub/sub in that specific connection (which you may however duplicate just for that, if needed).

    In all the other cases, using dedicated connections may be a better option.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search