6

I'm building a node.js server, with a simple authentication fetching uid and key in a redis database. Should I connect to the redis db once and for all upon running the server, like:

var http = require('http'),
    express = require('express');

var app = express();

var redis = require('redis'),
    redisclient = redis.createClient();

//... redis ready, error, end callback handlers here ...

app.get( '/connect/:uid/:key', function(req,res,next) {
   redisclient.hget(req.params.uid,req.params.key, function(err,rep) {
      // ... commands here...
      });
   });

or should I connect each time a connection request is done, like so:

var http = require('http'),
    express = require('express');

var app = express();

var redis = require('redis');

app.get( '/connect/:uid/:key', function(req,res,next) {
   var redisclient = redis.createClient();
   //... redis callback handlers here...
   redisclient.hget(req.params.uid,req.params.key, function(err,rep) {
      // ... commands here...
      });
   });

?

For now I'm talking about a limited number of connections, sparse in time, and no worries about efficiency optimisation.

nenj
  • 119
  • 9

2 Answers2

1

I had the same confusion at some point but couldn't find any good answer. At the end I chose connecting just once to reduce lines of code. Redis mostly follows single threaded design so connection pooling won't be much help either.

Dipen Bhikadya
  • 3,318
  • 3
  • 21
  • 19
  • Yes, I'll follow your path. A similar question was actually asked, and replied like you did: http://stackoverflow.com/questions/11009880/should-i-create-a-new-redis-client-for-each-connection – nenj Jan 31 '14 at 13:24
  • A single connection is sufficient in certain cases. If you're using transaction commands such as `WATCH`, `MULTI`, `EXEC`, you will need a separate connection for each incoming request for correctness. – nishanthshanmugham Aug 03 '20 at 15:26
0

You should not do both... Ideally you should have a connection pool.. Lets say 20 connection pool which should be reused.

If you connect on every request then its not good performance wise and also many TCP connection from your application to redis will be in TIMEWAIT status even if you close them.

If you have only one connection then its like you are driving a car on single lane road where network will get conjusted

I am not very sure but I think hiredis (node module) has connection pooling...

Jack Daniel's
  • 2,583
  • 22
  • 28
  • I'm not really worried about a large number of connections, so pooling won't be necessary. Thanks for your reply – nenj Jan 31 '14 at 13:25