You enqueue a background job to send an invoice, process a payment, or generate a report. The worker starts processing it, performs the operation, and then crashes before confirming that the job completed.
The queue cannot reliably determine whether the operation finished. Depending on the queue's delivery and acknowledgment behavior, it may deliver the job again. The next worker runs the same task, potentially sending another email, creating a duplicate record, or repeating an external API call.
This is a common challenge in distributed systems. Background jobs can execute more than once even when your application enqueues them only once.
The reliable solution is to design background jobs to tolerate repeated execution, protect important side effects with database constraints, and configure retries and acknowledgment behavior deliberately.
Why Background Jobs Run Twice
Duplicate execution can happen for several reasons. Understanding the source is important because each failure requires a different solution.
1. A Worker Crashes After Completing the Work
Imagine a worker processes an order and updates the database. Before it acknowledges the message, the worker crashes.
The queue may assume that the job has not completed and make it available again. Another worker receives the same job and repeats the operation.
The queue does not necessarily know that the first worker already performed the business operation. It only knows whether the message was acknowledged according to its protocol.
This is why acknowledging a message and completing the business operation are separate events.
2. A Job Is Delivered More Than Once
Many popular queue systems use at-least-once delivery semantics. They aim to ensure that messages are delivered, even when workers, networks, or queue infrastructure fail.
For example, Amazon SQS Standard queues can deliver a message more than once. Celery can also redeliver a task after a worker failure, depending on its acknowledgment configuration.
These behaviors improve reliability, but they mean consumers must be prepared to process the same logical job again.
3. A Job Takes Longer Than Its Visibility Timeout
Some queues temporarily hide a message while a worker processes it. This mechanism is commonly called a visibility timeout or lease.
If processing takes longer than the allowed period, the message can become available to another worker even though the original worker is still running.
Both workers may then execute the same job simultaneously.
This is especially problematic for long-running tasks such as video processing, report generation, bulk imports, and external API workflows.
4. Retries Repeat Partially Completed Operations
A job might perform several steps:
- Create an order record.
- Charge a payment provider.
- Send a confirmation email.
- Mark the job as completed.
Suppose the payment succeeds, but the email service times out. The worker retries the entire job.
Without safeguards, the second attempt might charge the customer again before reaching the email step.
Remark: A failed job does not necessarily mean that none of its side effects occurred. Always determine which operations completed before deciding what to retry.
5. Multiple Schedulers Enqueue the Same Job
Duplicate jobs can also originate before a worker receives anything.
For example, two application instances may run the same scheduled task at midnight. Both instances identify the same records as needing processing and enqueue jobs for them.
Similarly, a producer might successfully enqueue a job but lose the response. If it retries the enqueue operation without a stable job identity, it may create another job.
These situations require coordination or deduplication at the scheduling and job-enqueueing stages, not just inside the worker.
1. Make Job Handlers Idempotent
The most important protection is to make a job safe to execute multiple times.
An idempotent handler produces the same intended business outcome whether it runs once or several times with the same logical operation identifier.
For example, suppose a job marks an invoice as paid. Instead of blindly applying a new balance adjustment every time, the application should verify that the payment has not already been recorded and enforce the appropriate uniqueness rules in the database.
The goal is to prevent a retry from repeating the business effect, not necessarily to prevent the handler from running again.
Remark: Idempotency is a property of the operation's effects. It does not mean that the queue delivers a job only once or that the handler's code executes only once.
2. Use Database Constraints to Prevent Duplicate Effects
Application-level checks alone are not sufficient when multiple workers operate concurrently.
Consider two workers checking whether a payment has already been recorded. Both might see no existing record before either inserts one. Without a database constraint, both could proceed.
A unique constraint provides an atomic safeguard.
For example, a processed_jobs table can enforce uniqueness on a stable logical job identifier. The worker attempts to record that identifier and proceeds only if it successfully claims the operation.
In PostgreSQL, the core check can use:
INSERT INTO processed_jobs (job_id)
VALUES ('job_123')
ON CONFLICT (job_id) DO NOTHING
RETURNING job_id;
If the statement returns a row, the operation identifier was newly claimed. If it returns no row, the identifier already exists.
The claim and the associated business database changes should normally occur in the same transaction. Otherwise, the application could record a job as processed and crash before applying its business update, causing later retries to skip unfinished work.
Remark: A deduplication record by itself is not enough. Design the transaction so that claiming the job and applying its database effects succeed or roll back together.
3. Handle External Side Effects Separately
Database transactions cannot automatically make operations in external systems atomic.
Suppose a worker charges a payment provider and then crashes before recording the successful payment in PostgreSQL. A retry cannot safely assume the first charge failed.
When the external provider supports idempotency keys, pass a stable key representing the logical operation. Reusing that key can allow the provider to recognize retries rather than creating another charge.
This approach also applies to certain email, shipping, and third-party API workflows, depending on the provider's capabilities.
For complicated workflows that combine database changes and message publishing, a transactional outbox can help. The application writes its business update and an event record in one database transaction. A separate publisher sends the event to the queue and tracks delivery.
An outbox may publish an event more than once if it crashes after publishing but before recording success, so consumers still need duplicate protection.
Remark: A transactional outbox improves reliable event publishing, but it does not automatically provide exactly-once execution of every downstream side effect.
4. Configure Retries, Acknowledgments, and Timeouts Carefully
Queue configuration influences when jobs are repeated and whether unfinished work is lost or delivered again.
| Mechanism | What to check |
|---|---|
| Retries | Retry only recoverable failures and use an appropriate backoff strategy |
| Acknowledgments | Understand whether messages are acknowledged before or after processing |
| Visibility timeout or lease | Ensure it accounts for processing duration and extend it when supported |
| Heartbeats | Use them when supported to keep long-running jobs from appearing abandoned |
| Dead-letter queue | Move repeatedly failing jobs to a place where they can be inspected |
Exponential backoff can prevent workers from retrying failing operations continuously. A dead-letter queue helps isolate jobs that repeatedly fail rather than allowing them to retry forever.
For long-running jobs, make the visibility timeout or lease compatible with realistic processing times. If the queue supports extending the lease, do so while work is progressing. This reduces unnecessary concurrent execution, although it does not eliminate every possible duplicate delivery.
Acknowledgment settings involve trade-offs. Acknowledging too early can lose work if a worker crashes before completing it. Acknowledging after execution can allow completed work to run again if the worker crashes before the acknowledgment is recorded.
Neither setting removes the need for idempotent job handlers.
5. Prevent Duplicate Enqueueing
Sometimes the right fix is to avoid adding the same logical job to the queue repeatedly.
Give jobs a stable identifier based on the operation being performed. For instance, a task to generate a monthly report might use a combination of the report type, account identifier, and reporting period.
Queue-level deduplication can then suppress repeated enqueueing attempts when the same job is already waiting or active, depending on the queue's implementation and configuration.
BullMQ, for example, supports deduplication identifiers and offers different modes for suppressing repeated additions during a specified period or while a job remains incomplete.
However, queue-level deduplication and idempotent processing solve different problems:
- Enqueue deduplication reduces the number of equivalent jobs entering the queue.
- Idempotent processing protects business effects when a job is delivered or executed again.
Use both where appropriate.
Remark: A stable job ID must represent the correct business operation. If two legitimate operations share the same identifier, deduplication may suppress work that should have happened.
6. Avoid Overlapping Scheduled Jobs
Scheduled jobs introduce a related problem: the scheduler may trigger another run before the previous run has finished.
Suppose a report runs every five minutes but occasionally needs eight minutes to complete. Multiple runs may overlap and process the same records simultaneously.
There are several ways to handle this:
- Prevent overlapping runs with a distributed lock or lease.
- Use a database constraint or claim mechanism to assign records to one worker.
- Make each run operate on a well-defined time window or set of records.
- Decide explicitly whether missed schedules should be skipped, delayed, or caught up later.
A process-local lock is not sufficient when multiple application instances can run the same scheduler. The coordination mechanism must be shared across those instances.
Also consider what happens if a process crashes while holding a lock. Leases and ownership checks can support recovery, but an expired lease does not guarantee that the old worker has stopped. Database conditions or fencing tokens may be necessary to prevent a stale worker from overwriting newer results.
7. Monitor Duplicate Executions
Even well-designed queue systems need operational visibility.
Track job identifiers, execution attempts, retry counts, processing duration, and final outcomes. Record whether a handler skipped an operation because it had already been completed.
Monitoring these signals helps distinguish expected retries from scheduling bugs, short visibility timeouts, and persistent worker failures.
Useful alerts include unusually high retry counts, growing dead-letter queues, repeated executions of the same logical operation, and jobs that remain active longer than expected.
Never log sensitive credentials or complete payment details just to diagnose duplicates. Use stable operation identifiers and appropriately redacted metadata.
Conclusion
Background jobs can run more than once because of message redelivery, worker crashes, retries, visibility-timeout expiration, lost enqueue responses, and overlapping schedulers.
Trying to eliminate every duplicate at the queue level is rarely enough. A reliable design assumes that repeated execution is possible and protects important business effects accordingly.
Make job handlers idempotent, enforce database uniqueness, coordinate concurrent workers, handle external side effects safely, and configure retries and acknowledgment behavior deliberately.
The queue is responsible for delivering work. Your application must ensure that receiving the same work again does not produce an unwanted duplicate result.
Frequently Asked Questions
Why do background jobs run twice?
Jobs may be redelivered after worker crashes, acknowledgment failures, visibility-timeout expiration, or configured retries. Duplicate jobs can also be created by overlapping schedulers or producers that retry enqueueing after an uncertain result.
Does a queue guarantee that a job runs only once?
Not universally. Many queue systems use at-least-once delivery, which allows repeated delivery to protect against failures. Even systems offering stronger delivery guarantees cannot automatically make every external side effect exactly once.
How do I prevent a background job from processing the same record twice?
Use a stable logical identifier, database uniqueness constraints, and a transaction that protects the business update. For external operations, use downstream idempotency or reconciliation where supported.
Should duplicate jobs be deleted from the queue?
Not automatically. First determine whether they represent the same logical operation or separate valid operations. Queue deduplication is useful for equivalent jobs, but deleting jobs without understanding their purpose can discard legitimate work.
What is the difference between retries and duplicate jobs?
A retry is a deliberate attempt to recover from a failure. Duplicate execution occurs when the same logical operation is performed more than once, whether because of retries, redelivery, or duplicate enqueueing. A retry can be safe when the operation is designed to tolerate it.



