Background tasks · Engineering practice

One job, two deliveries

Use stable job keys, database rules, and bounded retries to make Celery tasks safe to repeat.

AuthorHanif Birgani
Reading timeAbout 5 minutes
Published27 October 2026

Consider a worker that acknowledges messages after task completion. It stores a result, then loses its broker connection. The broker can send the unacknowledged delivery again.

A job is one requested operation. A delivery is one attempt to send that job to a worker. One job can have several deliveries.

A task can receive the same job twiceThe worker reads the job key before execution. A completed job bypasses the task. A repeat delivery returns to the same key. Find job keyClaim + run taskCommit resultAcknowledge deliveryAlready completeRepeat delivery
A second delivery reads the saved job state. A completed job returns its stored result.

Separate delivery from completion

RabbitMQ uses consumer acknowledgements to track deliveries. Publisher confirms track the separate path from the sender to the broker. Neither mechanism makes a business operation execute once.[1]

An idempotent task can repeat without an additional business effect. This property belongs to the task and its data rules, not to the queue name.

A FastAPI or Django endpoint can accept work and return a job identifier. A later status request can report the saved state of that job.

The application needs a durable job record for this design. Broker delivery state alone cannot describe whether a result is ready for the user.

Give the operation a stable identity

A job key identifies the requested operation. The same document revision and operation version should produce the same key within one tenant.

A tenant is a customer scope within the application. The tenant identifier prevents two customers from sharing an application record. The document revision prevents a changed document from reusing an earlier result.

import hashlib
import json

def job_key(tenant_id, document_id, revision, operation_version):
    parts = [tenant_id, document_id, revision, operation_version]
    if any(not isinstance(part, str) or not part.strip()
           for part in parts):
        raise ValueError("Every job identifier must be a non-empty string")
    payload = json.dumps(parts, ensure_ascii=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()

The function produces a stable key from four explicit identifiers. The caller must get the tenant identifier from its authorization context.

A unique database constraint can enforce one row for each key. A check before an insert cannot prevent two workers from inserting at the same time.[2]

The key defines a deduplication boundary. It does not provide authorization or prevent a repeated call to an external service.

Store the result and completion together

A database transaction can make several writes one atomic change. The result and its completed job state should become visible together.[3]

This design uses a short claim step before the external call. The claim contains an expiry time and a unique attempt token.

The token identifies the worker attempt that owns the claim. A conditional database update can reject a stale attempt after another worker gets ownership.

  1. Read the job record by its stable key.
  2. Return the stored result if the job is complete.
  3. Claim an available job with an atomic database operation.
  4. Run the external operation outside the database transaction.
  5. Verify the attempt token before the final database writes.
  6. Store the result and completed state in one transaction.

A claim expiry permits recovery after a worker stops. Long tasks need a defined renewal policy. A stale worker must not overwrite a newer result.

An external service can still receive the same request twice. Where that service supports idempotency keys, the application can reuse one key. Otherwise, repeated work can incur additional cost.

Limit retries and test acknowledgement policy

Celery provides retries with backoff and optional jitter. Backoff increases the delay between attempts. Jitter spreads retry times across workers.[4]

Temporary connection failures can justify a retry. Invalid input and access failures usually need a different response. A single retry rule for all exceptions obscures this difference.

  1. Set time limits for external network operations.
  2. Retry only the error categories that can recover.
  3. Set a maximum retry count and a total time budget.
  4. Store a job-level attempt count to limit fresh worker claims.
  5. Move exhausted jobs to an explicit failed state.

Celery can acknowledge some terminated child tasks even with acks_late=True. The task_reject_on_worker_lost setting changes that behavior and can cause message loops.[5]

The acknowledgement configuration therefore needs worker-loss tests. A late acknowledgement alone is not a complete recovery policy.

Close the gap before the first delivery

The database commit and broker publish are separate operations. A process can stop after it creates the job but before it sends the message.

An outbox is a table of messages that still need delivery. The application can insert the job and its outbox message in one transaction.

A separate sender publishes saved outbox messages and records publisher confirms. The sender can repeat a publish after an uncertain outcome. The worker still needs the stable job key.

The following tests cover the important gaps in this design.

Failure pointExpected result
Before the outbox publishThe saved message remains available for the sender.
After an external call, before the result commitThe next attempt checks ownership. External work can repeat.
After the result commit, before acknowledgementThe second delivery uses the stored result.
Two workers receive the same jobThe claim and attempt token protect the final database writes.

The useful guarantee is a controlled business effect. Queue delivery, task execution, and result storage remain separate events. Their failure paths need explicit rules.

Sources

  1. RabbitMQ: Consumer acknowledgements and publisher confirms.
  2. PostgreSQL: Unique constraints.
  3. PostgreSQL: Transactions.
  4. Celery: Tasks and retry behavior.
  5. Celery: Acknowledgement configuration.

← All writing