3

Should you create an instance of the database connection outside the scope of route handlers, or create one for each handler (e.g., app.get('/todos'))?

Correct me if I'm wrong, but I'd guess the first approach is better because it can reuse the same connection. However, I've seen other examples that creates one for each route handler.

What's the recommended approach? Or does it matter due to how the database can cache connections on its end?

EDIT: I may be confused about how database drivers connect. Most provide a method such as connectDB(config) where you specify the location of the resource, authentication, etc. Is this actually making a connection or does it initiate the connection when you actually request something with that database object?

user1164937
  • 1,979
  • 2
  • 21
  • 29
  • Best practice is to create database connection outside the scope of route handlers, if you are creating db connection for every route then you are increasing your in-memory consumption and at scale it can decrease system performance. – Yogeshwar Tanwar Dec 25 '16 at 21:00

1 Answers1

2

You should make your connection once and use it in all handlers.

If you're reconnecting to the database on every request then you will use a lot of resources and increase latency, not to mention hammering your database with useless reconnections.

Database connections are meant to be persistent - not one-time things.

You didn't say which database you use, but on the example of Mongo - when you connect to the DB with the native MongoDB Node.js Driver there are some options that you can use, like:

  • poolSize - Set the maximum poolSize for each individual server or proxy connection (default is 5)
  • autoReconnect - Reconnect on error (default is true)

Some other interesting options are: reconnectTries, reconnectInterval, keepAlive, connectTimeoutMS, socketTimeoutMS.

You can change the values of those options if you're not happy with the defaults but those options are there to manage a long-living connection, not to reonnect and disconnect on every request.

For more info see:

See also this answer for more info:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177