One hospital reporting indicator required (n1 + n2) / c1. Each of the three numbers came from an independent SQL query. Suppose I want the report to run only two at once: start A and B, start C as soon as A returns, then wait for all three numbers before evaluating the formula. If a database connection pool already queues requests, does the program need to manage those two slots itself?
If only this report uses the pool and each query borrows one connection, setting the pool limit to two suffices. My tool eventually acquired two separately configurable limits: how many connections the database can lend in total and how many slots one batch of reporting tasks may occupy. To understand why, consider what the third query waited for before there was a pool.
With two running at a time, when does the third start?
In my June 17 Node.js script I first divided the queries into groups. Each group started together, and await Promise.all(batchPromises) waited for the entire group to finish before the loop sent the next one. Suppose A takes one second, B ten, and C one. Ignoring other overhead, the difference between two arrangements is easy to calculate.1
| Arrangement | At 1 second, when A finishes | When C finishes | When all three results are ready |
|---|---|---|---|
| Groups of two, wait for the whole group | B is still running, C still waits | Starts at 10 seconds, finishes at 11 | 11 seconds |
| At most two in flight, start the next when one finishes | B keeps running and C starts immediately | 2 seconds | 10 seconds |
A counting semaphore implements the second arrangement. Here it issues two permits. A task calls acquire() for one, joining the queue if none remain. A calls release() when done and C at the head of the queue can proceed. My script revised on the afternoon of June 17 still used Promise.all to wait for all results, but the wait moved to the end of the entire report. Each query returned its permit in a finally block, so C could proceed even if A failed.2
Why would an operating-system semaphore apply to SQL queries?
I initially wanted to do this in Go. Reading Go by Example on June 15, I had just understood how a goroutine lets a piece of work proceed independently. My next question was how to limit concurrent data retrieval after starting lots of tasks. The following day I read Yngz_Miao’s Linux semaphore sets. It calls a semaphore set “由多个信号量组成的一个数组” (an array of multiple semaphores). Back in the A, B, C example, the three queries compete for one kind of resource. One semaphore initialized to two is enough.34
Operating systems were already using semaphores to coordinate processes in the 1960s: wait when a resource is unavailable and continue when it becomes available. A backend can use the same mechanism. My script put tasks without permits into a JavaScript queue and woke the first waiter when a permit was returned. It did not need a separate thread for every query while waiting for the database.52
I remember wanting to put the concurrency cap in YAML, the text file holding the query definitions. The June 16 Go version could read metrics, formulas, and SQL. On June 17 the Go executor still retrieved values sequentially. The semaphore appeared that day in a separate Node.js script, level5sql. The actual setting in the script was the environment variable DB_CONCURRENCY_LIMIT, defaulting to five permits.62
With a connection pool, what does each limit control?
On June 18 I added a connection pool to level5sql. A connection is an established communications channel between program and database. The pool lends an available one and takes it back after the query, so the next statement can reuse it. This version called mysql.createPool() with a ten-connection cap, and the driver established connections on demand. Even though the pool could hold ten, the report still admitted only five tasks by default.78
Follow C through the two waiting points. Acquire a task permit first, then borrow a database connection. If this batch has used up its permits, C waits at the semaphore without holding a connection. If C has a permit but other tasks have borrowed every connection, it waits in the pool until someone returns one. Borrowing the connection before waiting for a permit makes a queued task hold a connection it cannot yet use.27
Another easily missed question is who shares the permits. The June 22 query management service let a web page supply concurrencyLimit with a batch of metrics, defaulting to two. Each executeQueries call created a semaphore. If two colleagues submitted separate batches, each got two permits. If all reports together should use at most two, the requests should share a semaphore.9
That tells you which value to change. If the only goal is two connections checked out across the whole pool, the pool limit suffices. If the pool holds ten and a batch of reports should use at most two to give other work a chance to borrow connections, set the report permits separately on a semaphore. For timeouts, check when the permit is returned: the June 18 script returned the task permit when waiting for a result timed out, yet the underlying query might still be running. Its connection returned only when the query call finished. The two counters can therefore change at different times for the same SQL statement.7
How can a semaphore set enforce two limits on one query?
Take the YAML configuration idea a step further. Suppose each batch can run at most two SQL statements at once, while all reports together can run at most one against the operational database. Queries to the archive do not consume the operational database permit. Express both rules separately in YAML and have the backend manage a set of semaphores: each batch has its own two permits, while all batches share one for the operational database.
Suppose another report currently holds the operational database permit. A and B in our batch need that database too, but C needs only the archive. If A and B each take a batch permit and then wait for the operational database, C is blocked even though the archive is free. Linux semop() provides an idea worth borrowing: submit several operations on one semaphore set together. Either they all take effect, or none do.10
Here is a small example that runs directly in Node.js. An array holds queries that have yet to start. free tracks the remaining permits for each resource. Initially another report holds the only operational database permit.
const free = { batch: 2, businessDB: 0 };
const waiting = [
{ name: "A", needs: ["batch", "businessDB"] },
{ name: "B", needs: ["batch", "businessDB"] },
{ name: "C", needs: ["batch"] },
];
function takeNext() {
const index = waiting.findIndex(job =>
job.needs.every(key => free[key] > 0)
);
if (index === -1) return null;
const [job] = waiting.splice(index, 1);
for (const key of job.needs) free[key]--;
return job;
}
function finish(job) {
for (const key of job.needs) free[key]++;
}
const c = takeNext();
console.log(c.name, free.batch); // C 1:A、B 都没占走批次名额
free.businessDB++; // 另一份报表结束,归还业务库名额
const a = takeNext();
console.log(a.name, free.batch); // A 0:此时 A 和 C 同时在跑
finish(a); // A 同时归还批次和业务库名额
const b = takeNext();
console.log(b.name); // B
finish(b);
finish(c);
every first checks all the permits a query needs. Only when all are available does it decrement them individually. There is no await between checking and decrementing, so another task in the same Node.js event loop cannot intervene halfway through. With real queries, call finish(job) in the task’s finally block, then select the next task from the queue.
Footnotes
-
CaiBorui [S2thend]. (2025, June 17). Add batch execution and limit batch size for SQL query execution [Local Git commit
c7078e6]. level5sql,calcProc.js, lines 84–109. ↩ -
CaiBorui [S2thend]. (2025, June 17). Add semaphore for better concurrent performance [Local Git commit
95e4672]. level5sql,calcProc.js, lines 70–95, 104–142, and 249–253. ↩ ↩2 ↩3 ↩4 -
McGranaghan, M., & Bendersky, E. (n.d.). Goroutines. Go by Example. Ordinary and concurrent calls. ↩
-
Yngz_Miao. (n.d.). 【Linux】Linux的信号量集. CSDN. Quotation in the first paragraph. ↩
-
Dijkstra, E. W. (1968). The structure of the “THE”-multiprogramming system. Communications of the ACM, 11(5), 341–346. Appendix on semaphores and waiting processes. ↩
-
CaiBorui [S2thend]. (2025, June 16–17). SqlQueryManagement. GitHub. YAML loading entry in the Go version, Executing queries sequentially by variable. ↩
-
CaiBorui [S2thend]. (2025, June 18). Boost performance by using connection pool [Local Git commit
953029d]. level5sql,db_query.js, lines 9–24 and 129–144, andcalcProc.js, lines 134–167. ↩ ↩2 ↩3 -
mysqljs contributors. (2020). mysql (v2.18.1). GitHub. Pooling connections and Pool options. ↩
-
CaiBorui [S2thend]. (2025, June 22). Add API execute SQL and get saved results, and corresponding UI. SqlQueryManagement, GitHub. Batch endpoint accepting the limit, Per-batch semaphore creation and default arguments. ↩
-
IEEE & The Open Group. (2017). semop — XSI semaphore operations. POSIX.1-2017. DESCRIPTION, atomicity of a group of operations. ↩