AI & Data18 November 202610 min read

From AI Prototype to Production — Part 4 of 10

RAG at real scale: ten million documents without losing control

At ten million documents, retrieval stops being a pipeline and becomes three systems: a write path that must be replayable, a read path that must respect permissions, and an operations plane that keeps both honest. Part 4 of From AI Prototype to Production gives the engineering view and a capacity worksheet with every calculation shown.

#RAG#Data Engineering#Event Streaming#Enterprise Search#Production AI
A workbench holding a few loose glass blocks, connected by a cyan line to a large, orderly frame of lit modules with a small yellow status light, in a dark workshop over a faint map of southern Africa.

The retrieval index behind the Swartberg Health Administrators pilot held about 200,000 documents and was rebuilt by a script every Sunday night. Swartberg is our fictional South African medical scheme administrator. When the business asked for the full estate, the number was ten million: claims correspondence, clinical motivations, scheme rules for every year and option, provider contracts and call summaries. The architect's first question was not which vector database to buy. It was what happens on the Monday morning when the Sunday script fails halfway through 50 million chunks.

At that scale, retrieval-augmented generation (RAG) is a distributed system. RAG is a data product, Part 4 of The Enterprise AI Control Plane, covers ownership, permissions and versioning, with a worked sizing example for a smaller estate. CloudNala's RAG That Survives Production series covers chunking, hybrid search and reranking as retrieval-quality decisions. This part is the engineering view at full scale: how to build ingestion that can fail safely, a read path that holds up under load, and the operations that keep it true.

Three planes, not one pipeline

RAG at scale: write path, read path and operations planeWRITE PATH (CONTINUOUS)Source changeeventsObject store:raw, versionedQueue keyedby document IDParse, classify,chunk, embedIndex: text,vectors, ACLsDead letters: owner review, then replayREAD PATH (PER QUESTION)Question plusidentityRewrite andscope accessHybrid retrieval,ACL-filteredRerank andcompose contextAnswer withchecked citationsCache keyed by query, access and index versiononly chunks this user may seeOPERATIONS PLANE (ACROSS BOTH)Retrieval andanswer evaluationFreshness andrevocation lagCost peraccepted answerRe-index andmodel migrationTraces, auditand lineageEACH BOX HAS A NAMED OWNER AND A NUMBER SOMEONE ACCEPTS
The write path runs continuously. Source changes arrive as events, raw files land in versioned object storage, and a queue keyed by document identifier feeds parsing, chunking and embedding, so each document's versions are processed in order and a failed document goes to a dead-letter store with an owner instead of blocking the rest. The read path runs per question and applies the user's permissions inside retrieval. The operations plane spans both: evaluation, freshness and revocation lag, cost, re-indexing and traces.

Treat these as three systems with separate owners, failure modes and service levels:

  • The write path turns source changes into indexed chunks. It runs continuously and must be replayable.
  • The read path turns a question and an identity into ranked, permitted, cited passages. It runs per request and must be fast.
  • The operations plane measures both: evaluation, freshness, revocation lag, cost, re-indexing and audit.

Most pilot failures at scale come from treating the write path as a batch job and the operations plane as an afterthought.

The write path: make ingestion replayable

Start by landing every raw document in versioned object storage before you parse it. The raw copy is what you reprocess when the parser improves, when a chunking rule changes, or when you switch embedding models. Without it, every fix means going back to source systems that may not be able to send ten million documents again.

Then move work through a queue. Apache Kafka is one common choice, and four of its concepts solve real ingestion problems (Kafka introduction and design documentation, version 4.4, checked on 18 November 2026):

Kafka conceptWhat the documentation saysThe ingestion problem it solves
Keyed partitionsEvents with the same key go to the same partition, and a partition is read in the order it was writtenKey by document ID, so version 3 of a scheme rule is never indexed after version 4
Consumer groupsEach partition is read by exactly one consumer in a group at a timeAdd parsing workers to scale out without two workers handling the same document
Retention and offsetsEvents are not deleted after consumption; a consumer can rewind to an old offsetReplay a day's documents after fixing a parser bug
Delivery semanticsAt-least-once by default; idempotent producers avoid duplicate log entriesYour consumers will see some events twice, so processing must be idempotent

You do not need Kafka for this. A managed queue with keyed ordering, retention and replay can do the same job, and a nightly batch is fine for a small, slow-changing corpus. The decision table later in this part sets out when each fits.

Dead letters need an owner. Some documents will fail: a corrupt PDF, a password-protected attachment, a scan the extraction step cannot read. Send them to a dead-letter store with the error, the document ID and the stage that failed, and give that store an owner who reviews it weekly. Kafka itself does not route application failures to a dead-letter topic; you build that in your consumer. Kafka Connect's dead-letter queue, from KIP-298, covers sink connectors only, and only records that fail in the converter or transformation step. Do not assume it catches parsing failures in your own code.

Idempotency comes from deterministic IDs. Build each chunk ID from document ID, document version and chunk number, and write with upserts. A replayed event then overwrites the same chunks instead of adding duplicates. When a new version arrives, delete the previous version's chunks in the same operation, or mark them superseded with an effective-to date if older versions must stay searchable.

Not every change needs re-embedding. A permission change, a retention deletion or a reclassification updates metadata on existing chunks. Route these as their own event type, so they take seconds rather than queuing behind embedding work. That is how you keep revocation lag short.

Embeddings at volume

Embedding is usually the slowest and most expensive step of the write path, and the one with the most hidden coupling.

  • Batch the backfill. Providers offer asynchronous batch endpoints for bulk work. As a dated example, OpenAI's Batch API guide (checked on 18 November 2026) states a 50% cost discount against its synchronous APIs, a 24-hour completion window and a limit of 50,000 embedding inputs per batch. Use the synchronous path for daily changes and batches for backfills and migrations.
  • Cache by content hash. If a chunk's text has not changed, its vector has not changed. Hash the chunk text with the embedding model version, and skip re-embedding unchanged chunks when a document is re-sent.
  • Store the model version with every vector. Vectors from different embedding models are not comparable. A mixed index fails silently.
  • Treat quantisation as a measured trade-off. Storing vectors as 8-bit integers instead of 32-bit floats cuts raw vector storage by a factor of four. Whether recall survives depends on your data, so run the retrieval evaluation before and after.

Approximate nearest-neighbour indexes make vector search fast at this size. Hierarchical Navigable Small World (HNSW) graphs, described by Malkov and Yashunin, are a widely used structure, with search cost that the authors show scales logarithmically. The graph links take memory on top of the vectors, which the worksheet includes as an assumption.

The read path: hybrid, filtered, reranked, cited

The read path at Swartberg serves contact-centre agents and claims assessors who need answers in seconds.

  1. Rewrite and scope. Normalise the question and resolve the user's access scope once: their groups, the members they may serve, the collections they may search.
  2. Hybrid retrieval with the filter inside. Run lexical and vector search together and fuse the ranked lists. Reciprocal rank fusion, from Cormack, Clarke and Büttcher (SIGIR 2009), is a simple, widely used method. Apply the access filter inside both searches. If you filter after taking the top results, a user with narrow access can get too few results, or none, even when permitted passages exist further down. CloudNala's permission-aware retrieval covers the access model.
  3. Rerank a shortlist. A cross-encoder reranker reads the question and each candidate together, which is more accurate and more expensive than vector similarity. Nogueira and Cho showed the approach with BERT in 2019. Rerank tens of candidates, not thousands.
  4. Compose and cite. Put the top passages into context with their document ID, version and source system, and check that each citation in the answer points to a passage that supports it.

Caches must know who is asking. A retrieval or answer cache keyed only on the question will serve one user's permitted passages to another. Key caches on the normalised question, the access scope and the index version, and clear them when the index version changes.

The operations plane

  • Evaluation. Keep a versioned set of questions with known correct passages, stratified by collection, document type, year and language. Measure retrieval recall and citation correctness separately from answer quality, as evaluate retrieval separately from the answer explains.
  • Freshness and revocation lag. Publish two numbers per collection: how long a new document takes to become searchable, and how long a permission removal takes to take effect. Alert when either breaches its target.
  • Re-indexing as a migration. Changing the embedding model, chunking rule or index settings means building a parallel index, evaluating it and cutting over, with the old index kept until rollback is no longer needed.
  • Cost per accepted answer. Track embedding, storage, reranking and generation cost per answer the user accepted, not per query.
  • Traces and lineage. For every answer, record the query, access scope, index version, passages returned and passages cited. Operating RAG after launch covers the operating calendar.

Capacity assumptions worksheet

Every figure below is an illustrative assumption for a fictional organisation, not a benchmark. Replace each with your own measurement and the derived numbers follow.

IDAssumptionValue
A1Documents10,000,000
A2Average tokens per document after extraction1,800
A3Chunk size and overlap400 tokens, 50 overlap, so a 350-token stride
A4Embedding768 dimensions, 32-bit floats (4 bytes each)
A5Index graph links per vectorAbout 256 bytes (depends on index settings)
A6Chunk text and metadata (IDs, access lists, dates, source)3,000 bytes per chunk
A7Serving replicas2
A8Backfill window10 days
A9Documents changed per day0.5%
A10Users and questions1,500 users, 40 questions each a day, 15% in the peak hour
A11Retrieval40 candidates reranked, 8 chunks into context
A12Other context and output per question2,000 input tokens, 400 output tokens
Derived figureWorkingResult
Corpus size10,000,000 × 1,80018 billion tokens
Chunks per document1 + (1,800 − 400) ÷ 350 = 1 + 45
Total chunks10,000,000 × 550 million
Tokens to embed50,000,000 × 40020 billion (overlap adds 2 billion, about 11%)
Raw vectors50,000,000 × 768 × 4 bytes153.6 GB (about 143 GiB)
Graph links50,000,000 × 256 bytes12.8 GB
Text and metadata50,000,000 × 3,000 bytes150 GB
One index copy153.6 + 12.8 + 150316.4 GB
Served footprint316.4 × 2 replicas632.8 GB, before backups
Raw vectors as 8-bit integers50,000,000 × 768 × 1 byte38.4 GB per copy
Backfill rate20 billion tokens ÷ 864,000 seconds (10 days)about 23,150 tokens a second, or about 58 chunks a second
Backfill batches at 50,000 inputs each50,000,000 ÷ 50,0001,000 batches
Daily change0.5% × 10,000,000 = 50,000 documents × 5 chunks × 400 tokens100 million tokens a day
Questions1,500 × 4060,000 a day
Peak load60,000 × 15% = 9,000 in an hour ÷ 3,6002.5 questions a second
Reranking60,000 × 402.4 million pairs a day; 100 a second at peak
Generation input60,000 × (8 × 400 + 2,000) = 60,000 × 5,200312 million tokens a day
Generation output60,000 × 40024 million tokens a day

To turn tokens into money, multiply by your contracted prices rather than list prices. With P_in and P_out as the price per million input and output tokens, daily generation cost is 312 × P_in + 24 × P_out. Each 10% of questions served from a permission-aware cache removes 31.2 million input tokens a day. A full embedding-model change re-embeds 20 billion tokens, which at the backfill rate takes another ten days, and temporarily adds a second set of vectors and graph links: 166.4 GB per copy.

Choose the ingestion backbone

OptionFits whenWatch for
Scheduled batch rebuildSmall corpus, changes weekly, a day's lag is acceptableRebuild time grows with the corpus; no partial replay
Managed queue with keyed orderingSteady change volume, a few source systems, a small platform teamCheck ordering, retention and replay limits against your volumes
Log-based event streaming, such as KafkaMany sources, high change volume, several consumers of the same events, replay neededOperational skill and cost; a managed service reduces but does not remove it

Swartberg chose a managed queue for the pilot estate and moved to event streaming only when claims, contracts and correspondence systems all had to feed the same index.

The South African version

  • Residency and transfer. The index holds copies of member correspondence and clinical motivations, which include health information, treated as special personal information under section 26 of POPIA. If the index, embedding or reranking service runs outside South Africa, section 72 sets the conditions for transfer. Check, model by model, which services are offered in a South African region. This is general information, not legal advice.
  • Backfill bandwidth. Moving ten million raw documents to a cloud region is a planned transfer, not a background task. Schedule it, measure it and keep the object store close to the parsing workers.
  • Scans and languages. Older scheme correspondence is often scanned, and members write in several languages. Put both into the evaluation set, or the averages will hide where the system fails.

Scale readiness checklist

  1. Land raw documents in versioned object storage before parsing.
  2. Key the queue by document ID and confirm ordering per key.
  3. Build a dead-letter store with an owner, a review cadence and a replay path.
  4. Make every write idempotent with deterministic chunk IDs and upserts.
  5. Route permission and deletion changes as metadata events, and publish the revocation lag.
  6. Store the embedding model version with every vector.
  7. Apply access filters inside retrieval and key every cache on access scope and index version.
  8. Fill in the capacity worksheet with measured values and keep it with the architecture record.
  9. Rehearse an embedding-model migration on a sample before you need one.

Scorecard contribution

This part supplies evidence for five rows of the Production Readiness Scorecard in Part 1. The states for Swartberg are illustrative.

Scorecard rowEvidence from this partSwartberg state
Context/RAGAccess filters inside retrieval; citation checks; cache keys include access scopetested
DataVersioned raw store; freshness and revocation lag published per collectiontested
ResilienceReplay from retained events; dead-letter store with owner; parallel index for rollbackhypothesis
EvaluationStratified retrieval set run before and after every index changetested
EconomicsCapacity worksheet with measured values; cost per accepted answerhypothesis

Next: Part 5, AI gateways, model routing and integration. Previous: Part 3, Context is the product. All parts are on the series page.

How CloudNala can help

CloudNala designs and reviews retrieval platforms for large document estates. We map your sources to a write path with replay, dead-letter handling and idempotent indexing, design a read path with access filtering inside retrieval and permission-aware caching, and fill in the capacity worksheet with your measured volumes. You leave with an architecture, a capacity model your finance team can follow, and an evaluation and migration plan your operations team can run.


Work with CloudNala

CloudNala helps organisations move from technology ambition to practical execution across cloud, AI, data, platform engineering and digital services.

Whether you are exploring AI, modernising your cloud environment, building a public-sector digital service, or turning an idea into a working MVP, we can help you shape the roadmap and deliver the next step.

Book a RAG Scale Review or write to us at consult@cloudnala.co.za

Found this useful?

Share