# Design a Document Ingestion Pipeline

> How a document ingestion pipeline turns files into searchable chunks, keeps them correct when files change, and copies access rules, explained for your AI interview.

**In short:** An ingestion pipeline reads each file, cuts its text into chunks, turns the chunks into lists of numbers that capture their meaning and stores them in a search index. It must also handle edited and deleted files and copy each file's access rules, so a rerun never leaves stale or leaked text behind.

AI and LLM interview question Q363, LLM system design. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/design-a-document-ingestion-pipeline

## Say it in 30 seconds

I'd split it into stages: read the file, clean the text, cut it into chunks, add labels like owner and date, turn each chunk into numbers that capture its meaning, then index. Each chunk keeps its source, so a bad answer can be traced. The hard part is change. A rerun should skip unchanged files, replace edited ones and delete removed ones. I'd also copy each file's access rights onto its chunks, so search never shows a salary sheet to the wrong person.

## Say it in 2 minutes

Start with the job. Imagine a mid-size bank with about a million pages across policy PDFs, scanned forms, wiki pages and exported chat logs. Staff need answers in seconds, and the assistant must cite the right policy version.

I'd run it in stages. A loader pulls new or changed files from each source. A reader extracts the text, using OCR for scanned pages. The text is then cut into small pieces, usually no more than a few hundred tokens (the units a model counts text in), and each chunk keeps its source, owner, date and version. An embedding model turns each chunk into a list of numbers, and the index stores it with its labels.

The hard part is change. Files get edited and deleted all day, and a rerun must not duplicate chunks or leave stale chunks behind. I'd fingerprint each file, re-ingest only what changed, write the new chunks, then remove the old ones. Deletion doesn't come for free either: Azure's storage indexers detect changes but not deletions, so the check has to be built on purpose.

Last, access. Each chunk carries its file's permissions, and search filters on them before the model sees anything. If a policy's audience changes, the pipeline updates those labels, not just the text. I'd test it with a staff member who lacks access and try to get the salary table to appear.

## What is a document ingestion pipeline, in plain words?

An ingestion pipeline is the conveyor belt that gets your documents ready for an AI assistant to search. Raw files go in one end. Clean, labelled, searchable pieces come out the other.

Think of a hospital records desk. Each new letter is opened, read, filed under the right patient and cross-referenced. A withdrawn letter comes out of the files. In an AI system the letters are a bank's policy pages, and the filing is a vector index.

- **Ingestion:** Loading a document, reading it and storing it so search can find it.
- **Chunk:** A short piece of a document, usually a few paragraphs, that gets searched and sent to the model.
- **Embedding:** A list of numbers, also called a vector, that stands for the meaning of a piece of text, so similar meanings sit close together.
- **Index:** The search store that holds the chunks, their numbers and their labels.
- **Metadata:** Labels on each chunk: source file, owner, date, version and who may read it.

## What happens at each stage?

1. **Load:** A connector pulls new or changed files from the source, such as a shared drive, a wiki or a mail export.
2. **Read and clean:** Text is pulled out of the file. Scanned pages go through OCR, which reads letters from an image. Repeated headers and footers are dropped.
3. **Chunk:** The text is cut into pieces that each hold one idea, with a small overlap so an idea at a cut point is not lost.
4. **Label:** Each chunk gets its source, owner, date, version and access rights.
5. **Embed and index:** An embedding model turns each chunk into a list of numbers, and the index stores it with its labels.

*Diagram, The ingestion stages: A policy PDF goes in on the left and comes out as labelled, searchable chunks.*
1. A new or edited file is picked up from its source.
2. Its text is pulled out, and scanned pages are read as text.
3. The text is cut into small pieces, each keeping its file name.
4. An embedding model turns each piece into a list of numbers, then the numbers, text and labels are stored for search.

Chunking is needed when a file is too big for a model to take in one go. Microsoft's Azure guide also says chunking helps when a long text is poorly represented as a single vector.

## Why do chunk size and overlap matter?

Chunks that are too big bury the answer in noise. Chunks that are too small lose the words around it. Azure's guide lists fixed-size chunks as one approach. It gives 10 to 15 per cent overlap as an example, and recommends starting with 512 tokens and 25 per cent overlap.

- **Too big: The answer is buried.** A chunk with twelve topics dilutes the match, so the right text ranks below the noise.
- **Too small: The context is lost.** A chunk that only says the fee is 25 pounds cannot say which product the fee belongs to.
- **Test it: Measure on real questions.** Try a few sizes on questions staff really ask, and keep the size that finds the answer most often.

Made-up example: a 60-page loan policy has the eligibility rule on page 14 and its exception on page 15. Cut at a hard 600 characters, the two land in separate chunks, and a question about the exception finds half the answer. Cutting at paragraph breaks with a small overlap keeps both in one chunk, as long as the two paragraphs fit inside it.

> "smaller chunks of text, usually no more than a few hundred tokens" (Anthropic)
>
> "prepending chunk-specific explanatory context to each chunk before embedding" (Anthropic)

A chunk on its own can lose the context of its document. Anthropic's 2024 write-up on contextual retrieval adds a short note explaining where each chunk sits in its document, before the chunk is embedded. In its own tests, that cut failed retrievals by 35 per cent. Adding a keyword search index as well cut them by 49 per cent.

> **Tip:** Asked how big chunks should be, don't give one magic number. Say you test a few sizes on real questions and measure which one finds the answer.

## How do you handle files that change or get deleted?

A rerun must make the index match the source: add new files, replace edited ones and remove deleted ones. Done badly, you get duplicates, old answers, or chunks from a policy that was withdrawn last year.

AWS's Bedrock knowledge base syncs incrementally, so it handles only the files that changed since the last sync. Each sync then re-ingests the changed files: parse, chunk, embed and index them again. A deleted file is removed from the vector store.

> "Although change detection is a given, deletion detection isn't." (Microsoft Azure)
>
> "Syncing is incremental, so Amazon Bedrock processes only the documents that were added, modified, or deleted since the last sync." (Amazon Bedrock)

*Diagram, Changes and deletes keep the index honest: Each run compares files with the last run. Edited files are read again. Removed files lose their chunks.*
1. The source changes, and the next run notices.
2. A new or edited file is read again, ready to replace its old chunks.
3. A removed file has its chunks marked for deletion.
4. Its new chunks replace the old ones, and the file is marked done.
5. Its old chunks are deleted, so nothing stale is left behind.

Made-up example: a bank withdraws its 2024 fee schedule. Its chunks must leave the index on the same day, or the assistant keeps quoting fees that no longer exist. Keep a list of each file's fingerprint from the last run. A fingerprint is a short code made from the file's contents, so any edit changes it. A file on that list but missing today triggers a delete of its chunks.

Make every write safe to repeat. Key each chunk by file ID, version and chunk position, so a retry overwrites the same chunk instead of adding a second one. Once a new version's chunks are written, delete the old version's chunks.

Here is the rerun logic in 30 lines, using two made-up policy files.

```python
import hashlib
def chunk(text, size=40, overlap=10):
    # Fixed-size character chunks that share a little text with the next chunk.
    step = size - overlap
    return [text[i:i + size] for i in range(0, max(len(text) - overlap, 1), step)]
def ingest(index, docs):
    # Re-running is safe: an unchanged file is skipped, and a removed file is deleted from the index.
    log = []
    for doc_id, text in docs.items():
        fingerprint = hashlib.sha256(text.encode()).hexdigest()[:8]
        if index.get(doc_id, {}).get("fp") == fingerprint:
            log.append("skip " + doc_id)
            continue
        index[doc_id] = {"fp": fingerprint, "chunks": chunk(text)}
        log.append("upsert " + doc_id + " (" + str(len(index[doc_id]["chunks"])) + " chunks)")
    for doc_id in list(index):
        if doc_id not in docs:
            del index[doc_id]
            log.append("delete " + doc_id)
    return log
index = {}
day1 = {"refund-policy.txt": "Refunds take 5 to 7 working days after approval. The call centre is open Monday to Saturday.",
        "leave-policy.txt": "Annual leave is 25 days. Carry-over is capped at 5 days a year."}
print(ingest(index, day1))
day2 = {"refund-policy.txt": "Refunds take 5 to 7 working days after approval. The call centre is open Monday to Friday.",
        "leave-policy.txt": "Annual leave is 25 days. Carry-over is capped at 5 days a year."}
print(ingest(index, day2))
day3 = {"refund-policy.txt": day2["refund-policy.txt"]}
print(ingest(index, day3))
print(sorted(index))
```

Output:

```text
['upsert refund-policy.txt (3 chunks)', 'upsert leave-policy.txt (2 chunks)']
['upsert refund-policy.txt (3 chunks)', 'skip leave-policy.txt']
['skip refund-policy.txt', 'delete leave-policy.txt']
['refund-policy.txt']
```

## How do you keep access rules and safety in the pipeline?

Search should only return what the person asking may read. OWASP's 2026 list covers this in its vector and embedding entry. Its advice is to apply access control at the chunk level, because one document can hold public and confidential text.

Made-up example: an HR assistant indexes the leave policy and the salary bands from one shared drive. Without labels, a question about leave can return the salary table. With the drive's permissions copied onto each chunk, the search drops rows the asker cannot see before the model gets them.

Ingested text is also a way in for attacks. A supplier's PDF can hide an order for the assistant. OWASP's 2026 prompt injection entry lists a retrieved passage as one of the sources that can carry injected instructions.

> **Tip:** Asked about access, say the rules are copied when a file is ingested and checked again at query time. A permission change should relabel the chunks. Re-embedding the text does not change who can read it.

### How would you ingest two million files in a week?

Turn the work into a queue of small jobs, one per file, so a failure retries one file only. A queue is a line of waiting jobs that workers pick up one at a time. Run many workers in parallel, but cap them to the embedding provider's rate limit, the most requests it will accept in a set time. Store a status for each file, so a crash resumes where it stopped. Files that keep failing go to a holding list, a dead-letter queue, for a person to check.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] The stages in order: load, read, chunk, label, embed, index.
- [ ] Why chunk size and overlap matter, with a worked case.
- [ ] How changes and deletes keep the index honest.
- [ ] Access rules copied at ingest and checked at query time.
- [ ] How you test it: real questions, and a check that deleted files are gone.
- [ ] Cost and scale: queues, retries and rate limits, named as trade-offs.

**Common traps**

- Trap: "Embed every file once and you're done." Better: Files change and get deleted. The pipeline has to re-run safely and remove what is gone.
- Trap: "Use the biggest embedding model." Better: Model choice matters, but switching models means re-embedding everything. Plan that reindex from the start.
- Trap: "The chatbot's prompt will keep salary data hidden." Better: A prompt can be talked round. Filter by permissions in the search, before the model sees any text.

## Can you spot the problem?

**Spot the flaw:** A nightly job re-embeds every file in the drive and appends the new chunks to the index. What breaks first?

A. The chunk overlap is 10 per cent.
B. Old chunks are never removed, so a withdrawn policy keeps answering next to the new one.
C. Each chunk has labels for its owner and date.
D. Scanned pages go through OCR before chunking.

**Answer:** B. Appending without replacing means old and new chunks both answer questions. Key each chunk by file and version, and once the new ones are written, delete the old ones.

**Quick check:** A bank's assistant must hide salary tables from staff who cannot read them. Where should that check happen?

A. In the system prompt, by telling the model to hide them
B. In the search, filtering chunks by the asker's permissions before the model sees them
C. In the chat window, by hiding the answer after the model writes it
D. In the embedding model's settings

**Answer:** B. Filtering in the search means the model never sees text the person may not read. A prompt can be talked round, and a hidden answer can still leak through the model's reply.

## Can you answer these from memory?

**Flash cards**

- **What are the stages?** Load, read and clean, chunk, label, embed, then index.
- **What is a chunk?** A short piece of a document that gets searched and sent to the model.
- **Why overlap chunks?** So an idea cut at a boundary still appears whole in one chunk.
- **What must a rerun do?** Replace changed files by key, and delete the chunks of removed files.
- **Why is deletion tricky?** In Azure's storage indexer, changes are tracked but deletions are not. Build that check.
- **Where do access rules go?** Copied onto each chunk at ingest, and filtered in search before the model sees it.

## Likely follow-up questions

- Q113 What is chunking, and why does size matter? https://designervenkat.online/interview/ai/what-is-chunking-in-rag
- Q115 What is chunk overlap? https://designervenkat.online/interview/ai/what-is-chunk-overlap
- Q139 How do you keep the index fresh? https://designervenkat.online/interview/ai/how-do-you-keep-the-index-fresh
- Q140 How do you enforce access control in RAG? https://designervenkat.online/interview/ai/how-do-you-enforce-access-control-in-rag
- Q116 How do you choose an embedding model? https://designervenkat.online/interview/ai/how-do-you-choose-an-embedding-model
- Q201 What is prompt injection? https://designervenkat.online/interview/ai/what-is-prompt-injection

## Learn it in depth

- [Chunking](https://designervenkat.online/learn/ai-engineering/chunking)
- [Indexing Embeddings](https://designervenkat.online/learn/ai-engineering/indexing-embeddings)
- [Retrieval-augmented generation](https://designervenkat.online/learn/ai-engineering/rags)
