Search code examples
mysqlnode.jsconnection-pooling

MySQL connection pool on Nodejs


If Node is single-threaded, what is the advantage of using a pool to connect with MySQL?
If it is, when should I release a connection?

Sharing the same, persistent, connection with the whole application isn't enough?


Solution

  • Nodejs is single threaded, right. But it is also async, meaning that the single thread fires multiple sql queries without waiting for the result. The result is only processed via callbacks. Therefore it makes sense to use a connection pool with more than one connection. The database is likely multi-threaded, which makes it possible to parallelize the queries, although they were fired consecutively. There is no guarantee however in which order the results are processed if you don't take extra care for that.

    Addendum about connection release

    If you use a connection pool, than you should aquire/release each connection from the pool for each query. There is no big overhead here, since the pool manages the underlying connections.

    1. Get connection from pool
    2. Query
    3. In the callback release connection back to the pool.