Playground

Build log

Building a RAG ingestion pipeline in Python - and checking whether its retries actually retry

A RAG ingestion pipeline in Python: FastAPI, a Redis reliable queue, Qdrant and deterministic chunk IDs - what holds up, and five fixes before production.

By Winson GR · · 12 min read · Source on GitHub

Most RAG tutorials start at the query. The part that decides whether answers are any good happens earlier, when documents are chunked, embedded and indexed. That part is a batch pipeline with the usual problems: slow work, crashes halfway through and duplicate requests. This post walks through a Python ingestion engine built for them, with FastAPI, PostgreSQL, a Redis reliable queue, a worker and Qdrant. The full source, tests and Docker setup are on GitHub.

The headline result: a 100 KB text document becomes 223 chunks and about 1.37 MB of vectors, duplicate submissions are absorbed by a UNIQUE constraint, and re-indexing a document overwrites its vectors instead of duplicating them. But the 3 retries before the dead-letter queue that the README promises never run, for three separate reasons. That, and four other things to change, are covered at the end.

The constraints that shape the design

  • Ingestion is slow and must not block the API. Reading, chunking, embedding and indexing a document takes far longer than an HTTP request should.
  • Every step can fail halfway. A worker can die after writing half a document’s vectors to Qdrant.
  • Clients retry. The same document will be submitted more than once, and the pipeline must not index it twice.

Architecture

Architecture of the RAG ingestion pipeline: the client creates a document and uploads a file to FastAPI, which commits a row to PostgreSQL with a unique source and pushes a job to the documents:pending Redis list. A worker moves the job to documents:processing with BRPOPLPUSH, reads and chunks the file into 500-character pieces, embeds them, upserts them into Qdrant with uuid5 IDs, marks the document DONE and removes the job. On failure the job stays in the processing list; a DLQ is reached only on a third redelivery.

A document takes two HTTP calls: POST /documents creates a row with a source, and POST /documents/{id}/upload saves the file and queues the document. A separate worker does everything slow.

The API path

Duplicates are handled by the database

Idempotent ingestion starts with a unique index on documents.source. The service doesn’t check whether the document exists first - that check-then-insert would race. It simply inserts and lets PostgreSQL reject the duplicate:

async def ingest(self, request: DocumentCreateRequest):
    queue_length = await self.queue.get_queue_length()
    if queue_length >= settings.QUEUE_MAX_LENGTH:
        raise QueueFullError(queue_length, settings.QUEUE_MAX_LENGTH)

    doc = None
    try:
        async with self.session.begin():
            doc = await self.repo.create_document(request.source)
    except IntegrityError:
        await self.session.rollback()
        doc = await self.repo.get_document_by_source(request.source)
        if doc:
            logger.info(f"Returning existing document for source: {request.source}")
            return doc
        raise

    try:
        await self.queue.enqueue(doc.id)
        logger.info(f"Enqueued document {doc.id}")
    except Exception as e:
        logger.error(f"Failed to enqueue document {doc.id}: {e}")
        try:
            async with self.session.begin():
                await self.repo.update_status(doc.id, DocumentStatus.FAILED)
        except Exception as mark_error:
            logger.critical(f"Could not mark {doc.id} as FAILED: {mark_error}")
        raise InfraError(f"Failed to enqueue document: {str(e)}") from e

    return doc

Two concurrent requests with the same source both try the insert; one wins and the other gets an IntegrityError and returns the winner’s row. The ordering matters too. The row is committed before the job is queued, so a worker can never pick up a job for a document that doesn’t exist yet. If Redis is down, the document is marked FAILED and the client gets an error instead of a document that silently never gets processed.

Backpressure as a 429

Before doing anything, the API checks the length of the pending list and returns 429 Too Many Requests at 1,000 queued jobs (QUEUE_MAX_LENGTH). The check and the push are separate commands, so a burst can overshoot the limit slightly, which is fine for a guard against memory growth.

The queue

The queue is two Redis lists and one command. BRPOPLPUSH atomically pops a job from documents:pending and pushes it onto documents:processing, so a job is never in neither list:

result = await self.redis.brpoplpush(
    DOCUMENT_QUEUE, PROCESSING_QUEUE, timeout=2
)

This is the classic Redis reliable-queue pattern. With a plain BRPOP, a worker that crashes after the pop loses the job. Here the job sits in the processing list until the worker removes it with LREM after success - the acknowledgement. The README calls this at-least-once delivery, and the pattern supports it - if something requeues jobs that stay too long.

After the move, dequeue rewrites the payload to add a started_at timestamp, so that a sweeper can tell how long a job has been in flight. requeue_stale_jobs implements that sweeper: jobs older than 300 seconds go back to the pending list with an incremented retry_count, or to the DLQ after three.

The worker

Claiming the document

The worker locks the row, refuses documents that are already PROCESSING or DONE, and commits the PROCESSING status before doing any heavy work:

async with self.session.begin():
    doc = await self.repo.get_document_by_id_for_update(doc_id)
    if not doc:
        raise DocumentNotFound(doc_id)

    if doc.status in (DocumentStatus.DONE, DocumentStatus.PROCESSING):
        raise ProcessingConflict(doc_id, doc.status)

    file_path = doc.file_path
    await self.repo.update_status(doc_id, DocumentStatus.PROCESSING)

try:
    if file_path:
        content = await self._read_file(file_path)
        chunks = self.chunking_service.chunk(content)

        if chunks:
            embeddings = self.embedding_service.embed_batch(chunks)
            await self.vector_service.upsert_chunks(doc_id, chunks, embeddings)

Keeping the transaction short is the right call: holding a row lock and a connection through seconds of embedding would cap the pipeline at the size of the connection pool.

Chunking

Chunks are 500 characters with a 50-character overlap, so each new chunk starts 450 characters after the previous one. The overlap means a sentence cut at a chunk boundary still appears whole in one of the two chunks. Production pipelines usually split on tokens and structure instead, because model limits are in tokens and a chunk that ends mid-sentence retrieves worse.

Deterministic vector IDs

This is the core idempotency idea, and it is implemented exactly as described:

for i, (chunk, vector) in enumerate(zip(chunks, embeddings)):
    chunk_id = str(uuid5(NAMESPACE_DNS, f"{document_id}_{i}"))

    payload = {
        "document_id": str(document_id),
        "chunk_index": i,
        "text": chunk,
    }

    points.append(
        models.PointStruct(id=chunk_id, vector=vector, payload=payload)
    )

await self.client.upsert(collection_name=self.collection_name, points=points)

uuid5 is a hash, so chunk 7 of a document always gets the same point ID. Qdrant’s upsert replaces a point with the same ID. If indexing runs twice for the same content, the second run overwrites the first instead of adding a second copy, and search never returns the same passage twice. A random uuid4 would make every retry add duplicates.

The guarantee has an edge. Overwriting works when the second run produces the same number of chunks or more. If a document is re-indexed with different content that produces fewer chunks, the old high-index chunks stay in the collection. Deleting points by document_id before the upsert closes that gap.

Benchmarks

The repository has no recorded measurements. The README’s performance table - about 50,000 documents a day, p95 enqueue under 200 ms, crash recovery under 30 seconds - gives no hardware or setup, and scripts/benchmark_latency.py prints results but none are checked in. So instead of measured numbers, here is what the code’s constants imply. This is derived arithmetic, not a measurement:

Quantity Calculation Result
Chunks for a 100 KB text document ⌈100,000 ÷ 450⌉ 223
Vector size 1,536 dimensions × 4 bytes (float32) 6 KB
Vectors per 100 KB document 223 × 6,144 bytes ≈ 1.37 MB
Average rate at the README’s 50,000 docs/day 50,000 ÷ 86,400 s ≈ 0.58 docs/s
Time to drain a full queue at that rate 1,000 ÷ 0.58 ≈ 29 minutes
Raw vector data per day, all docs 100 KB 50,000 × 1.37 MB ≈ 68.5 GB

I checked the chunk count by running the repository’s own ChunkingService on a 100,000-character string (Python 3.11, macOS on Apple silicon, no dependencies needed): 223 chunks, 222 of 500 characters and one of 100.

The vectors are about 14 times larger than the text they index, before Qdrant’s own index overhead; storage planning for a RAG system is mostly vector planning. And with a real model, a 223-chunk document is 223 embedding inputs: the provider’s rate limit, not the queue, decides how many documents a day get indexed.

What to change before production

Reading the failure paths against the README’s failure table turns up five issues.

1. A failed document is never retried, and never reaches the DLQ. When processing raises, the worker marks the document FAILED, increments documents:retry:<id>, and the main loop swallows the exception:

try:
    await self.process(str(doc_id), raw_payload)
    await self.queue.acknowledge(raw_payload)
except Exception:
    pass

The job stays in documents:processing. The only code that moves jobs out of that list is requeue_stale_jobs, and nothing in src/ calls it. So the job is never delivered again, the retry counter stops at 1, and the “3 attempts before DLQ” path is unreachable. Even if the sweeper ran, two more things would stop the retry. process() deletes the uploaded file in its except block, so the retry has nothing to read. And update_status rejects FAILED → PROCESSING; the only transition out of FAILED is to PENDING through retry_document, which also has no caller outside the tests. The DLQ test passes because it patches process_job and calls process() four times by hand. A single Qdrant timeout fails a document permanently. The fix is to make failure explicit: on error, LREM the job and push it back with a delay (a sorted set scored by retry time works well), move the document back to PENDING, keep the file until the final attempt, and keep one retry counter instead of two (the Redis key and the payload’s retry_count used by the sweeper).

The document state machine: PENDING to PROCESSING to DONE, any error to FAILED, and FAILED back to PENDING only through retry_document, which has no caller. FAILED to PROCESSING raises InvalidStateTransition. Three independent reasons a retry never runs: the job stays in documents:processing because requeue_stale_jobs is never called, the source file is deleted on failure, and FAILED to PROCESSING is rejected.

2. Creating a document queues a job before the file exists. ingest() enqueues the document as soon as the row is created, but the file arrives in a second request. An idle worker waits in BRPOPLPUSH, or at most a one-second sleep between polls, so it can take the job before the client has even sent the upload. It finds file_path empty, skips reading, chunking and indexing, and marks the document DONE with zero vectors. The upload then hits the status check, returns 409 Conflict, and leaves the file it already saved on disk, because save_file runs before the check. The repository’s test_e2e.py expects exactly this: it creates a document with no file and waits for DONE. Under load the order flips: the upload lands while the first job is still queued, the document gets two jobs, and the second one becomes the duplicate delivery described next. The fix is to enqueue only from the upload path, or to accept the file in the create request, and to treat “no file” as an error instead of success.

3. A duplicate delivery fails the job it duplicates. At-least-once delivery means a document can be processed by two workers, which the README marks as safe. In the code, the second worker finds the row in PROCESSING, raises ProcessingConflict, and the worker’s generic error handler calls mark_failed. That deletes the source file and moves the document to FAILED while the first worker is still embedding it. If the first worker has already read the file, it writes its vectors, tries FAILED → DONE, gets InvalidStateTransition, and the document ends FAILED with a full set of vectors in Qdrant. A conflict on an in-flight document should acknowledge the duplicate and do nothing else. A lease (a worker ID plus expiry on the row) would also let a real crash be told apart from a slow job.

4. Crash recovery has no mechanism behind it. The README promises recovery from a worker crash in under 30 seconds. With no sweeper running, a crashed worker’s job stays in the processing list forever and its document stays PROCESSING. The sweeper, if scheduled, waits 300 seconds, not 30, and skips entries without started_at. Those entries exist: dequeue adds the timestamp with an LREM followed by an LPUSH (the comment says “atomically”, but these are two commands), so a crash between BRPOPLPUSH and that rewrite leaves an entry the sweeper will never touch, and a crash between the LREM and the LPUSH loses the job entirely. Finally, a redelivered job for a PROCESSING document hits the same ProcessingConflict path and is marked FAILED, not reprocessed. The fix is a scheduled sweeper with a visibility timeout longer than the slowest job, the timestamp written in the same step as the move (a Lua script, or LMOVE with the timestamp kept in a hash keyed by job), and a lease on the row so that a recovered job can take over a stale PROCESSING document.

5. The embedding interface is synchronous, and the mock makes search meaningless. The README shows async def embed, but the pipeline calls embed_batch without await, inside an async worker. A real provider SDK call there blocks the event loop for the whole HTTP round trip. Shaped like the mock, where embed_batch loops over embed, the 100 KB document above becomes 223 sequential blocking calls, with no batching, timeout or rate-limit handling. The mock also hides that search doesn’t work:

random.seed(len(text))
return [random.random() for _ in range(1536)]

The vector depends only on the length of the text. Every full 500-character chunk gets the same vector - running the repository’s mock on the 223 chunks above produces two distinct vectors - and any two queries of the same length are identical. Search returns arbitrary chunks with equal scores, so no test can tell good retrieval from bad. It also reseeds Python’s global random generator on every call. A deterministic mock should hash the content (for example, seed a local random.Random with a SHA-256 of the text), and the interface should be async and batch-shaped before a real model is plugged in.

Two smaller notes. The worker’s Redis error handling is a fixed 5-second sleep, not the exponential backoff the README describes. And the DLQ endpoint is /api/v1/documents/admin/dlq, unauthenticated, and returns two formats mixed together: bare document IDs pushed by the worker and JSON entries with a reason pushed by the queue. The upload path also queues its job inside the database transaction, before the commit, unlike ingest(); if that commit fails, a job exists for a file path the database never recorded.

What a large RAG platform does differently

At scale This project
A durable log or managed queue with visibility timeouts and redrive Two Redis lists and an unscheduled sweeper
Many embedding workers, batched requests, provider rate-limit budgets One worker, one embedding call per chunk
Token- and structure-aware chunking Fixed 500-character windows
Object storage for source files Local data/uploads directory
Re-indexing deletes old points by document ID first Upsert by deterministic ID only

What carries over unchanged: a unique key on the source, commit before enqueue, a reliable queue instead of a destructive pop, and vector IDs that make re-running a job harmless.

Try the design yourself

An ingestion pipeline is a queue in front of slow workers, and its job is to absorb bursts without losing work. Design a RAG pipeline walks through the full system - ingestion, vector search, reranking and cost per query - and the Queue It Up challenge lets you feel the queue part: write traffic spikes 5× partway through, and you have to absorb it without dropping a single write.

The full source, with docker-compose up to run PostgreSQL, Redis, Qdrant, the API and the worker, is at github.com/winsongr/async-rag-ingestion-engine.

One system design problem a week

A real scenario, its constraints, and where the obvious design breaks.

One email a week. Unsubscribe any time. Privacy

Now break one yourself.

The first challenge takes about two minutes. No signup.