Concurrency
Introduction
The concurrency package runs several pieces of work at the same time and gives you the results together. You hand it a list (or a named set) of tasks, and run() resolves when every task is finished. A second operation, defer(), starts the same kind of batch in the background so your code can carry on without waiting.
Tasks can run in two ways, chosen by a driver. The default async driver runs your functions on the current event loop, which is what you want for I/O such as database queries and HTTP calls. The worker driver runs each task in its own worker thread, which is what you want for CPU-heavy work that would otherwise block the event loop.
pnpm add @plinthjs/concurrencyRunning tasks concurrently
Import Concurrency and pass run() an array of functions. It calls them all at once and resolves with an array of results in the same order as the tasks, regardless of which finished first.
import { Concurrency } from '@plinthjs/concurrency'
const [users, posts] = await Concurrency.run([async () => fetchUsers(), async () => fetchPosts()])The total time is that of the slowest task, not the sum of them all. Tasks may be synchronous or return promises.
Named tasks
Pass an object instead of an array to name your tasks. The result is an object with the same keys.
const { users, posts } = await Concurrency.run({
users: async () => fetchUsers(),
posts: async () => fetchPosts(),
})The result types follow the tasks, so users and posts above have the types your functions return.
Handling failures
If any task throws or rejects, run() rejects with that error. Results from the other tasks are discarded, so catch inside a task when a failure there should not fail the whole batch.
try {
await Concurrency.run([
() => {
throw new Error('boom')
},
() => 1,
])
} catch (error) {
// Error: boom
}Deferring work
defer() takes the same batch but does not give you the results. It schedules the batch to start after the current work yields, returns right away, and ignores both the results and any errors.
Concurrency.defer([async () => recordAnalytics(event), async () => warmCache()])
// the next line runs immediatelyIt suits side effects you do not want to hold up a response for. Because errors are swallowed, do your own error handling inside the tasks if you care about failures.
defer() returns a handle. Call invoke() on it to start the batch now and wait for it to settle. The batch only ever runs once: calling invoke() again, or letting the scheduled start fire afterwards, does not run it twice.
const handle = Concurrency.defer([async () => flushMetrics()])
await handle.invoke() // run it now and wait; never rejectsThis is also how you make a deferred batch deterministic in a test.
Choosing a driver
A driver decides where tasks execute. Concurrency is a manager with two built in:
| Driver | Runs tasks | Best for |
|---|---|---|
async | On the current event loop, as promises | I/O: queries, requests, files |
worker | Each in its own worker_threads worker | CPU-bound computation |
The async driver is the default. To use another driver for one batch, ask the manager for it by name:
const results = await Concurrency.driver('worker').run([workerJob((n: number) => n + 1, 1)])
// => [2]The async driver
The async driver is the plain case. It starts every task, waits for the promises with Promise.all, and returns the results. Because everything shares one thread, a task that does a long synchronous calculation still blocks the others. Use it for work that waits.
The worker driver
The worker driver gives each task its own worker thread, so heavy computation in one task does not freeze the event loop or the other tasks. Because a worker is a separate JavaScript environment, tasks have to be described differently. Wrap the function and its input in workerJob(fn, payload). The function receives the payload as its only argument.
import { Concurrency, workerJob } from '@plinthjs/concurrency'
const worker = Concurrency.driver('worker')
const [doubled, sum] = await worker.run([
workerJob((n: number) => n * 2, 21),
workerJob(async (p: { a: number; b: number }) => p.a + p.b, { a: 1, b: 2 }),
])
// doubled => 42, sum => 3Named batches work the same way:
const { fib } = await worker.run({
fib: workerJob((n: number) => {
const f = (x: number): number => (x < 2 ? x : f(x - 1) + f(x - 2))
return f(n)
}, 20),
})
// fib => 6765WARNING
The function is converted to source text and evaluated inside the worker, so it must be self-contained. It cannot use variables from the surrounding scope, imported modules or other functions in your file. A task that references an outer variable fails inside the worker with closure is not defined. Pass everything it needs through the payload. The payload and the result must be values that can be copied between threads, such as plain objects, arrays, strings and numbers.
An error thrown inside the worker rejects the batch with an error that carries the original message and stack. A worker that exits abnormally rejects with Worker stopped with exit code ....
Every workerJob starts a new thread, which has a cost. Use the worker driver for work that takes long enough to repay it.
Timeouts for workers
By default a worker task may run forever. To cap it, create your own manager with workerTimeoutMs. A task that exceeds the limit is terminated and the batch rejects.
import { ConcurrencyManager, workerJob } from '@plinthjs/concurrency'
const concurrency = new ConcurrencyManager({ default: 'worker', workerTimeoutMs: 5_000 })
await concurrency.run([workerJob(() => crunch(), null)])
// rejects with "Worker task timed out after 5000ms." if it takes longerConfiguring the manager
The exported Concurrency is a ready-made ConcurrencyManager whose default driver is async. To change the default or register drivers, build your own manager and use it in place of the shared one.
import { ConcurrencyManager, workerJob } from '@plinthjs/concurrency'
const concurrency = new ConcurrencyManager({ default: 'worker', workerTimeoutMs: 10_000 })
concurrency.getDefaultDriver() // => 'worker'
await concurrency.run([workerJob((n: number) => n * 2, 4)]) // uses the worker driver
await concurrency.driver('async').run([() => 'on the event loop']) // pick another per callAsking for a driver name that is not registered throws Concurrency driver [name] is not defined. The manager creates each driver once and reuses it.
Custom drivers
A driver is any object with run(tasks) and defer(tasks). Register one with extend() (or the drivers option) and select it by name. This is handy for a test double or an alternative execution strategy.
import type { ConcurrencyDriver, Task } from '@plinthjs/concurrency'
// Runs array batches one task at a time instead of all at once.
const serial: ConcurrencyDriver = {
async run(tasks) {
const results: unknown[] = []
for (const task of tasks as Task<unknown>[]) {
results.push(await task())
}
return results as never
},
defer() {
return { invoke: async () => {} }
},
}
concurrency.extend('serial', () => serial)
await concurrency.driver('serial').run([() => 1, () => 2]) // => [1, 2]Testing
Use the async driver in tests. It runs your functions in-process with no threads, and defer() handles can be driven by hand. Awaiting handle.invoke() runs a deferred batch to completion, so you can assert on its side effects right afterwards without timers.
import { Concurrency } from '@plinthjs/concurrency'
import { expect, it } from 'vitest'
it('records analytics in the background', async () => {
const seen: string[] = []
const handle = Concurrency.defer([async () => void seen.push('event')])
await handle.invoke()
expect(seen).toEqual(['event'])
})If the code under test accepts a ConcurrencyDriver, pass a stub driver that runs tasks inline.