Should I share a Redis connection between files / modules?

I am developing a node.js application and I really need to use Redis. The application will cluster ed through 8 processor cores.

Now I have 100 simultaneous connections to Redis, because each worker on one processor has several modules with require('redis').createClient() .

Scenario A:

file1.js:

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

file2.js

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

SCENARIO B:

redis.js

 var redis = require('redis').createClient(); module.exports = redis; 

file1.js

 var redis = require('./redis'); 

file2.js

 var redis = require('./redis'); 

Which approach is better: creating a new Redis instance in each new file that I present (scenario A), or creating one Redis connection worldwide (scenario B) and sharing this connection in all of my modules. What are the disadvantages / advantages of each solution?

Thanks in advance!

+8
redis
source share
2 answers

When I come across this question, I usually think of three main questions.

  • What is more readable?
  • What makes it better to reuse the code?
  • Which is more efficient?

Not necessarily in this order, since it depends on the scenario, but I believe that in this case all three questions concern option B. If you ever needed to change the settings for createClient, you will need to edit them in each file that it uses. Which in option A is every file that uses redis, and option B is only redis.js. Also, if a new or different product comes out and you want to replace redis. It would be possible to make redis.js a wrapper for another package or even a newer redis client, significantly reducing conversion time.

Globals are generally bad, but in this example redis.js should not save mutable state, so in this context there is no problem with global / singleton.

+3
source share

Both Node and Redis can handle a lot of connections pretty well, so this is not a problem.

In your situation, you create Redis connections when you start the application, so the number of connections that you configure is limited (in the sense that after the application starts, the number of connections will be constant).

Situations in which you want to use the same connection are in highly dynamic situations, for example, with an HTTP server, where you need to request Redis for each request. Creating a new connection for each request would be a waste of resources (creating and destroying connections all the time) and reusing one connection for each request would be preferable.

As for which of the two scenarios I would prefer, I am inclined to scenario A.

+1
source share

All Articles