How to (re-)use redis client connections in nodejs/express?

Bdfy picture Bdfy · Apr 30, 2013 · Viewed 7.1k times · Source

Given a simple example:

var express = require("express")
var redis = require('redis')
var app = express()

var client = redis.createClient()

app.get('/', function(req, res) {
    req.connection.setTimeout(2 * 1000)
    client.set("test", 1, function (err, resp) {
        res.send('Hello World')
    })
})

app.listen(80)

Redis connection doesn't need to be re-established for every request, does it?

Do you need to use redis connection pool?

Answer

Bryce Baril picture Bryce Baril · Nov 20, 2013

Replying to incarnate's connection pool post:

Hi there -- first clarification, Redis server IS single-threaded.

What you're seeing in terms of command ordering is an artifact of the way you're using async, and unrelated to either node_redis library or Redis itself.

Connection pooling with node_redis is definitely not required. You can certainly use it, but it is not suggested. Connection pooling will reduce the effectiveness of Redis pipelining, and due to the stateful nature of the Redis protocol, can be problematic with some commands.

Reason #1: I'm not sure this is significant, or possibly worse by creating additional clients which are an additional GC burden.

Reason #2: That's not really how it works. The Redis server is single-threaded. If you're waiting on the server, all clients are waiting on the server. If you're blocked in javascript, all clients in that process are blocked in javascript.

Reason #3: The node_redis library already reconnects after failures.