Paj Digital Labs
All articles
AI & Automation

Durable AI Jobs: Queues, Retries and the Cost of Doing Work Twice

Long AI tasks need a job record, bounded retries and resumable steps. A loading spinner cannot tell you whether a timed-out request already created the report or charged for another generation.

Paj Digital Labs 4 min read
Robotic gripper sorting components on a laboratory workbench
Editorial illustration · AI & Automation

A user requests a lengthy document analysis. The browser waits, the network drops, and the user clicks again. You now have two model calls, two bills and possibly two contradictory reports. The failure was not that the model took too long. The failure was treating a durable task as a single web request.

Queues and job records separate acceptance from execution. The browser can receive a job ID promptly, and the worker can finish independently. That does not make retries magically safe; it gives you somewhere to manage them deliberately.

Define the unit of work

A job should describe an outcome: analyse this authorised document revision using this workflow version. Store references to input, not a giant prompt copied into every queue message. Freeze the input revision so a resumed task does not silently process different data.

Record who requested the job, what permissions applied, the workflow version, current state and result location. Do not put private document content into a public queue dashboard or a URL.

A practical state model might include queued, running, succeeded, failed and cancelled. If cancellation is best-effort, say so. A model call already accepted by a provider may still complete and incur cost after your local cancellation flag changes.

Accept duplicate requests deliberately

Use an idempotency key scoped to the authenticated requester and the intended operation. Repeated submission of the same request should return the existing job rather than creating a new one.

sql
CREATE TABLE analysis_jobs (
  id uuid PRIMARY KEY,
  requester_id uuid NOT NULL,
  request_key text NOT NULL,
  input_revision text NOT NULL,
  workflow_version text NOT NULL,
  status text NOT NULL,
  attempt_count integer NOT NULL DEFAULT 0,
  lease_until timestamptz,
  result_ref text,
  UNIQUE (requester_id, request_key)
);

This PostgreSQL example sketches the state record. Add your actual permission policies, validation and state constraints. A client-supplied request key is not a substitute for checking whether the requester may read the document.

If the same key is reused with a different input, reject the mismatch. Returning an unrelated old result is just a quieter form of data corruption.

Expect at-least-once delivery

Many queue systems can deliver a message more than once. A worker can crash after saving a result but before acknowledging the message. Another worker then receives it.

Claim work through an atomic state transition or the queue's documented lease mechanism. Keep a lease expiry so a crashed worker does not own the job forever. Use an attempt token or version check when committing results so an expired worker cannot overwrite a newer attempt's output.

A lease reduces concurrent execution; it does not ensure a provider call occurs exactly once. If the provider supports an idempotency mechanism for the operation, use it as documented. Otherwise design for the possibility of duplicate external work and control its cost.

Retry only failures that may recover

Transient network errors, certain provider server errors and rate limits are candidates for retry. Invalid inputs, unsupported file formats, permission failures and an exceeded job budget generally are not.

Use bounded exponential backoff with jitter, respect Retry-After when provided and cap attempts. A hundred queued jobs all retrying exactly one second later can prolong the outage that caused them to fail.

Keep a maximum elapsed time and a per-job resource budget. Retrying a large context until it succeeds is not a policy; it is an unbounded invoice. Record why the job stopped so support can distinguish a validation failure from provider unavailability.

Break the workflow into checkpoints

A multi-document report may have extraction, section analysis and final synthesis steps. Persist successful step outputs with their input fingerprint and workflow version. On retry, reuse a valid completed step rather than paying to regenerate everything.

Do not reuse outputs across users just because two prompts look similar. The documents and permission context may differ. Any shared caching needs an explicit privacy and tenancy design.

For side effects such as emailing the report, use a separate delivery record or outbox with a stable identity. Generation success and notification success are different states. A mail retry should not regenerate the report.

Provide a truthful status screen

Let the browser ask for status or subscribe through an appropriate update mechanism. Enforce access on the status endpoint as carefully as on the result download. A guessable job ID must not expose another user's report.

Show accepted, processing, completed or failed states that reflect stored facts. Avoid a fabricated 97 percent progress value for an opaque model call. If you know that three of five independent documents are done, report that concrete progress instead.

When the user reloads or changes devices, the job should still be discoverable. The browser's loading state is not the system of record.

Exercise crash windows

Test failure before the provider call, after provider acceptance, after result storage and before queue acknowledgement. Deliver a duplicate message. Expire a lease while the old worker is still alive. Cancel a task during a long step.

Check whether results remain consistent and whether notifications are duplicated. Track queue age, attempts, failure categories and spend per completed outcome, not just average model latency.

The useful queue is not the one that makes work look asynchronous. It is the one that lets you explain what happened, resume safely and avoid turning every network wobble into another full-price analysis.

Paj Digital Labs

The engineering journal of Paj Digital Solutions — hosting, server infrastructure and web engineering, written by the people who run the servers.

Related reading