Production Workflows

Add Background Jobs and Retries to an Anthropic Workflow

Add Background Jobs and Retries to an Anthropic Workflow
Learn how to move multi-step Anthropic workflows out of synchronous request handlers and into reliable background jobs. This practical guide covers job state tracking, exponential backoff retries for transient rate limits, distinguishing permanent validation errors, and maintaining an immutable job history to ensure scalable, observable, and resilient AI-driven backend automation.

The first time I ran a batch of fifty document summaries inside a web request, the browser tab spun for almost four minutes and then timed out. Three of the Anthropic calls had hit transient rate limits; the rest had succeeded, but the user saw only an error page. I had no record of which documents had already been processed, no way to resume, and no automatic retry. That afternoon I moved the work into a background job with a simple retry policy and never put a multi-step Anthropic workflow back inside a synchronous request handler.

This post builds the smallest useful version of that pattern. We will take a single Anthropic task (the structured document summarizer from an earlier post), run it as a background job, add retries for the failures that are actually transient, and record enough state that we can see what succeeded, what failed, and what is still in progress. No Kubernetes, no managed queue service—just a clear job shape you can later move onto Celery, RQ, Sidekiq, or a cloud task queue.

As always:

Build the smallest useful version, then test what breaks.

What You Will Have Working by the End

  • A job function that performs one Anthropic call and returns a structured result

  • A simple in-memory job runner with explicit status tracking

  • Retry logic that distinguishes transient errors from permanent ones

  • A clear record of attempts, errors, and final outcomes

  • Three realistic failure modes and how to notice them early

The goal is a workflow that can survive a brief API blip without losing work or blocking a user.

Why Background Jobs Matter for Anthropic Calls

Anthropic requests are network calls. They can be slow, they can be rate-limited, and they can fail for reasons that have nothing to do with your prompt. When you run them inside a web request or a CLI that the user is watching:

  • The user waits for the slowest call.

  • A single transient error can fail the entire operation.

  • You have no natural place to record partial progress.

Moving the work to a background job gives you three things at once: the user gets an immediate “accepted” response, failed attempts can be retried automatically, and you can inspect the full history of each job later.

The Unit of Work

We treat one document summary as one job. The job function is deliberately small and side-effect free except for the Anthropic call itself.

Python

import json
import os
import time
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any

from dotenv import load_dotenv
from anthropic import Anthropic, APIError, APIStatusError, RateLimitError

load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

SYSTEM = """You are a precise document summarizer.
Return ONLY a valid JSON object with these keys:
- title: string
- one_sentence_summary: string
- key_points: array of 1-5 strings
- sentiment: "positive" | "neutral" | "negative"
Do not wrap the JSON in markdown. Do not add extra keys.
"""

def summarize_document(text: str) -> dict:
    """The core Anthropic call. Raises on failure."""
    response = client.messages.create(
        model="claude-sonnet-5",  # verify current ID in official docs
        max_tokens=512,
        system=SYSTEM,
        messages=[
            {"role": "user", "content": f"Summarize the following document:\n\n{text}"}
        ]
    )
    raw = response.content[0].text.strip()
    data = json.loads(raw)  # may raise JSONDecodeError
    required = ["title", "one_sentence_summary", "key_points", "sentiment"]
    for key in required:
        if key not in data:
            raise ValueError(f"Missing key in model output: {key}")
    return data

This function either returns a valid dictionary or raises. It does not retry. Retry policy lives one layer up.

Job Status and Record

A documentary close-up of a screen showing Python job status classes and record history schema definitions.

Python

class JobStatus(str, Enum):
    PENDING = "pending"
    RUNNING = "running"
    SUCCEEDED = "succeeded"
    FAILED = "failed"
    RETRYING = "retrying"

@dataclass
class JobRecord:
    id: str
    document_text: str
    status: JobStatus = JobStatus.PENDING
    result: dict | None = None
    attempts: int = 0
    max_attempts: int = 3
    last_error: str | None = None
    created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
    updated_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
    history: list[dict] = field(default_factory=list)

    def touch(self):
        self.updated_at = datetime.now(timezone.utc).isoformat()

    def add_history(self, event: str, detail: Any = None):
        self.history.append({
            "at": datetime.now(timezone.utc).isoformat(),
            "event": event,
            "detail": detail
        })
        self.touch()

Every job carries its own attempt count, last error, and a short history. In a real system this record would live in a database or a queue backend; for learning we keep it in memory.

Deciding What Is Worth Retrying

Not every error should be retried.

Python

def is_transient(error: Exception) -> bool:
    """Return True only for errors that are likely to succeed on retry."""
    if isinstance(error, RateLimitError):
        return True
    if isinstance(error, APIStatusError):
        # 429 and 5xx are usually transient
        return error.status_code == 429 or error.status_code >= 500
    if isinstance(error, APIError):
        # Network-level problems
        return True
    # JSON parse errors, validation errors, 4xx (except 429) are permanent
    return False

A rate limit or a 503 is worth retrying. A 400 caused by a bad prompt or a schema violation is not. Retrying permanent errors only burns tokens and delays the inevitable failure.

The Job Runner with Retries

Python

def run_job(job: JobRecord, base_delay: float = 1.0) -> JobRecord:
    """Execute the job with retries for transient failures."""
    while job.attempts < job.max_attempts:
        job.attempts += 1
        job.status = JobStatus.RUNNING
        job.add_history("attempt_started", {"attempt": job.attempts})

        try:
            result = summarize_document(job.document_text)
            job.result = result
            job.status = JobStatus.SUCCEEDED
            job.last_error = None
            job.add_history("succeeded", {"attempt": job.attempts})
            return job

        except Exception as e:
            error_msg = f"{type(e).__name__}: {e}"
            job.last_error = error_msg
            job.add_history("attempt_failed", {
                "attempt": job.attempts,
                "error": error_msg,
                "transient": is_transient(e)
            })

            if not is_transient(e) or job.attempts >= job.max_attempts:
                job.status = JobStatus.FAILED
                job.add_history("failed_permanently", {"error": error_msg})
                return job

            # Transient failure – schedule a retry
            job.status = JobStatus.RETRYING
            delay = base_delay * (2 ** (job.attempts - 1))  # exponential backoff
            job.add_history("retry_scheduled", {"delay_seconds": delay})
            print(f"Job {job.id}: transient error, retrying in {delay:.1f}s...")
            time.sleep(delay)

    job.status = JobStatus.FAILED
    return job

The policy is simple:

  • Retry only transient errors.

  • Use exponential backoff.

  • Stop after max_attempts.

  • Record every attempt in the job history.

    A documentary photo of a developer reviewing terminal logs for transient rate limit retries and job backoff delays.

A Minimal In-Memory Queue

Python

JOBS: dict[str, JobRecord] = {}

def enqueue(document_text: str, max_attempts: int = 3) -> str:
    job_id = str(uuid.uuid4())
    job = JobRecord(
        id=job_id,
        document_text=document_text,
        max_attempts=max_attempts
    )
    JOBS[job_id] = job
    job.add_history("enqueued")
    return job_id

def process_next() -> JobRecord | None:
    """Find one pending job and run it. Returns the job or None."""
    for job in JOBS.values():
        if job.status == JobStatus.PENDING:
            return run_job(job)
    return None

def get_job(job_id: str) -> JobRecord | None:
    return JOBS.get(job_id)

In production the enqueue call would push a message onto a real queue and a separate worker process would call run_job. The shape of the job record and the retry logic stay the same.

Putting It Together

Python

if __name__ == "__main__":
    sample = (
        "Acme Corp reported quarterly revenue of $42 million, "
        "an 18% increase year-over-year. Management expressed "
        "optimism about the next quarter despite supply-chain pressure."
    )

    job_id = enqueue(sample)
    print(f"Enqueued job {job_id}")

    finished = process_next()
    print(f"\nFinal status: {finished.status}")
    print(f"Attempts: {finished.attempts}")
    if finished.result:
        print("Result:", json.dumps(finished.result, indent=2))
    if finished.last_error:
        print("Last error:", finished.last_error)
    print("\nHistory:")
    for event in finished.history:
        print(f"  {event}")

When the call succeeds on the first try you see a single attempt and a succeeded status. When you simulate a rate limit (or temporarily lower the max tokens so the model returns incomplete JSON) you see the retry events and the eventual outcome.

Three Failure Modes Worth Testing

1. Transient Rate Limit

Force a RateLimitError (or temporarily use an invalid key that you then correct). Confirm the job retries with backoff and eventually succeeds once the condition clears. Confirm the history records each attempt.

2. Permanent Validation Error

Feed a document and a system prompt that reliably produces invalid JSON. Confirm the job fails on the first attempt without retrying and that the error is stored on the job record.

3. Exhausted Retries

Simulate repeated transient failures that exceed max_attempts. Confirm the job ends in FAILED, the history shows every attempt, and no further Anthropic calls are made.

I keep a small test harness that injects these three cases. Running it is part of every change to the retry policy.

Practical Rules That Keep Jobs Reliable

  • Make the core Anthropic function raise on failure; let the job layer decide whether to retry.

  • Distinguish transient from permanent errors with an explicit function, not an ad-hoc list of string matches.

  • Record every attempt. When a job finally fails, the history is the only way to understand why.

  • Prefer exponential backoff with a modest ceiling over aggressive immediate retries.

  • Never put a multi-step Anthropic workflow inside a user-facing request handler. Accept the work, return a job ID, and let the user poll or receive a callback.

What This Setup Does Not Do Yet

It does not:

  • Persist jobs to a database or Redis

  • Run multiple workers concurrently

  • Provide a webhook or UI for job status

  • Handle fan-out (one request → many document jobs) or fan-in (wait for all children)

  • Apply global rate limiting across many jobs

Those capabilities belong to later infrastructure posts. The goal today is a single-job shape with honest retries and visible history.

Verification Checklist

  1. Enqueue a normal document and confirm the job succeeds on the first attempt.

  2. Simulate a transient error and confirm the job retries and eventually succeeds (or fails after max attempts).

  3. Simulate a permanent validation error and confirm there is no retry.

  4. Inspect the job history and confirm every attempt is recorded with a timestamp and error detail.

  5. Confirm that a completed job (succeeded or failed) is never run again by the simple runner.

If all five steps pass, you have a working background-job pattern for Anthropic workflows.

Update Note

Anthropic’s error types and rate-limit behavior can change. Always verify the current exception hierarchy and recommended retry guidance in the official documentation and the Python SDK. The job-record shape and the transient-vs-permanent distinction remain useful regardless of those surface details.

Looking Ahead

We have now completed the first four Production Workflow posts: structured summarization, human-reviewed triage, a research assistant with source tracking, and background jobs with retries. The next set of posts moves into Testing, Evaluation, and Debugging—how to build small evaluation sets, how to test structured outputs when the model sometimes deviates, and how to measure latency, cost, and quality in the same experiment.

Keep the job runner. When you later move it onto a real queue, you will already have the retry policy, the status model, and the history that make a background Anthropic workflow observable and recoverable.

Build the smallest useful version, then test what breaks.

— Caleb Fletcher

Boise, Idaho

Updated · 2026-10-24 10:53
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Context & Tools. All rights reserved. data-driven, published weekly ♥