Reliable Background Jobs: Visibility Timeouts, Retry Budgets, and Dead-Letter Queues

Reliable Background Jobs: Visibility Timeouts, Retry Budgets, and Dead-Letter Queues

A web request may finish in a few seconds, but sending email, generating invoices, transcoding video, or calling a third-party API can take much longer. Moving these tasks to a queue improves request latency and failure isolation, but it introduces a new class of design problems: How long should a consumer own a message? When should a failed message become available again? Which failures deserve a retry? How can one malformed message be isolated without blocking the entire queue?

This article presents a practical design for avoiding three common queue failures: messages that appear to disappear, jobs that execute twice, and messages that are retried forever. The examples use Amazon SQS terminology, but the same principles apply to RabbitMQ, Azure Service Bus, Google Cloud Tasks, and other job systems.

Start with the delivery guarantee

Most distributed queue systems behave close to an at-least-once delivery model. The system attempts to deliver a message at least once, but the same message may be delivered more than once. Consider a worker that completes an external API call and crashes before acknowledging or deleting the message. The queue cannot know that the side effect already occurred, so it makes the message available again.

For this reason, “each message runs only once” is not a safe assumption. The handler must tolerate repeated execution. For an invoice job, for example, store a unique processing key or enforce a unique database constraint before creating the invoice record. This is not merely an API feature; it is an application-level response to the normal behavior of at-least-once queues.

How visibility timeouts work

When a consumer receives a message, the message is usually not deleted immediately. Instead, it becomes temporarily invisible to other consumers. Amazon SQS calls this period the visibility timeout. After the worker completes successfully, it deletes the message. If the worker crashes or fails to delete it before the timeout expires, the message becomes visible again.

Suppose a PDF generation job normally takes 20 seconds and has a 95th-percentile duration of 70 seconds under load. A 10-second visibility timeout allows another worker to receive the same message before the first worker finishes. Both workers may generate the same file, overwrite each other’s output, or send the same downstream request twice.

The opposite configuration is also problematic. A 30-minute timeout delays recovery if a worker crashes immediately after receiving a message. Failed work stays hidden for too long, increasing queue latency and slowing operational recovery.

A practical starting rule

Start with a timeout slightly above the expected processing duration, then adjust it using measurements:

MeasurementExampleInitial timeout
p50 processing time8 seconds30 seconds
p95 processing time24 seconds45-60 seconds
p99 processing time55 seconds90 seconds or heartbeat

If processing duration varies widely, do not solve the problem by choosing an extremely long fixed timeout. Use a heartbeat that extends the visibility timeout while the job is still making progress. Amazon SQS supports changing the visibility period during processing. The heartbeat should still have a maximum total runtime; otherwise, a stuck worker can hide a message indefinitely.

A retry policy needs more than “try again”

Not every error should be handled in the same way. A DNS failure, temporary HTTP 503 response, or short database outage may be retryable. Invalid JSON, a missing resource, or a schema validation failure usually will not be fixed by sending the same input again.

Classify failures into at least three categories:

  • Transient failure: Network interruption, rate limiting, or temporary service unavailability. Use delayed retries.
  • Permanent job failure: Missing required data, an invalid identifier, or an unsupported file type. Move the message to an inspection path without wasting retries.
  • Unexpected system failure: A software defect, process crash, or database access problem. Use bounded retries, detailed logs, and an alert.

Use exponential backoff with a small random jitter instead of retrying at a fixed interval. For example, delays of 5, 15, 45, and 135 seconds reduce the chance that hundreds of workers will call a recovering service at the same time. Jitter further spreads those attempts and avoids synchronized retry storms.

Define a retry budget

Retrying a job forever is usually not resilience; it is a delayed failure. Define a maximum attempt count or a maximum retry duration for every job type. A policy might look like this:

{
  "maxAttempts": 6,
  "backoff": [5, 15, 45, 135, 300],
  "maxAge": "2h"
}

This example allows up to six attempts, including the first attempt, and prevents the job from remaining in the normal retry path for more than two hours. Google Cloud Tasks exposes equivalent controls such as maximum attempts, maximum retry duration, minimum and maximum backoff, and the number of exponential doublings. If you build your own worker, model these limits explicitly in application code.

Use a dead-letter queue to isolate poison messages

Messages that exceed the retry budget should be moved to a dead-letter queue, or DLQ. A DLQ is not a trash can where failures disappear. It is an operational holding area containing enough context to investigate the problem: failure reason, last attempt time, attempt count, job identifier, and preferably a trace or correlation ID.

Consider a shipping service that queues label-generation jobs. If the carrier API returns HTTP 503, delayed retries are appropriate. If the customer address is missing a required field, retrying six times will not change the input. That message should move to the DLQ. An operator can correct the data and replay the message safely.

DLQ operations should be designed before production launch. Decide:

  • Where will the reason for the final failure be inspected?
  • How will a corrected message be replayed?
  • How will duplicate side effects be prevented during replay?
  • Who receives an alert when the DLQ grows or its oldest message becomes too old?

Solving a concrete failure step by step

Imagine a reporting service that sends reports to 10,000 customers every night. The first implementation receives a message, generates the report, sends the email, and deletes the message at the end. The visibility timeout is 60 seconds, but some large reports take 90 seconds.

Customers occasionally receive the same email twice. At the 60-second mark, the message becomes visible again and another worker starts the same job. Four changes address the issue:

  1. Measure p95 and p99 processing times, then increase the initial timeout to 120 seconds.
  2. For longer reports, send a heartbeat every 30 seconds to extend the timeout while work is progressing.
  3. Make the send record unique using a key such as report_id + customer_id + period.
  4. Move messages to a DLQ after six failed attempts and alert on DLQ age and size.

Increasing the timeout alone is not a complete solution. A worker can still crash after sending the email but before deleting the message. The timeout controls how long a consumer temporarily owns the message; it does not guarantee that the business side effect happens only once.

Queues require observability

At minimum, monitor the following:

  • Number of pending messages and age of the oldest message
  • p50, p95, and p99 processing duration
  • Success, transient failure, permanent failure, and retry rates
  • Number of visibility timeout expirations
  • DLQ message count and age of the oldest DLQ message
  • Active jobs and error rate per worker

The condition “few messages, but a very old oldest message” is especially valuable. It can indicate that a small number of jobs are stuck or that workers cannot process a particular message type. Include the queue message ID, job ID, attempt number, timeout-extension count, and correlation ID in structured logs.

Conclusion

Reliable background processing is more than placing a message on a queue. Visibility timeouts must reflect real processing times, long-running jobs need controlled heartbeats, transient and permanent failures must be separated, retry attempts need a budget, and unrecoverable jobs need a DLQ with an operational workflow.

The most robust design treats at-least-once delivery as normal. When handlers are safe to run again, side effects are protected, retries are bounded, and failures are observable, the queue behaves predictably under real load instead of merely appearing reliable during a happy-path test.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published