The direct answer

A small API does not need enterprise infrastructure to run reliable background jobs. It needs four things:

  1. A clear queue boundary: accept the request quickly, persist a job, and move slow or failure-prone work out of the request path.
  2. A retry policy based on failure type: retry transient failures, but do not repeatedly retry invalid work or permanent errors.
  3. Idempotent handlers: assume the same job can run more than once.
  4. Visible recovery: track attempts, preserve failure context, and give stuck work a controlled path back into the queue.

The important design principle is simple: queueing and idempotency solve different problems. A queue moves work and retries it. Idempotency ensures that running the work again does not create duplicate side effects.

For a founder, this protects more than uptime. It prevents one customer request from becoming three emails, three invoices, or three AI-generation charges. It also keeps temporary infrastructure failures from turning into manual support work.

Start with the queue boundary

The purpose of a background queue is not to hide latency. It is to separate work that should happen immediately from work that can safely continue after the API response.

A good boundary usually has these properties:

  • The API request can validate the request and create a job record quickly.
  • The response returns a stable job identifier, not a false promise that processing has finished.
  • The worker can process the job independently of the original HTTP connection.
  • The job record survives an API process restart.
  • A customer or internal operator can determine whether the job is queued, running, completed, or failed.

Before adding a queue, ask whether the work actually needs one. A short database update that completes within the request budget may be simpler and more reliable in-process. A call to an AI provider, a video renderer, a large export, or a third-party service with uncertain latency is usually a good candidate for asynchronous processing.

The wrong boundary is equally common: putting a slow external call in the request path and then adding retries there. That holds customer connections open and can turn one timeout into several repeated external calls. Move the work to a job system and let the API acknowledge that it has been accepted.

What should happen when the API accepts a job?

A dependable flow looks like this:

  1. Validate the request.
  2. Create a durable job record with a unique ID and status such as queued.
  3. Enqueue a reference to that job.
  4. Return the job ID and a status URL.
  5. Let a worker claim the job and change its status to running.
  6. Record the result or failure reason.
  7. Mark the job succeeded or failed.

The durable job record matters because queue delivery alone may not tell you whether work was accepted. If the API writes the record and fails while enqueueing, a dispatcher can find unqueued jobs later. If the API enqueues first and crashes before recording the job, the worker may receive work the system cannot track.

For most small APIs, a database row plus a lightweight queue is enough. The exact product is less important than the contract between the API, queue, and worker.

Treat delivery as at-least-once

Do not design a background system that assumes a job message arrives exactly once. A worker can crash after completing a side effect but before recording success. A network timeout can also leave the producer unsure whether the queue accepted the message.

In both cases, retrying is safer than dropping the work. That creates at-least-once delivery: a job may execute one time or several times.

This is not automatically a design flaw. AWS documentation makes the same distinction: durable-execution steps use at-least-once semantics by default, and Lambda durable functions can prevent duplicate execution starts while still requiring business logic to tolerate retries within an execution. The practical lesson is that duplicate prevention belongs at the side-effect boundary, not only in the queue.

Ask one question for every job:

If this exact job runs again after appearing to fail, what could happen twice?

Possible answers include:

  • Sending an email or SMS
  • Charging a payment
  • Creating a third-party resource
  • Generating an AI response and incurring another provider charge
  • Updating a counter
  • Publishing an event
  • Creating a subscription

Each answer needs either an idempotent implementation or a deliberate strategy that prevents unsafe replay.

Make the job handler idempotent

Idempotency means that repeating an operation with the same logical input does not add another side effect. The first execution may perform the work; later executions should return the existing result or safely repeat the operation.

The easiest pattern for a small team is a three-state job record:

  • running or pending: the operation has not completed.
  • succeeded: the result is stored and should be returned on replay.
  • failed: the operation failed, subject to the retry policy.

Before performing a non-idempotent side effect, the worker checks for a completed record with the same logical operation key. If one exists, it returns that result without repeating the side effect.

A practical schema can be as small as:

jobs
----
id                unique job identifier
operation_key     deterministic key for the logical operation
status            queued | running | succeeded | failed
attempt_count     number of worker attempts
result            serialized result when successful
last_error        failure context from the latest attempt
locked_until       lease expiry for the current worker
created_at        creation time
updated_at        last state change

Make operation_key unique for the logical operation. If two workers receive the same job simultaneously, a conditional write or database uniqueness constraint should allow only one to transition it from queued to running.

This is important. A simple “check, then write” sequence has a race: both workers can check before either writes. The uniqueness constraint or conditional update closes that gap.

Use a stable operation key

The key must remain the same across retries of the same logical operation. Generating a fresh UUID during each retry defeats the purpose because every attempt looks new.

Derive it from stable inputs, such as:

operation_key = hash(
  customer_id,
  operation_type,
  canonical_request_fields
)

Use canonical inputs. Normalize the relevant request fields so harmless differences in ordering or formatting do not create different keys. At the same time, include every field that changes the operation’s meaning. Two export jobs for the same report may legitimately be separate operations if the user explicitly requests two exports.

An alternative is to generate one key at request acceptance and persist it with the job. That key is then reused for every attempt. This is often simpler than deriving it inside the worker.

Avoid using only a timestamp, a random value generated during retry, or the current worker attempt number. Those values describe an attempt, not the logical operation.

Store the result, not only the side effect

A durable result turns a duplicate delivery into a cheap replay. If the job succeeds, save enough information to return the same outcome later:

  • The external resource ID
  • A confirmation identifier
  • A URL for the generated artifact
  • A normalized response body
  • The completed timestamp

On replay, return the stored result rather than invoking the external system again.

This works particularly well for jobs that can be reconciled against an external system. Suppose an AI provider request times out after accepting the work. Before sending it again, check whether the provider exposes a request ID, lookup endpoint, or status resource. If it does, use that to determine whether the original request succeeded. AWS guidance supports passing idempotency tokens through multi-step workflows and into external systems that support their own idempotency mechanisms.

Reconciliation is the next best control when an external API does not support idempotency. “Did it happen?” is often safer than “Run it again and hope.”

Build a retry policy, not a retry loop

Retries are appropriate for temporary failures such as a connection reset, timeout, rate limit, or temporary dependency failure. They are wasteful or harmful for invalid input, missing resources, authentication failures, or malformed requests.

Use a small classification:

Failure Default response
Network timeout or connection reset Retry with backoff
Dependency rate limit Retry after the indicated delay
Dependency temporarily unavailable Retry with backoff
Invalid request or business-rule rejection Fail without automatic retry
Authentication or permission failure Fail and alert the operator
Side effect completed but result was not recorded Reconcile or replay idempotently

Add jitter to backoff so a burst of failed jobs does not retry in lockstep. Also cap the number of attempts. A dead-letter or failed state after the cap gives operators a concrete item to inspect instead of an invisible task cycling forever.

AWS Batch exposes similar concepts: retry strategies can respond to exit conditions, while jobs that are cancelled, terminated, or invalid may not be retried. The platform-specific numbers are not the important lesson. The lesson is to distinguish retryable failures from terminal failures.

Do not use a separate retry system inside the worker if the queue already retries failed jobs. Two independent retry layers can multiply attempts: three queue deliveries multiplied by three worker retries becomes nine executions. Choose one primary retry owner and make the other layer predictable.

Protect the handler from concurrent execution

A queue may deliver a message more than once, and two workers may receive it at nearly the same time. Use a lease or claim mechanism:

  1. Atomically update the job from queued to running only if it is still claimable.
  2. Attach a short lease expiry to the claim.
  3. If the worker crashes, allow another worker to reclaim the job after the lease expires.
  4. Extend the lease for long-running work or use frequent heartbeats.

The lease is not a promise of exactly-once execution. It limits overlap. Idempotency remains necessary because a worker can perform the side effect and then die before saving success.

Make lease duration comfortably longer than the normal execution time, but not so long that recovery after a crash becomes painfully slow. Long AI or media jobs may need heartbeats; short database transformations usually do not.

Decide what each side effect can safely repeat

Not every operation deserves the same engineering effort. Classify handlers using the AWS pattern of matching execution semantics to the side effect:

  • At-least-once: suitable for reads, upserts, deterministic recalculations, and calls that accept an idempotency key.
  • At-most-once: safer for one-shot effects such as charging a card or sending a one-shot SMS, but only with strict control over retry behavior. The AWS Durable Execution SDK describes at-most-once as preventing a step from being re-executed within a retry attempt, while noting that it is not an end-to-end exactly-once guarantee.

For a payment, a more reliable approach may be to authorize with an idempotency key, store the authorization ID, and reconcile if the response is lost. If the provider does not support that, route it through an operation designed for manual review rather than repeatedly sending it.

For AI generation, use a provider request ID where available. Also record the provider, model, prompt or input reference, generation request ID, and billable usage. That allows support to answer “Was this generated twice?” and provides the data needed to investigate abnormal cost growth.

Make failure states useful

A failed job is only useful if an operator can understand it. Capture:

  • The last error category and sanitized message
  • Attempt count
  • First and last failure timestamps
  • Provider or dependency name +- Retry decision +```

+Do not store secrets or sensitive customer payloads in an unrestricted error field. Sanitize logs and truncate upstream responses. + +Also record enough request context to reproduce a safe retry. If the original payload may contain personal data, store a reference to the secured source rather than duplicating it across logs and failure views. + +Expose a small operational view rather than a separate enterprise control plane. For a small team, a database query or compact admin page can answer: + +- How many jobs are queued, running, failed, and succeeded? +- Which jobs are approaching their retry limit? +- Which jobs have failed most often? +- Are delays growing because workers are unavailable or jobs are too slow? +- Are cache hits or idempotency replays increasing after a deployment? + +AWS’s idempotency guidance recommends monitoring idempotency-store health and cache-hit rates because retries returning cached results are evidence that duplicate prevention is working. + +## A minimal failure-recovery checklist + +Use this before launch and after changing the worker or queue provider. + +### Request acceptance + +- The API validates input before creating work. +- A durable job record is written before the response. +- The response returns a job ID and status location. +- Enqueue failure is recoverable; it does not leave an untracked job. + +### Queue behavior + +- The queue and worker have separate failure domains. +- Visibility timeouts or leases cover normal execution time. +- A crashed worker’s job becomes claimable again. +- Queue depth and oldest-job age are visible. + +### Retry behavior + +- Transient failures are classified separately from permanent failures. +- Backoff and an attempt cap are configured. +- There is only one primary retry layer. +- Retry delay respects provider rate-limit guidance. +- Cancelled or invalid jobs do not loop forever. + +### Idempotency + +- Every logical operation has a stable key. +- The key is stored with the job and reused on every attempt. +- A unique constraint or conditional write protects the state transition. +- A successful result is stored before the job is reported complete. +- Replaying a completed job does not repeat the side effect. +- Keys are propagated to downstream steps and supported external APIs. + +### Side effects + +- Emails, payments, AI calls, exports, and webhooks are individually classified. +- External APIs that support idempotency receive the stable key. +- APIs without idempotency have a reconciliation or manual-review path. +- Logs and job records exclude secrets and unnecessary sensitive payloads. + +### Recovery drill + +- Kill a worker during processing and confirm the job is reclaimed safely. +- Simulate a lost success response and confirm no duplicate side effect occurs. +- Force one job past its retry limit and verify that it reaches a visible failed state. +- Restore queue or worker availability and confirm stalled jobs resume. + +A recovery drill is more valuable than a diagram claiming the system is exactly once. It tests the points where your assumptions can break. + +## Common failure patterns + +### Retries without idempotency + +The queue works, but a timeout happens after the email is sent. The retry sends another email. Fix the operation, not merely the queue: accept an operation key, store the sent message ID, and return it on replay. + +### A fresh key on every retry + +The worker regenerates its request ID before each attempt. The provider sees a new operation and charges again. Persist the key at acceptance or derive it deterministically from the logical operation. + +### A check without a concurrency guard + +Two workers both see no completed record and both execute the side effect. Use a database uniqueness constraint, conditional update, or lease claim so only one execution owns the operation. + +### Success recorded only after an irreversible call + +The provider completed the work, but the process died before the local status changed. On retry, the provider is called again. Prefer a provider request ID and reconciliation. If reconciliation is impossible, document the residual duplicate risk and require human review. + +### Retries for every error + +Invalid input fails ten times, delaying diagnosis and consuming worker capacity. Retry only failures likely to change on another attempt. + +### A queue without durable status + +The queue shows a message, but the API cannot answer whether the customer’s job succeeded. Maintain a durable job record and treat the queue as transport, not the system of record. + +## The small-team implementation decision + +Do not begin by selecting the most feature-rich queue. Begin with the operational contract:

+1. Can the API durably record accepted work? +2. Can a worker reclaim work after a crash? +3. Can every non-idempotent side effect be identified? +4. Can a repeated logical operation return the same result? +5. Can an operator see and resolve terminal failures? + +If the answers are yes, the queue product can remain deliberately boring. A managed queue plus a relational job table may remove more operational pain than adding a separate workflow platform.

+That is the real goal: not “enterprise-grade” job infrastructure, but fewer duplicate outcomes, faster recovery, and less founder time spent manually investigating invisible failures. + +## Frequently asked questions + +### Do I need exactly-once delivery?\n+ +Usually, no. Aim for an at-least-once queue plus idempotent side effects. Exactly-once delivery across databases, queues, networks, and external APIs is difficult to guarantee end to end. Stable operation keys, conditional writes, reconciliation, and stored results provide a more achievable safety net. + +### Can I use the job ID as the idempotency key?\n+ +Yes, if the job ID is created once, persisted, and reused for every delivery of that job. The key must represent the logical operation. A new ID generated during each retry will not work. + +### Should every job have an idempotency record?\n+ +Not necessarily. Pure reads and deterministic recomputations can be retried safely. Create explicit idempotency state for jobs that send messages, charge users, call non-idempotent external APIs, or otherwise create observable side effects. A durable job record can serve both purposes if designed well. + +### How long should idempotency records remain?\n+ +Keep them longer than the longest possible retry, reconciliation, and customer-reporting window. The exact duration depends on your business and upstream limits; it is not a universal number. A time-to-live policy can control storage growth, but deleting a record prematurely reopens the duplicate risk. + +### Is a database-backed job table enough for a small API?\n+ +Often, yes. It is especially reasonable when work volume and recovery requirements are modest. Add a dedicated queue only when you need stronger delivery behavior, independent worker scaling, scheduling, or workload isolation. The architecture should follow the failure modes you actually have. + +## Sources + +- https://docs.aws.amazon.com/wellarchitected/latest/agentic-ai-lens/agentrel06-bp04.html +- https://docs.aws.amazon.com/lambda/latest/dg/durable-execution-idempotency.html +- https://docs.aws.amazon.com/durable-execution/patterns/best-practices/idempotency +- https://docs.aws.amazon.com/batch/latest/userguide/job_retries.html +- https://docs.aws.amazon.com/AmazonECS/latest/APIReference/ECS_Idempotency.html