Node.js worker threads allow applications to execute CPU-intensive JavaScript operations in parallel without blocking the main event loop. They are useful for tasks such as image processing, data transformation, report generation, encryption, and large calculations.
However, introducing worker threads also creates new challenges when an application needs to access a database. A database connection or connection pool that works correctly in the main thread cannot automatically be shared with worker threads. Each worker runs in a separate JavaScript execution context, with its own memory and module state.
This becomes important when several workers need to read or update database records at the same time. Creating too many database connections can overload the database server, while sharing connection details incorrectly can cause connection failures, transaction problems, and unexpected application behavior.
The right approach is to understand what can be shared, what must remain isolated, and how to control the number of active database connections.
In this article, we will explore how database connections behave across Node.js worker threads, how to create independent connections safely, how to manage connection pools, and how to avoid common problems in production applications.
Understanding Database Connections and Worker Threads
A Node.js worker thread runs JavaScript independently from the main thread. It has its own event loop, execution context, and module state.
For example, a main application can create a worker using the worker_threads module:
const { Worker } = require("node:worker_threads");
const worker = new Worker("./worker.js");
worker.on("message", (result) => {
console.log("Worker result:", result);
});
worker.on("error", (error) => {
console.error("Worker failed:", error);
});
worker.on("exit", (code) => {
console.log("Worker exited:", code);
});
The worker can execute its own database operations, but it does not automatically inherit the main thread's database connection or connection pool.
Consider an application that creates a PostgreSQL pool:
const { Pool } = require("pg");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10
});
This pool belongs to the JavaScript execution context in which it was created. Passing the pool object through workerData or postMessage is not a supported way to share the live pool between threads.
The same principle applies to many database drivers. Connection objects contain internal state, sockets, event handlers, and other resources that are not designed to be transferred as ordinary JavaScript objects.
A safer approach is to pass configuration or work instructions to the worker and let the worker establish its own database connection.
Why Database Connections Cannot Be Shared Directly
A database connection is more than a connection string. It represents an active communication channel between an application and a database server.
For example, a PostgreSQL client maintains a network socket and protocol state. It also tracks whether a query is executing, whether a transaction is active, and whether the connection is available for another operation.
Worker threads have separate JavaScript heaps. Objects created in one worker are not directly accessible from another worker.
Node.js provides mechanisms such as structured cloning and transferable objects, but these do not make arbitrary database clients or connection pools transferable.
Trying to share a database pool directly can lead to several problems:
- The object may not be cloneable.
- The underlying network socket cannot be safely reused as an ordinary shared object.
- Transaction state may become difficult to manage.
- Multiple workers may attempt to use the same connection simultaneously.
- Driver-specific internal resources may not support cross-thread access.
Instead of sharing a live connection, share the information required to create a connection.
For example, a worker can receive a database connection string through workerData:
const { Worker } = require("node:worker_threads");
const worker = new Worker("./worker.js", {
workerData: {
databaseUrl: process.env.DATABASE_URL
}
});
The worker can then create its own connection pool.
Creating a Database Connection Inside Each Worker
Let's use PostgreSQL and the pg package to demonstrate this approach.
Install the package:
npm install pg
Create a file named worker.js:
const {
parentPort,
workerData
} = require("node:worker_threads");
const { Pool } = require("pg");
const pool = new Pool({
connectionString: workerData.databaseUrl,
max: 2,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000
});
async function processCustomer(customerId) {
const result = await pool.query(
`SELECT id, name, email
FROM customers
WHERE id = $1`,
[customerId]
);
return result.rows[0] || null;
}
async function run() {
try {
const customer = await processCustomer(
workerData.customerId
);
parentPort.postMessage({
success: true,
customer
});
} catch (error) {
parentPort.postMessage({
success: false,
error: error.message
});
} finally {
await pool.end();
}
}
run();
The worker creates its own PostgreSQL connection pool and performs a query.
The main thread does not pass a database client object. It passes only the database configuration and the customer ID.
The worker closes its pool after completing the operation.
This is a simple implementation for a worker that performs one database task and then exits. For long-running workers, creating and closing the pool for every individual task would be inefficient. In that case, the worker should keep a pool for its lifetime and close it when the worker shuts down.
Managing Database Connections in the Main Thread
Creating a separate pool in every worker is safe from a JavaScript object-sharing perspective, but it introduces an important resource-management problem.
Every pool can create multiple database connections.
Suppose an application uses the following configuration:
| Component | Pool size |
|---|
| Main thread | 10 |
| Worker 1 | 5 |
| Worker 2 | 5 |
| Worker 3 | 5 |
| Worker 4 | 5 |
| Total possible connections | 30 |
If the application creates more workers, the total number of possible database connections increases.
This can become a problem when the database has a limited connection capacity or when several application instances run simultaneously.
For example, four application instances with a potential pool size of 30 each could request up to 120 database connections.
The application should therefore manage the connection budget across all workers and application instances.
A useful starting point is to calculate the maximum connection requirement:
Maximum application connections =
Number of application instances
×
(Main thread pool size + Worker pool sizes)
The resulting number should leave enough database connections available for administration, monitoring, migrations, and other services.
Using a Shared Database Access Service
Another approach is to keep database connections in the main thread and let workers request database operations through message passing.
In this design, workers do not create database connections. They send a request to the main thread, which executes the query using its existing pool and returns the result.
This can reduce the total number of database connections because all database operations use a centrally managed pool.
The architecture looks like this:
Main Thread
|
Database Connection Pool
|
Database Access Handler
|
---------------------------
| | |
Worker 1 Worker 2 Worker 3
| | |
Request Request Request
| | |
---------------------------
Create a main.js file:
const { Worker } = require("node:worker_threads");
const { Pool } = require("pg");
const path = require("node:path");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10
});
function createWorker(customerId) {
return new Promise((resolve, reject) => {
const worker = new Worker(
path.join(__dirname, "worker.js"),
{
workerData: {
customerId
}
}
);
worker.once("message", (message) => {
if (message.type === "database-request") {
return;
}
resolve(message);
});
worker.once("error", reject);
worker.once("exit", (code) => {
if (code !== 0) {
reject(
new Error(
`Worker stopped with exit code ${code}`
)
);
}
});
worker.on("message", async (message) => {
if (message.type !== "database-request") {
return;
}
try {
const result = await pool.query(
message.sql,
message.params
);
worker.postMessage({
type: "database-response",
requestId: message.requestId,
rows: result.rows
});
} catch (error) {
worker.postMessage({
type: "database-response",
requestId: message.requestId,
error: error.message
});
}
});
});
}
This example illustrates the communication pattern, but a production implementation needs a request-response protocol that tracks multiple outstanding requests, correlates responses by request ID, handles worker termination, and prevents untrusted SQL from being submitted by workers.
A better design does not allow workers to send arbitrary SQL statements. Instead, expose a limited set of database operations such as getCustomer, saveReport, or updateJobStatus.
This keeps database access controlled by the main application.
Implementing a Request-Response Database Handler
A worker can use a message-based database interface without knowing how the actual connection pool works.
For example, create a worker that requests a customer record:
const {
parentPort,
workerData
} = require("node:worker_threads");
let requestId = 1;
function getCustomer(customerId) {
return new Promise((resolve, reject) => {
const currentRequestId = requestId++;
function handleMessage(message) {
if (
message.type !== "database-response" ||
message.requestId !== currentRequestId
) {
return;
}
parentPort.off("message", handleMessage);
if (message.error) {
reject(new Error(message.error));
} else {
resolve(message.rows[0] || null);
}
}
parentPort.on("message", handleMessage);
parentPort.postMessage({
type: "database-request",
requestId: currentRequestId,
operation: "getCustomer",
customerId
});
});
}
async function run() {
try {
const customer = await getCustomer(
workerData.customerId
);
parentPort.postMessage({
type: "completed",
customer
});
} catch (error) {
parentPort.postMessage({
type: "failed",
error: error.message
});
}
}
run();
The main thread should receive the operation name and customer ID, validate the request, and execute a predefined parameterized query:
async function handleDatabaseRequest(message, pool) {
if (message.operation === "getCustomer") {
const result = await pool.query(
`SELECT id, name, email
FROM customers
WHERE id = $1`,
[message.customerId]
);
return result.rows;
}
throw new Error("Unsupported database operation");
}
This approach is useful when database access must be centralized or when the database connection budget is tightly controlled.
However, message passing adds complexity and overhead. It is not automatically faster than allowing each worker to maintain its own connection pool.
Choose this design when centralized access, connection control, or a clear database ownership boundary is more important than minimizing communication overhead.
Choosing Between Independent Pools and Centralized Database Access
Both approaches are valid, but they solve different problems.
| Area | Independent worker pools | Centralized database access |
|---|
| Connection ownership | Each worker owns its pool | Main thread owns the pool |
| Database connections | Can increase with worker count | Shared across workers |
| Communication | Direct database queries | Message passing |
| Implementation | Relatively simple | Requires request-response handling |
| Transaction management | Managed inside each worker | Managed by the central service |
| Suitable for | Independent database-heavy tasks | Controlled database access and limited connections |
Independent pools are usually easier to implement when workers perform substantial database operations independently.
Centralized database access is useful when the application needs strict control over connection usage or wants to keep database access inside a single service boundary.
Neither approach should be selected only because it appears more parallel. Database performance depends on query execution, connection availability, locking, disk operations, and server capacity.
Handling Transactions Safely Across Workers
Transactions require special attention.
A transaction belongs to a specific database connection. It cannot be started on one connection and continued on another connection simply because both connections use the same database.
For example, the following operations must use the same PostgreSQL client:
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
[100, 1]
);
await client.query(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2",
[100, 2]
);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
Do not run the first update through one worker's connection and the second update through another worker's connection while expecting them to participate in the same transaction.
If a transaction must involve multiple operations, keep the transaction within one database client and one execution flow.
A worker can own that transaction through its own pool, or the main thread can execute it through a centralized database service.
The important requirement is that all statements belonging to the transaction use the same client connection.
Handling Worker Shutdown and Connection Cleanup
A worker that owns a database pool should close it when it no longer needs database access.
For a long-running worker, this usually happens when the worker receives a shutdown message or when its task queue is drained.
A simplified shutdown handler might look like this:
const {
parentPort
} = require("node:worker_threads");
const { Pool } = require("pg");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 2
});
let shuttingDown = false;
async function shutdown() {
if (shuttingDown) {
return;
}
shuttingDown = true;
await pool.end();
parentPort.postMessage({
type: "shutdown-complete"
});
}
parentPort.on("message", async (message) => {
if (message.type === "shutdown") {
await shutdown();
}
});
The main thread can request shutdown and wait for the worker to exit.
In a production implementation, the worker should stop accepting new tasks before closing the pool. It should also finish or safely cancel active operations according to the application's requirements.
Avoid terminating workers immediately while they may still have active database queries. A forced termination can leave application operations incomplete, even though PostgreSQL will eventually clean up a disconnected session.
Common Mistakes to Avoid
Creating Too Many Connection Pools
Creating a pool for every worker without calculating the total connection requirement can exhaust database connections.
Set explicit pool limits and consider the number of application instances and workers running at the same time.
Passing a Pool Through workerData
A live database pool is not a normal transferable JavaScript object.
Pass connection configuration or operation data instead, then create the pool in the worker when using independent connections.
Sharing Transaction State Across Connections
Transactions are connection-specific. Keep related statements on the same database client.
Allowing Workers to Execute Arbitrary SQL
If workers can submit unrestricted SQL to a central database handler, the application becomes harder to secure and maintain.
Expose predefined operations and use parameterized queries.
Forgetting Connection Cleanup
Workers should close their pools when they finish. The main thread should also close its own pool during application shutdown.
Assuming More Workers Always Improve Performance
Additional workers can increase database concurrency, but they can also increase connection pressure, lock contention, and query load.
Measure actual database performance before increasing worker counts.
Best Practices for Production Applications
When using database connections with Node.js worker threads, keep the connection ownership model simple and explicit.
Use independent pools when workers need to perform database operations autonomously. Set a small maximum pool size for each worker and calculate the total connection requirement before deploying the application.
Use centralized database access when the application needs strict connection management or when database operations should remain inside the main application service.
Keep transactions within a single database client. Use parameterized queries, validate worker requests, and avoid sending unrestricted SQL through message channels.
Finally, treat worker shutdown as part of database resource management. Stop accepting new work, complete or safely cancel active operations, close connection pools, and then allow workers to exit.
Summary
Node.js worker threads provide a useful way to execute CPU-intensive tasks in parallel, but they do not make database connection pools automatically shareable across threads.
Each worker has its own JavaScript execution context, so a safer design is to pass connection configuration and create independent database connections inside workers. When connection limits are important, the main thread can also own the database pool and process worker requests through message passing.
The right choice depends on the application's workload, database capacity, transaction requirements, and connection-management strategy.
By controlling pool sizes, keeping transactions on individual connections, handling worker shutdown correctly, and exposing clear database operations, developers can use worker threads without creating unnecessary database pressure or unreliable connection behavior.
Join the conversation! Your thoughts help the community grow.