Make Background Jobs Safe to Redeliver

Published · System Administration

The worker updates the account balance, commits, and dies before it acknowledges the job. The queue still has work as far as the broker is concerned. The database already has a new balance. When another worker gets the delivery, should it add the credit again?

That little gap between committing work and acknowledging it is where a background job earns its reliability. Design the second attempt to find the result of the first one. Then a worker can crash at the worst possible moment without making the customer the reconciliation system.

Give the business operation a durable identity

Start by deciding what may happen only once. In this example, it is the credit authorized for one particular service adjustment. Assign an operation ID when that adjustment is accepted and persist it alongside the authorized amount and account. Every enqueue retry, worker retry, and manual replay of that adjustment carries the same ID. A second legitimate adjustment gets its own ID even if the numbers are identical.

Delivery tags identify deliveries for the broker protocol. An application operation ID answers a different question, namely whether this particular business action already took effect. A producer can publish the same intent in two separate messages, so even the first delivery of a message can refer to work that has already finished. RabbitMQ documents channel-scoped delivery tags, automatic requeue of unacknowledged deliveries on channel or connection closure, and the separate roles of consumer acknowledgments and publisher confirms. See the RabbitMQ acknowledgment guide.

Prefer sending just the operation ID if the worker can load the authorized inputs from an immutable record. If the message carries inputs too, validate them against the stored intent. An existing ID paired with a different account or amount is a conflict that deserves investigation. Never bless it as a successful duplicate.

Put the claim and the effect in one transaction

Assume PostgreSQL holds the immutable adjustment requests, the account balances, and an applied-adjustment table with a primary key on operation ID. The following is worker pseudocode. The database transaction runs at Read Committed, and all three tables live in the same database.

BEGIN
  request = load authorized adjustment by operation_id
  if request is missing:
      ROLLBACK and classify the delivery
      return

  inserted = INSERT INTO applied_adjustments (operation_id)
             VALUES (request.id)
             ON CONFLICT (operation_id) DO NOTHING
             RETURNING operation_id

  if inserted:
      updated = UPDATE accounts
                SET balance_cents = balance_cents + request.amount_cents
                WHERE account_id = request.account_id

      if updated.row_count != 1:
          ROLLBACK and classify the delivery
          return
COMMIT
ACK this delivery on its channel

The unique constraint arbitrates concurrent attempts. If two workers race, the losing insert can wait for the other transaction. A committed competing insert prevents the second credit. If the first transaction rolls back, the other can acquire the claim and apply the credit. PostgreSQL documents that at Read Committed, an insert with ON CONFLICT DO NOTHING can skip insertion because of a concurrent transaction even when the conflicting row was invisible to the statement snapshot. See the PostgreSQL transaction isolation documentation.

The claim exists durably only if the credit commits with it. A worker that commits the claim first and then crashes can turn a valid retry into a permanently missing credit. A worker that checks for an existing claim in application code before issuing an unguarded update can let two attempts race past the check. Keep the transaction short and bound waits. If a database operation times out or the transaction aborts, classify the error and retry the whole transaction when appropriate.

Use precise names for the evidence. In this example, a row in applied adjustments is evidence that the balance mutation committed. Keep it for at least as long as a duplicate can plausibly arrive, including delayed retries, queue restoration, and operator replay. If old requests remain executable after the record disappears, deleting the record reopens the operation.

Recover from the attempt whose result you cannot see

A disconnected database client may have lost the response to a commit that succeeded. Treat the outcome as unknown and retry using the same operation ID. A normal successful commit followed by an uncertain acknowledgment leads to the same answer if the broker delivers again. The next attempt resolves the business outcome using the database.

Failure point Durable result Next handling
The worker dies before the transaction commits Neither the claim nor the credit committed, assuming rollback Run the same transaction on redelivery.
The connection drops during commit Outcome unknown to the worker Leave the delivery unacknowledged and resolve using the same operation ID.
The transaction commits and the worker dies before acknowledgment One credit and its claim Return from the duplicate path and acknowledge the new delivery.
Two different messages carry the same operation The database serializes the claims Apply the credit once and acknowledge both successful outcomes.
The account update fails permanently The transaction rolls back Quarantine the delivery with the operation ID and failure reason.

Keep transient retries bounded and spaced. Tight requeue loops turn an outage into extra work for the broker and database. Record the operation ID, attempt outcome, and failure class in logs, and track aggregate rates for duplicate suppression, unknown outcomes, and quarantined jobs. Repeated failures need an owner and a way to check applied state before replay. The dependency failure guide covers the complementary retry and timeout decisions.

Handle effects outside the database separately

A local transaction cannot roll back an email or a remote payment. A transactional outbox can commit an instruction to send alongside the local state change. Its publisher can still crash after sending and before recording that it sent. Give the next consumer a stable event ID, and give an external API a stable idempotency key when its contract supports one.

Read the provider's retention and parameter rules before promising automatic recovery. Stripe, for example, documents that keys may be removed after at least 24 hours. A replay after removal can create a new request. If the provider's deduplication horizon has expired or its response is ambiguous, query a durable provider reference if available or route the operation to reconciliation before trying again. See Stripe's idempotent request documentation.

Test the crash window before you need it

In a test environment, interrupt the worker after commit and before acknowledgment. Replay the same operation concurrently, including as two independently published messages. Check the account delta and the number of applied records, then verify the broker can clear the deliveries. Repeat with a forced rollback and a mismatched input if the message carries any. For an external effect, simulate losing the response and verify your reconciliation path before enabling automatic replay.

The same exercise makes graceful shutdown easier to reason about. Once a second worker can recover, the first worker can have a finite shutdown budget. A job is ready to redeliver when you can point to the durable evidence that tells the next worker what happened. For more engineering guides, visit Slaptijack.

Slaptijack's Koding Kraken