1

I'm building a Node.js backend and trying to understand the role of database connection pooling more deeply.

Since Node.js is single-threaded and uses an event loop with non-blocking I/O via libuv, I figured that await would allow the app to handle thousands of concurrent requests without blocking. I understand that when await is hit (e.g., await db.query(...)), the query is offloaded to the underlying TCP/network layer, and Node can move on to handle other events or requests.

If the DB query is offloaded and non-blocking, and Node resumes the function only when the result comes back, why do I still need a pool of DB connections?

Wouldn’t a single connection be enough since the app is async and the queries are not blocking the event loop?

Here’s what I’m using as an example:

app.get('/price', async (req, res) => {
 const result = await db.query('SELECT price FROM crypto WHERE id = $1', [req.params.id]);
});

I'm using PostgreSQL with the pg library. I'm debating whether to use a single Client or a Pool for handling queries.

1
  • Imagine three or more users try to access price at the same time. Two of them are going to block because the underlying database connection can only run one query at a time. If you use a connection pool, each query gets a seperate connection and you don't have that problem. Commented Jul 9 at 1:15

1 Answer 1

0

Node server and DB server are two different things. While indeed they are both able to handle concurrent stuff, as they talk to each other they must do it on a single channel. That's a DB connection. Now since many requests to the server are concurrent, and each needs its own connection (or re-use another connection) that is why a pool of connections is needed.

In conclusion, if you want to support more than one DB connection at a given moment, you need a pool.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.