Background work and email from a feature
Move slow work off the request path: enqueue a welcome email in the sign-up transaction, run it in a retrying worker, and compare Postgres with BullMQ.
Payments and webhooks end to endThe sign-up and login flowError handling across the stack
Background work and email from a feature
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Work the user does not need to wait for, such as sending email or resizing an image, belongs in a background job so the request returns fast and survives a slow third party.
- Enqueue the job in the same database transaction as the change that triggers it, so you can never save a user without their welcome email or send an email for a user who was rolled back.
- A worker must assume failure: record attempts, retry with a growing delay, and cap the retries so a poisoned job does not loop forever.
- Jobs run at least once, so a job such as sending email needs its own guard against doing the work twice.
- A table in your existing Postgres is enough for a small queue using FOR UPDATE SKIP LOCKED, while Redis-backed libraries such as BullMQ add features and throughput for heavier loads.
Don’t make the user wait for the mail server
A user signs up for Taskboard. The handler inserts a row, then sends a welcome email by calling an email provider’s API. On a good day that call takes 300 ms. On a bad day it takes 20 seconds, or times out, or the provider is down. If the handler waits for it, the user stares at a spinner, and when the call fails you must decide whether sign-up failed. It did not. The account exists. Only the email did not go out.
The core problem is that some work is slow, unreliable or both, and nothing about the user’s request depends on it finishing. The standard answer is to record “an email needs to be sent” and let another process do it later, on its own schedule, retrying when it fails. This is a background job. Other Taskboard examples: resizing an attachment’s thumbnail, sending a daily digest, finishing work after a payment webhook as in the last lesson, deleting an account’s data.
The shape of every queue
All the libraries and services differ in details, but they share a shape:
- Producer (your API) writes a job: a kind and a payload.
- Store holds jobs until claimed. This is a table, Redis, or a cloud queue.
- Worker (a separate process) claims a job, runs it, then marks it done or schedules a retry.
The worker is a different process from the API, with its own deploy and logs. A job queue is also what lets you absorb a spike: ten thousand signups in a minute become ten thousand jobs that the worker drains at its own pace.
The first rule: enqueue in the same transaction
The most common bug is a quiet one. Consider:
await db.insert(users).values({ email });
await queue.add("welcome_email", { email }); // crash here and the email is lost
If the process dies between the lines, the user exists and no job does, and nothing will ever notice. Swapping the order is no better: you could email someone whose insert then fails. When the queue is a table in the same database as your data, you can do both in one transaction:
await pg.transaction(async (tx) => {
const u = await tx.query("insert into users(email) values ($1) returning id", [email]);
await tx.query("insert into jobs(kind,payload) values ('welcome_email',$1)",
[JSON.stringify({ userId: u.rows[0].id, to: email })]);
});
Both rows commit together or neither does. This is why a Postgres jobs table is a good first queue. It is often called the transactional outbox pattern when used for messages leaving your system. With a Redis queue you cannot share a transaction with Postgres, so you accept a small window of inconsistency or add a reconciliation job.
A small worker
Here is the table and the worker loop I ran on PGlite 0.5.17, using the claim query that makes a Postgres queue practical:
create table jobs(id serial primary key, kind text not null, payload jsonb not null,
attempts int not null default 0, run_at timestamptz not null default now(),
done_at timestamptz, last_error text);
update jobs set attempts = attempts + 1 where id = (
select id from jobs where done_at is null and run_at <= now()
order by id for update skip locked limit 1)
returning id, kind, payload, attempts;
for update skip locked is the important part. It locks the chosen row, and any other worker running the same query skips locked rows and takes the next one. Several workers can pull from one table without handing the same job to two of them and without waiting on each other. (That is documented Postgres behaviour. My run used one worker, so I did not exercise the concurrent case.)
The loop around it claims a job, calls the sender, and either marks it done or records the failure and sets run_at into the future:
try { await sendEmail(j.payload.to);
await pg.query("update jobs set done_at=now() where id=$1", [j.id]); }
catch (e) { const delaySec = 2 ** j.attempts; // 2s, 4s, 8s ...
await pg.query("update jobs set last_error=$2, run_at=now()+make_interval(secs=>$3) where id=$1",
[j.id, e.message, delaySec]); }
My fake sendEmail fails on its first call. The run showed the sequence: attempt 1 failed with smtp timeout, attempt 2 succeeded, and the third tick found nothing due. The final row had attempts: 2, done: true and last_error: 'smtp timeout'. For the demo I set the retry delay to zero so it would not sleep. In a real worker you would use the exponential delay shown above.
What a real worker needs
- A retry cap. After, say, eight attempts, stop and mark the job failed for a human to look at. A job that can never succeed must not loop forever.
- Backoff with jitter. If the email provider is down, a thousand jobs retrying at the same instant make it worse.
- A visibility timeout. If a worker crashes mid-job, the job should become claimable again after a while. My sketch does not do that.
- Idempotency. Delivery is at least once. If the worker sends the email and crashes before marking the job done, it runs again. Guard the side effect with a key the provider understands, or check a “welcome email sent” column first. See idempotency keys in practice.
- Visibility. Count queued, failed and oldest-waiting jobs and alert on the age of the oldest, as in observability across layers. Carry the request id into the job payload so a job’s log lines join the request that caused it.
- Graceful shutdown. Finish the current job on deploy rather than dropping it. See health checks and graceful shutdown.
Postgres table or a queue library
A Postgres table is the right start for Taskboard: no new infrastructure, transactional enqueue, and you can inspect it with SQL. It gets uncomfortable when you need thousands of jobs per second, delayed and repeating schedules with fine retry policies, rate limits per queue, or a dashboard.
BullMQ, covered in the talk linked under further viewing, is a Node library backed by Redis that provides those features. The cost is one more service to run, host and monitor, and the lost transactional guarantee described above. The full options and trade-offs, including scheduled and recurring jobs, are in background jobs, task queues and scheduling. Either way the app-side contract is identical: enqueue small payloads, keep ids not whole objects, and make the work safe to repeat.
Sending the email itself
Email adds its own failure modes. Use a transactional provider’s API (Resend, Postmark, SES and similar) rather than your own mail server, set up the domain’s DNS records (SPF, DKIM and DMARC, covered in sending transactional email) or messages land in spam, and always send from the worker, never inside the request. Build the message from the job’s data at send time, so a retry an hour later uses fresh data. For Taskboard, log the provider’s message id in the job row so you can answer “did the user’s email go out?” with one query.
In development and tests, point the sender at a fake that records messages. Your integration tests can then assert that signing up created a job, and a separate test can run the worker against the fake.
What the video covers
Codeman’s “How to Schedule Jobs with PgBoss in Node.js & PostgreSQL” is about sixteen minutes, published August 2025. Its description says it covers setting up pg-boss, a Node job library that runs on PostgreSQL, creating one-time, delayed and recurring jobs, handling retries, failures and job expiration, and monitoring and debugging job processing. That is a library version of the Postgres-backed queue this lesson describes; the hand-written FOR UPDATE SKIP LOCKED worker and the enqueue-in-the-sign-up-transaction pattern are my own. I could not read a transcript, so I rely on the title and description. The Resend getting-started video is linked for the email-sending half, and Codeminer42’s BullMQ talk for the Redis-backed alternative.
Where this fits
You can now move slow work off the request path and survive its failures. The next lesson asks what happens when many more people use the app and some of these pieces start to hurt: first bottlenecks when traffic grows.
Check yourself
Why enqueue the email job inside the sign-up transaction?
If the user insert commits, the job commits with it, and if the transaction rolls back, the job disappears. Enqueuing after the commit can lose the job on a crash, and before it can email a user who was never saved.
What does FOR UPDATE SKIP LOCKED let several workers do?
Each worker claims a different due row without waiting on rows another worker has locked, so jobs are handed out once each without a separate coordinator.
Why do background jobs need to be idempotent?
Queues deliver at least once. A crash after sending but before marking the job done means it runs again, so the job needs a check or key to avoid sending the email twice.
When would you move from a Postgres jobs table to BullMQ or similar?
When you need high throughput, delayed and repeating jobs with rich retry policies, rate limiting or dashboards, and you are willing to run Redis.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.