A background job is reliable when the product can tolerate it running late, running more than once, or being interrupted by a process crash, without silently losing the intended work. “We call the queue after saving” is not that guarantee. It is a hope that nothing fails in the few milliseconds between two systems.
This guide covers how I design reliable background jobs in full-stack web products: emails, imports, webhook delivery, document generation, synchronization with external APIs, and scheduled maintenance. The queue technology matters less than five properties: a durable handoff, idempotent consumers, a retry policy, visible failure, and a safe replay path.
Decide what “lost work” means for your product
Before choosing tools, list the jobs and write down what happens if each one never runs, runs twice, or runs an hour late.
| Job | If it never runs | If it runs twice | If it runs late |
|---|---|---|---|
| Welcome email | Minor annoyance | Minor annoyance | Usually acceptable |
| Payment capture or refund | Revenue or trust problem | Direct financial harm | Depends on provider rules |
| Customer data import | Missing records, support tickets | Duplicate records | Users wait for their data |
| Outbound webhook | Partner system drifts out of sync | Partner may double-process | Partner sees stale state |
| Search index update | Stale search results | Harmless if writes are idempotent | Usually acceptable |
This table decides where to spend effort. A search index can usually be rebuilt from source data. A refund cannot be “rebuilt”; it needs an idempotency key, a record of every attempt, and a human-visible failure state.
Make the handoff durable
The most common way to lose work is the gap between committing a database change and publishing a message:
- The API saves the order.
- The API publishes “send confirmation” to the queue.
- The process crashes, deploys, or times out between steps 1 and 2.
The user sees success. The follow-up work never happens, and nothing records that it was supposed to.
The reverse is also possible: the message is published, then the transaction rolls back. A worker now processes an order that does not exist.
The transactional outbox pattern closes this gap. When a request changes durable state and requires follow-up work, store both the state change and a pending event in the same database transaction. A separate delivery worker reads the outbox, publishes the job, and records the attempt.
flowchart LR
accTitle: Durable background work handoff
accDescr: An API transaction stores product state and an outbox event. A worker delivers the event to a queue and a job consumer performs idempotent work. Exhausted jobs move to a visible failure state that supports replay, and every step emits logs, metrics, and alerts.
A["API transaction"] --> D[("Product state")]
A --> O[("Outbox event")]
O --> W["Delivery worker"]
W --> Q["Queue"]
Q --> C["Idempotent consumer"]
C -->|"retries exhausted"| F[("Failed jobs")]
F -->|"reviewed replay"| Q
C --> M["Logs, metrics, alerts"]
An outbox row usually needs only a few columns:
- a unique event identifier;
- the event type and a versioned payload;
- the identifier of the record it refers to;
- created time, next attempt time, attempt count, and last error;
- a delivered or processed timestamp.
If your queue already lives in the same database, as with Postgres-backed job libraries, the job row itself can be the outbox. The principle is the same: the work is recorded in the same transaction as the state that requires it.
When you do not need an outbox
Not every job needs this ceremony. If the work is purely derived and can be recomputed, a periodic reconciliation job may be simpler: “find every order without a confirmation sent timestamp older than five minutes and send it.” Reconciliation is also a useful safety net alongside an outbox for work that must never be lost.
Assume at-least-once delivery
Most practical queues may deliver a message more than once. A consumer can finish its work and crash before it acknowledges the message. A visibility timeout can expire while a slow job is still running. A deployment can stop a worker halfway through.
Do not try to promise “exactly once” by assuming a network call cannot time out after the remote system accepted it. Make the effect idempotent instead.
Practical idempotency techniques:
- Unique constraints. Insert a row keyed by the operation, such as
(import_id, source_row_number). A duplicate delivery fails the constraint and becomes a no-op. - Processed-event table. Record the event identifier in the same transaction as the consumer’s state change. Skip events that are already recorded.
- State transitions. Update with a condition, such as “set status to
sentwhere status ispending.” If zero rows change, another attempt already finished. - Provider idempotency keys. Many payment and messaging APIs accept a key per request. Derive it from your own operation identifier, not from a random value generated on each attempt.
The last point matters. If every retry generates a new idempotency key, the provider cannot recognize the retry, and the protection disappears.
Give retries a policy
“Retry on error” is not a policy. Classify failures first:
| Failure type | Example | Action |
|---|---|---|
| Temporary | Provider timeout, rate limit, connection reset | Retry with exponential backoff and jitter |
| Permanent input error | Invalid email address, missing required field | Fail immediately and record the reason |
| Bug in the consumer | Unhandled null, schema mismatch | Fail, alert, fix the code, then replay |
| Unknown outcome | Timeout after the remote call may have succeeded | Check remote state or rely on an idempotency key before retrying |
Then set limits:
- A maximum attempt count per job type.
- Exponential backoff with jitter, so a provider outage does not become a retry storm.
- Respect for
Retry-Afteror provider rate limits. - A per-job timeout shorter than the queue’s visibility timeout.
- A concurrency limit for jobs that hit the same external API or database table.
Retrying invalid input forever wastes capacity and hides the real problem. A job that fails for a permanent reason should move to a failed state on the first attempt.
Make failure visible and recoverable
Every job system eventually has jobs that cannot succeed automatically. The question is whether anyone knows.
When retries are exhausted:
- Move the job to a failed or dead-letter state that persists.
- Store the payload, the last error, the attempt history, and the correlation identifier.
- Alert an owner when failures cross a threshold or a critical job type fails.
- Fix the cause.
- Replay the failed job through the same idempotent consumer.
Replay should be a reviewed, deliberate action, not a database edit. A small admin command or internal screen that replays one job, or all jobs of one type in a time range, is usually enough. Because the consumer is idempotent, replaying something that partly succeeded is safe.
Also decide when to stop. Some failed jobs should be discarded after review, for example a notification for an account that no longer exists. Record that decision rather than leaving the job in a failed list forever.
Handle long-running and scheduled work
Imports, exports, and batch synchronizations behave differently from short jobs.
- Split large work into checkpoints. Process a file in batches and record progress, so a crash at row 40,000 does not restart from row one.
- Prevent overlapping schedules. A cron job that runs every five minutes but sometimes takes seven will eventually run twice at once. Use a lock, a lease with expiry, or a unique “running” record.
- Make schedules observable. Alert when an expected scheduled job has not completed, not only when it fails. Silence is the most common failure mode of cron.
- Use the right clock. Store schedules and timestamps in UTC and convert only for display.
Observe the work, not just the queue
Queue depth alone does not tell you whether customers are affected. Track signals that map to outcomes:
- age of the oldest pending outbox event;
- time from enqueue to completion per job type;
- success, retry, and failure counts per job type;
- count and age of failed jobs;
- external provider error rates and latency.
Include a correlation identifier from the initiating request in every job log and downstream call. The question support will ask is concrete: “Did this customer’s import finish, and if not, where is it stuck?” Your logs and job records should answer it in minutes. The production logging and observability checklist covers which fields to log and which alerts to own.
Design the data so jobs can be safe
Many job bugs are really schema gaps. A unique constraint on the business identity of an imported row prevents duplicates even when the consumer has a bug. A status column with an explicit set of allowed values prevents a job from writing an impossible state. If the schema allows duplicates, a retry will eventually create them. The database schema review checklist covers constraints and migrations in more depth.
When jobs become events
Once several independent consumers react to the same fact, such as an invoice being paid, you are moving from jobs toward events. The same reliability rules apply, plus schema versioning and ordering. Read where event-driven architecture helps a SaaS product before introducing a message broker for that reason alone.
Reliable background jobs checklist
Use this before shipping a new job type:
- The cost of the job never running, running twice, and running late is written down.
- Work that must not be lost is recorded in the same transaction as the state that requires it.
- The consumer is idempotent through a constraint, processed-event record, or conditional update.
- Provider calls use a stable idempotency key derived from the operation.
- Failures are classified into temporary, permanent, bug, and unknown outcome.
- Retries have a maximum count, backoff with jitter, and a timeout.
- Exhausted jobs move to a persistent failed state with payload and error.
- An owner is alerted for critical failures and missing scheduled runs.
- A reviewed replay path exists and has been tested once.
- Long-running work checkpoints its progress and cannot overlap itself.
- Logs carry a correlation identifier from the original request.
Reliable job design is a core part of production readiness, not infrastructure polish for later. It is far cheaper to add an outbox row and a unique constraint on day one than to reconcile months of silently missing or duplicated work.
Frequently asked questions
What makes a background job reliable?
A background job is reliable when the product tolerates it running late, running more than once, or being interrupted by a crash without silently losing the intended work. That requires a durable handoff, idempotent processing, a bounded retry policy, a visible failure state, and a safe way to replay work.
Why is calling a queue after saving to the database not enough?
The process can commit the database transaction and crash before it publishes the message, or publish the message for a transaction that later rolls back. Writing the state change and an outbox record in the same transaction removes that gap.
Can a queue guarantee exactly-once processing?
Treat delivery as at-least-once. A consumer can finish its work and lose the acknowledgement, or a remote API can accept a request and time out before responding. Make consumers idempotent with a durable operation key, a unique constraint, or a processed-event record.
What should happen when a job keeps failing?
Stop retrying after a bounded number of attempts, move the job to a visible failed state with its error and context, alert the owner, and provide a reviewed replay path once the cause is fixed.