Node.js Course
Node.js
/
Advanced

Database Connections

Definition

The methodology and lifecycle of establishing a secure, persistent connection between a Node.js runtime and an external Database server.

Explain Like I'm New

Connecting to a database is expensive. It takes time to authenticate and establish a secure tunnel. If you open a new connection every time a user requests a page, your server will be extremely slow and eventually crash the database. Instead, you open a connection ONCE when the server boots up, and share that tunnel for all requests.

Real World Example

Using a Connection Pool. Instead of opening 1 tunnel, you open 10 tunnels on boot. When 50 users hit the site, Node passes their requests through whichever of the 10 tunnels is currently free, maximizing throughput without overwhelming the database.

Common Use Cases

  • •Server bootstrapping
  • •Preventing database connection limits

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Should you connect to the database inside your Express route (`app.get`)?

intermediate

  • What is a Connection Pool?

Flash Cards

Question

Connect inside the route?

Click to reveal answer
Answer

Absolutely NEVER. You will create a new connection for every single page refresh, quickly hitting the database's max connection limit (e.g., 100) and crashing the entire system.

Question

What is a Connection Pool?

Click to reveal answer
Answer

A cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools drastically improve application performance.