Add a background job
Offload slow work to the worker app with a typed BullMQ queue, define the contract, enqueue from a service, add the processor.
Use a background job for work that is slow or can fail, such as sending an email, writing an audit entry, or syncing with an external API. The request adds the work to a queue and returns at once, and a separate process runs it later. This page adds a new email type to the existing email queue, end to end, and then shows how to create a new queue.
The queue is BullMQ, a job queue stored in Redis. Two roles share it:
- Producer: the code that adds a job. This is almost always a service in the server app.
- Processor: the code that runs the job. This is usually the worker app, sometimes the audit app.
The producer and the processor run in different processes and never call each other. They agree only on the shape of the payload, which is defined once in @app/shared, the library that both apps import. The compiler then checks both sides against the same contract.
Contract, producer, processor
Every background job is three things in three places: a payload type in @app/shared, a producer that adds the job (a server service), and a processor that runs it (the worker or audit app). When those three agree, the job runs.
For how queues sit next to the RabbitMQ message channel, see Queues and messaging.
The example
The email queue (EMAIL_QUEUE, value 'email') already exists. Its producer is EmailService in the server, and its processor is EmailProcessor in the worker. A new kind of email extends that contract, so nothing new has to be wired. The example on this page emails a guardian when a term report is ready.
The payload is a discriminated union: every variant has a literal type field, so the compiler can tell the variants apart and give each one its own typed data. When you add a variant, the compiler points you to every place that must change.
The names on this page are examples
TERM_REPORT_READY, TermReportReadyEmailPayload, TermReportEmail, REPORT_QUEUE, ReportJobPayload, and ReportProcessor are not in the code. Replace them with names for your job, and check that the enum and the library barrel do not already use the name you choose.
Step 1: Extend the contract in @app/shared
To make the shared library know the new email, add three things to the email types file: an enum value, a payload interface, and the new variant in the union.
export enum EmailType {
// ...existing variants...
TERM_REPORT_READY = 'TERM_REPORT_READY',
}
interface TermReportReadyEmailPayload extends BaseEmailPayload {
type: EmailType.TERM_REPORT_READY;
data: { firstName: string; termName: string; reportUrl: string };
}
export type EmailJobPayload =
| /* ...existing variants... */
| TermReportReadyEmailPayload;BaseEmailPayload already has the common fields (to, subject, and an optional campusId), so your interface declares only the type discriminator and a typed data object. Change the fields in data to what your template needs.
Result: the build now fails in EmailProcessor, because the processor does not handle the new type yet. Step 2 fixes that.
Add the variant to the union
The new interface does nothing until it is in the EmailJobPayload union. The producer and the processor are both written against the union, so without it the producer cannot pass your payload and the processor never sees it.
Step 2: Handle it in the processor
EmailProcessor.getTemplate() is a switch on payload.type that returns a React Email template. The switch is exhaustive: its default branch has a never check, so the build fails until every EmailType has a case.
To make the worker send the new email, add a case for your type. The props are the data fields from Step 1.
case EmailType.TERM_REPORT_READY:
return createElement(TermReportEmail, {
firstName: payload.data.firstName,
termName: payload.data.termName,
reportUrl: payload.data.reportUrl,
});Then add the matching template under emails/. To start, copy emails/otp.tsx, the one fully built template today, and change its props.
Result: the build passes again.
The never check catches a missing case
The exhaustive switch turns a forgotten email type into a compile error instead of a gap that shows up only at runtime.
Step 3: Enqueue it from the server
EmailService is @Global(), so any module can inject it without an import. To send the email, call send with your payload from the service that knows the report is ready. The guardian, termName, and reportUrl values come from that service.
this.emailService.send({
type: EmailType.TERM_REPORT_READY,
to: guardian.email,
subject: 'Your child’s term report is ready',
data: { firstName: guardian.firstName, termName, reportUrl },
});send calls emailQueue.add(payload.type, payload), so the EmailType value is the job name and the payload is the job data. The global Bull config sets attempts: 3, so a job that throws is retried up to three times before it is marked failed.
Result: each call adds one job named TERM_REPORT_READY to the email queue.
Do not wait on the enqueue
send returns void. It catches any enqueue error and logs it, so an API request does not fail because Redis had a short problem. Do not await a result, and do not make a request's success depend on the job being added.
Step 4: Test the producer
A producer test checks one thing: that the service adds the right job name with the right payload. Mock the queue and check the add call, as email.service.spec.ts does. In this snippet, payload is a TERM_REPORT_READY payload that the test builds.
service.send(payload);
expect(mockQueue.add).toHaveBeenCalledWith(EmailType.TERM_REPORT_READY, payload);Result: the test passes when send adds one job with your type as its name.
Do not test the producer and the processor together, because they run in different processes. The contract in @app/shared is what keeps them in step. See Testing for how queues are mocked.
A new queue
When the work is not email or audit, create a new queue. It has the same three parts (contract, producer, processor), built new instead of extended. Copy the EMAIL_QUEUE setup at each part.
Define the contract
To let both apps import the queue, add a queue-name constant and the payload type in @app/shared, and export both from the library barrel. Put the fields your job needs in the interface.
export const REPORT_QUEUE = 'report';
export interface ReportJobPayload {
/* the typed job data */
}Register the producer in the server
To add jobs from the server, register the queue with BullModule in the module that owns the work, and show it in Bull Board, the dashboard at /queues. Then inject the queue into a service with @InjectQueue and add jobs without waiting on them, as EmailService does.
imports: [
BullModule.registerQueue({ name: REPORT_QUEUE }),
BullBoardModule.forFeature({ name: REPORT_QUEUE, adapter: BullMQAdapter }),
],constructor(@InjectQueue(REPORT_QUEUE) private readonly queue: Queue) {}Result: the queue appears in Bull Board at /queues.
Add the processor
To run the jobs, write a class in the consuming app that extends WorkerHost and has the @Processor(REPORT_QUEUE) decorator. Then register it in that app's module: the queue in imports and the processor in providers, as the worker does for EmailProcessor.
imports: [
// ...
BullModule.registerQueue({ name: REPORT_QUEUE }),
],
providers: [
// ...
ReportProcessor,
],The consuming app already holds the global Bull and Redis connection, so you register only the queue and the processor. You do not configure Redis again.
Worker for general jobs, audit for audit writes
The worker app is the default home for background jobs. The audit app is only for audit-log writes, so do not add other processors there. One exception exists: the Microsoft sync processor runs inside the server, because it depends on many server modules. Treat that as a special case, not the pattern.
Verify
To check the whole path, run the tests, then start the server, worker, and audit apps together. The clinic app is a separate process and does not start with them.
pnpm test
pnpm dev:allpnpm dev:all is what task dev runs. Then trigger the producing code, for example by calling the endpoint, and open /queues.
Result: your job appears in its queue in Bull Board and moves to completed. If the job is added but never runs, the processor is usually missing or not registered: check that the consuming app lists it in providers and registers the queue in imports.
Where to go next
Queues and messaging
Every queue, the RabbitMQ message channel, and how the two differ.
Module anatomy
Where modules, services, and providers live: the wiring this recipe relies on.
Testing
How to mock a queue and check that a producer adds the right job.
Add a resource module
Create the module that will own your new producer service.