Callum Rogers
Callum Rogers

Reputation: 15819

Better to have a single, global connection to memcached/mongo from node or connections on every request?

I am (re)writing an api from php to node that has extremely high usage; it uses memcached and currently connects to memcached, does its business and closes afterwards every time the php file run, ie every time the api page is accessed.

Now with node, we are building the http server itself; I could define a global memcached connection and use that:

var mclient = new memcache.Client(server, port);

// This would only run after mclient has connected 
http.createServer(function (req,res){
    // stuff involving mclient
}).listen(8888);

or I could put it inside the createServer callback. The same question also applies to mongodb connections. Which should I do?

Upvotes: 1

Views: 707

Answers (2)

mstearn
mstearn

Reputation: 4276

I would suggest using a pool of more than one connection. This will allow multiple in-flight operations at once while saving you the overhead of the TCP handshake / rate-limiting and application-level handshaking (such as log-in) that comes when you create new connections.

I don't know about memcached, but I think the node-native-driver for MongoDB (https://github.com/christkv/node-mongodb-native) is working on built-in connection pooling so you don't have to implement this yourself. There is a note in the docs saying it's coming soon, but it looks like the code is already there so it should be very soon.

Update: I just checked with the author of the driver and connection pooling is fully implemented, he just forgot to remove that line from the docs.

Upvotes: 2

Paul Rumkin
Paul Rumkin

Reputation: 6873

One connection is better because you don't need to pass authorization and initialization each time you make request to db. Almost everything that you want to be fast accessed you should to store in RAM, not only db connections, but general templates or other files that you often use, configuration or some queues.

Upvotes: 2

Related Questions