Run a durable ingestion pipeline
Process ingestion jobs in a worker that survives crashes, retries safely and parks poison messages.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.
In short
A worker is a separate process that takes ingestion jobs and runs the slow steps: download, extract, chunk, embed and index. It must survive crashes, retry without creating duplicates, and park jobs that keep failing in a dead-letter state. The hard part is keeping the database and the queue consistent when a crash hits between two writes.
Think of it like this: A good kitchen ticket system: every order is on a ticket, a cook claims one at a time, and a burnt dish goes to a shelf for the manager instead of being cooked forever.
Explained simply
After the upload, someone still has to do the real work: read the file, pull out the text, split it into chunks and create embeddings. That job goes to a worker, a separate program that runs in the background and takes jobs one at a time.
Things go wrong. The worker can crash halfway. The embedding service can be down. A file can be broken. A durable worker is one that copes with all of this. It records what state every job is in, so after a restart it knows what to pick up again.
Retries are normal, so the work must be idempotent. That word means doing it twice gives the same result as doing it once. If a job saves chunks and then crashes, the retry must not save a second copy of every chunk.
Some jobs will never succeed, such as a corrupt PDF. Retrying them forever wastes money and blocks other work. After a fixed number of attempts, the job moves to a dead-letter state, a parking place where a person can look at the error and decide what to do.
Press Play on a diagram to walk through it one step at a time.
- 1queued
Created by the API or released after a failure
- 2running
Claimed by one worker with a lease
- 3succeeded or failed
Success ends; a failure with retries left waits for backoff
- 4retry scheduled
attempts + 1, run_after set in the future
- Back to step 1
- Validates and stores the upload
- Writes document and job rows
- Answers fast with 202
- Reads job status for polling
- Claims one job at a time
- Extracts, chunks and embeds
- Writes chunks in one transaction
- Marks success, retry or dead letter
- Temporary
- Timeout
- 429 rate limit
- 503 from provider
- Permanent
- Corrupt or encrypted file
- Unsupported format
- Document deleted
- Worker crash
- Lease expires
- Another worker reclaims
- Out of attempts
- Status dead_letter
- Alert and manual replay
In depth
A queue in Postgres or a separate broker
You can build the queue on the jobs table itself. Workers claim a row with SELECT ... FOR UPDATE SKIP LOCKED, which locks the row for this transaction and makes other workers skip it instead of waiting. This needs nothing beyond Postgres, keeps job state and data in one place and is plenty for many thousands of jobs per hour.
A separate broker such as RabbitMQ, Redis Streams, Amazon SQS or Azure Service Bus adds higher throughput, routing and built-in dead-letter queues. The cost is a second system whose state must be kept in step with the database. Whichever you pick, delivery is at least once: a message can arrive twice, so the handler must be idempotent.
- Postgres queue: one system, transactional, simple
- Broker: more throughput and features, one more thing to run
- Both: at-least-once delivery
- Both: need leases or visibility timeouts
Making each step idempotent
Write the pipeline so every step can run again safely. Derive IDs from stable inputs: a chunk's key is (document_id, embedding_version, chunk_index), not a random UUID per attempt. Replace instead of append: in one transaction, delete the chunks for this document and version, then insert the new set. Or upsert with INSERT ... ON CONFLICT DO UPDATE.
Check before expensive calls. If chunks for this checksum and embedding version already exist, skip the embedding call and just mark the job done. Store the result of each stage (extracted text, chunk list) so a retry can resume from the last finished stage instead of starting over.
- 1Claim job
Lease for five minutes
- 2Extract text
Skip if text for this checksum exists
- 3Chunk
Stable chunk_index for each piece
- 4Embed
Batch calls; retry 429 and 5xx with backoff
- 5Replace chunks
Delete and insert in one transaction
- 6Mark succeeded
Same transaction as the chunks
Retries, backoff and the dead-letter path
Classify failures. Temporary ones, such as a timeout or a 503 from the embedding provider, are worth retrying. Permanent ones, such as a password-protected PDF, are not. For temporary failures, set run_after to now plus an exponential delay with random jitter (for example 10 s, 40 s, 160 s, each plus up to 50 percent) so retries do not all arrive together.
When attempts reach the maximum, or the error is permanent, set status to dead_letter and save the error code and a short message. Expose these jobs in an admin view or a metric. A replay action resets attempts and status to queued after someone fixes the cause.
Crashes between the database and the queue
With a separate broker, the API must both insert the job row and publish a message. If it commits the row and crashes before publishing, the job is never processed. If it publishes first and the commit fails, the worker gets a job that does not exist.
The transactional outbox fixes this. In the same transaction as the document and job rows, insert a row into an outbox table. A small relay process reads unsent outbox rows, publishes them and marks them sent. If the relay crashes after publishing but before marking, the message goes out twice, which is fine because consumers are idempotent. A periodic sweeper that requeues jobs stuck in queued or with expired leases is a useful second safety net.
- API to Postgres: BEGIN; insert document, job, outbox row; COMMIT1BEGIN; insert document, job, outbox row; COMMIT
- Outbox relay to Postgres: Read unsent outbox rows2Read unsent outbox rows
- Outbox relay to Queue: Publish job message3Publish job message
- Outbox relay to Postgres: Mark outbox row sent4Mark outbox row sent
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Split API and worker duties~50m
- 2Model job states~50m
- 3Make retries idempotent~50m
- 4Add a dead-letter path~50m
- 5Recover between DB and queue writes~50m
Key points
- Keep the API and the worker as separate processes so slow jobs never block requests.
- Store job state in Postgres; claim work with SELECT ... FOR UPDATE SKIP LOCKED or a queue with acknowledgements.
- Make every step idempotent: running a job twice must leave the same result as running it once.
- Cap attempts and move jobs that keep failing to a dead-letter state with the last error.
- Use a transactional outbox so a crash between the database write and the queue publish loses nothing.
Key terms
Tap a card to flip it. 0/6 known
Examples
-- Claim one job; concurrent workers skip rows already locked
UPDATE jobs SET status = 'running', attempts = attempts + 1,
lease_until = now() + interval '5 minutes'
WHERE id = (
SELECT id FROM jobs
WHERE (status = 'queued' AND run_after <= now())
OR (status = 'running' AND lease_until < now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, document_id, attempts;Expired leases make jobs from crashed workers claimable again.
A worker crashes in the middle of embedding
Step 1: worker A claims job 42 with a five-minute lease and attempts = 1. Step 2: it extracts text and has embedded half the chunks when the container is killed. Nothing was committed, because chunks are written in one transaction at the end. Step 3: five minutes later the lease expires. Step 4: worker B claims job 42, attempts = 2. Step 5: B finds extracted text for this checksum and reuses it, embeds all chunks, replaces them in one transaction and marks the job succeeded. The tenant sees one copy of each chunk.
A minimal worker loop with a dead-letter path
The loop claims one job, runs it and records the outcome. Temporary errors schedule a retry with backoff and jitter. Permanent errors or too many attempts go to dead_letter. The sleep when idle keeps the loop from hammering the database.
async def run_worker(): # MAX_ATTEMPTS = 5 in settings
while True:
job = await repo.claim_next_job()
if job is None:
await asyncio.sleep(1); continue
try:
await ingest(job) # idempotent pipeline
await repo.mark_succeeded(job.id)
except TemporaryError as e:
if job.attempts >= MAX_ATTEMPTS:
await repo.mark_dead_letter(job.id, str(e))
else:
await repo.schedule_retry(job.id, backoff_with_jitter(job.attempts))
except PermanentError as e:
await repo.mark_dead_letter(job.id, str(e))Quick reference
- Claim jobs with SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1.
- Use a lease (lease_until) so jobs from crashed workers are reclaimed.
- Chunk key = (document_id, embedding_version, chunk_index), not a random UUID.
- Write chunks and mark the job succeeded in the same transaction.
- Backoff with jitter: base * 4^attempt plus a random extra.
- Permanent error or max attempts reached: status dead_letter, keep the error.
- Outbox: write the event with the data; a relay publishes it later.
Common mistakes
- Inserting chunks with plain INSERT on retry, which doubles them; delete-then-insert or upsert by (document_id, version, chunk_index).
- Retrying forever on a corrupt file instead of stopping after a fixed number of attempts.
- Committing the job row and then publishing to the queue in a separate step with nothing to repair a crash in between.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Draw the job states for your pipeline and list which status change each component (API, worker, sweeper, admin) is allowed to make.
- Exercise 2medium
Run two worker processes against the same Postgres jobs table with 20 queued jobs. Prove that no job is processed twice and every job finishes.
- Exercise 3hard
Simulate a crash between committing the job row and publishing to a queue, then add an outbox table and relay so the job is still processed.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need Celery, RabbitMQ or Kafka for this?
- Not to start. A Postgres jobs table with SKIP LOCKED is durable and transactional. Move to a broker when throughput or routing needs outgrow it.
- Can I use FastAPI BackgroundTasks instead of a worker?
- BackgroundTasks run in the same process after the response, so a restart loses them and they share the API's CPU. They suit small chores like sending an email, not durable ingestion.
- What is the difference between a lease and a lock?
- A row lock lasts only while the transaction is open. A lease is a timestamp column, so a job can stay claimed across several short transactions and still be reclaimed if the worker dies.
- How many retries are reasonable?
- Three to five attempts with exponential backoff covers most temporary outages. After that, a person should look at the dead-letter job.