Building a RAG Knowledge Assistant, Part 2: The Foundation (Database, Storage, and Background Jobs)

•Venkata Lokesh P
Part 2 of 8 · Building a RAG Knowledge AssistantRAGPostgreSQLpgvectorSystem DesignDatabase Design

Part 1 sketched the architecture at a high level. This part goes one level down, into the decisions underneath it. These are the ones that are annoying to change later if you get them wrong, so they're worth getting right, and worth understanding, first.

If terms like "vector database," "transaction," or "background worker" are new to you, don't worry: each one gets explained in plain English the first time it shows up, before any code.


1. Why pgvector instead of a dedicated vector database

First, a quick definition. An embedding (or vector) is just a list of numbers that represents the meaning of a piece of text, so that two pieces of text with similar meaning end up with similar numbers. A vector database is a database built specifically to store these lists of numbers and quickly answer the question "which of my stored vectors are closest in meaning to this new one?" Part 4 explains embeddings properly; for now, just know that's what one is.

A lot of RAG tutorials reach for a purpose-built vector database like Pinecone, Weaviate, or Qdrant. This project uses pgvector instead, which is not a separate database at all, it's a plugin (an "extension") for PostgreSQL, the same relational database already storing users and conversations. Installing it just adds a new column type, vector, and a few new ways to compare two vectors, directly inside the database you already have.

Why that's the right call here, not just the lazy one:

  • One transactional store. A transaction is a group of database changes that either all succeed together or all fail together, with nothing in between. When a document finishes processing, inserting its chunks-with-vectors and flipping the document's status to indexed can happen in the same transaction. With a separate vector database, those become two unrelated systems: the vectors insert succeeds, the Postgres status flip fails (or vice versa) if something crashes in between, and now you have two sources of truth that disagree, and someone has to notice and fix that by hand.
  • One thing to run, back up, and reason about. No second service, no second set of credentials, no second place to check when something's wrong.
  • Good enough at this scale. pgvector won't outperform a purpose-built vector database once you're searching hundreds of millions of vectors, but for one user's knowledge base of a few thousand chunks, that difference never shows up in practice, and switching to a dedicated vector database later, if it's ever actually needed, is a straightforward migration, not a rewrite.

The rule of thumb: reach for a specialized tool when a general-purpose one has measurably run out of road, not just because the specialized tool is the trendier choice. Nothing here has run out of road yet.


2. Why the original files live in object storage, not the database

Object storage is a simple, cheap place to dump files as-is (think: a giant, infinitely scalable folder you can only ask for files by name, not search or query, that's what S3 or MinIO do). It's a different kind of system from a database like Postgres, which is built for structured, searchable rows, not large files.

When someone uploads a PDF, the raw bytes go to MinIO (a self-hosted, S3-compatible object storage service, meaning it speaks the same API as Amazon S3), not into a Postgres column:

PYTHON
# app/providers/storage/s3_provider.py (trimmed)
class S3StorageProvider(StorageProvider):
    """The only module that imports boto3. Works unchanged against MinIO
    (via `endpoint_url`) and real AWS S3 (endpoint_url unset)."""

    async def upload(self, *, key: str, data: bytes, content_type: str) -> None:
        await asyncio.to_thread(
            self._client.put_object,
            Bucket=self._bucket, Key=key, Body=data, ContentType=content_type,
        )

Only the extracted text, chunks, and vectors (the stuff derived from the PDF, not the PDF itself) go into Postgres. The reasoning:

  • Databases are good at rows and indexes; they're a poor fit for large binary files (raw, non-text data like a PDF or image, often called a "blob"): every backup, every replication stream, every query-planner decision gets heavier for no benefit.
  • Object storage is cheap, scales horizontally (just add more machines, no clever tricks needed) without extra effort, and that's exactly what it's designed for.
  • It keeps two concerns cleanly separated: "what the user originally gave us" (object storage, never changes once uploaded) versus "what we derived from it for search" (Postgres, can be rebuilt any time). If the chunking strategy improves later, the source file is still sitting untouched in storage, ready to be reprocessed from scratch. Nothing was lost by not keeping a copy in the database.

One small but telling detail: endpoint_url (just the web address the code talks to) is the only thing that changes between local MinIO and real AWS S3. Same adapter, same code, in both places: another instance of the provider-adapter pattern from Part 1, where swapping what's on the other side never means rewriting the code that calls it.


3. Why ingestion runs in a background worker, not inline in the API

Here's the core idea before any jargon: when you upload a file, you want the website to respond instantly ("got it, we're working on it"), not make you sit on a loading spinner for a minute while a PDF gets fully processed.

Ingestion here just means "everything that has to happen to turn an uploaded PDF into searchable pieces": parsing, cleaning, splitting it into chunks, and generating an embedding for each chunk. None of that is instant, a 40-page PDF can take real seconds. If all of it ran inside the same HTTP request that handles the upload (the request/response cycle: browser sends a request, server does the work, server sends a response, browser is stuck waiting the whole time), the user's browser would sit there waiting. Worse, if it takes longer than the server infrastructure's timeout, the upload just fails outright, even though the processing might have finished successfully a few seconds later.

So instead, the upload endpoint (the bit of code that handles "a file was uploaded") does three fast things and returns immediately, without waiting for any of the slow parsing/chunking/embedding work:

  1. Store the raw file in object storage.
  2. Create a documents row (status = pending) and an ingestion_jobs row, so there's a record that this file exists and is waiting to be processed.
  3. Add a "job" (a description of the work to do) to a queue, and hand the response back to the browser right away.

A job queue is just a to-do list that one process can add to, and another process can keep pulling from. Here that's Redis, an in-memory data store good at exactly this kind of lightweight queue. A separate worker process (a second, independent program, running via a library called ARQ) sits there watching that queue and actually does the slow work, completely separately from the server that's handling browser requests:

PYTHON
# app/workers/jobs/ingest_document.py (trimmed)
async def ingest_document(ctx: dict, document_id: str) -> None:
    ...
    await job_repo.start_attempt(job)
    await document_repo.mark_processing(document)
    await db.commit()
    try:
        file_bytes = await storage_provider.download(key=document.storage_key)
        result = await run_ingestion_pipeline(file_bytes=file_bytes, ...)
    except Exception as exc:
        await job_repo.mark_failed(job, error_message=str(exc)[:2000])
        await document_repo.mark_failed(document, error_message="Document processing failed. You can retry it.")
        await db.commit()
        return
    # only reached if the pipeline succeeded — persist chunks + flip status
    ...

Two details worth calling out:

  • The error message shown to the user is a fixed, safe string ("Document processing failed. You can retry it."), while the real exception text is truncated to 2000 characters and stored separately on the job row for debugging. Never show a raw stack trace or internal exception text to an end user: it can leak internal details, and it's rarely something they can act on anyway.
  • The ingestion_jobs table tracks per-document progress (stage, progress percentage, attempts) so the frontend can poll and show a real progress bar instead of a generic spinner.

There's an honest limitation here, documented right in the code's own docstring: if the worker crashes during the final persist step, the document is stuck at status = processing with no automatic recovery: a retry is only exposed once the status reaches failed. A future improvement is a sweep job that notices a document stuck in processing past some timeout and flips it to failed automatically. Calling this out matters more than hiding it: a system that's honest about its edges is easier to operate than one that pretends not to have any.


4. The data model

Here's the actual shape of the data, table by table, in plain English, followed by the real column definitions for the ones with an interesting design decision baked in.

TableWhat it is
users / sessionsEmail + password auth, server-side session cookie
knowledge_basesA named folder of documents, owned by one user
documentsOne uploaded file: name, size, storage key, status, and the parser/chunking/embedding config that produced its chunks
ingestion_jobsOne row per document's background processing run: stage, progress %, attempt count
document_chunksThe actual searchable unit: text, page range, heading, and a vector column
conversationsOptionally linked to a knowledge base; if not, it's a plain LLM chat with no retrieval
messagesOne row per turn: role, content, model, token counts, latency
message_citationsOne row per source shown under an assistant answer

documents: tracking provenance, not just content

PYTHON
class Document(Base, UUIDMixin, TimestampMixin):
    __tablename__ = "documents"

    filename: Mapped[str] = mapped_column(String(255), nullable=False)
    storage_key: Mapped[str] = mapped_column(String(500), nullable=False)
    status: Mapped[DocumentStatus] = mapped_column(..., default=DocumentStatus.pending)

    # Provenance: which parser/chunker/embedder version produced the
    # current chunks for this document.
    parser_name: Mapped[str | None] = mapped_column(String(50), nullable=True)
    chunking_strategy: Mapped[str | None] = mapped_column(String(50), nullable=True)
    chunking_version: Mapped[int | None] = mapped_column(Integer, nullable=True)
    embedding_model: Mapped[str | None] = mapped_column(String(100), nullable=True)
    embedding_dimensions: Mapped[int | None] = mapped_column(Integer, nullable=True)

Why store which version of the parser/chunker/embedder produced a document's chunks, not just the chunks themselves? Because these things change over time: a better chunking strategy ships, or the embedding model gets upgraded. Without a version stamp, there'd be no way to tell "this document was indexed with the old, worse chunker" from "this one's current," which matters the moment you need to decide which documents to re-process after an upgrade. It's the same instinct as labeling a food container with the date it was made: not useful today, very useful in three weeks.

document_chunks: the vector lives right next to its metadata

PYTHON
class DocumentChunk(Base, UUIDMixin, TimestampMixin):
    __tablename__ = "document_chunks"

    content: Mapped[str] = mapped_column(Text, nullable=False)
    page_start: Mapped[int | None] = mapped_column(Integer, nullable=True)
    page_end: Mapped[int | None] = mapped_column(Integer, nullable=True)
    heading: Mapped[str | None] = mapped_column(String(500), nullable=True)
    section_path: Mapped[str | None] = mapped_column(String(1000), nullable=True)

    embedding: Mapped[list[float] | None] = mapped_column(Vector(384), nullable=True)
    embedding_model: Mapped[str] = mapped_column(String(100), nullable=False)
    chunking_strategy: Mapped[str] = mapped_column(String(50), nullable=False)

Vector(384) is the pgvector column type mentioned in section 1: 384 is the number of dimensions (individual numbers) the embedding model produces for each chunk of text (Part 4 explains exactly why 384, and what a "dimension" even means). Every chunk also carries owner_id and knowledge_base_id directly, as columns on the row itself, instead of only being reachable by looking them up through the related documents row (what's called a join: fetching data by following a relationship between two tables, e.g. "go from this chunk to its parent document, then read the owner off that"). Copying those two values directly onto the chunk, a practice called denormalization, means every retrieval query can filter "only this user's, only this knowledge base's chunks" without an extra join. It's a deliberate, small trade of some data repetition for query simplicity and speed, made on purpose on the hottest, most frequently-run path in the whole system.

PYTHON
class MessageCitation(Base, UUIDMixin, TimestampMixin):
    __tablename__ = "message_citations"

    # Nullable + SET NULL: a citation is a historical record of what was
    # shown to the user at generation time, and must survive the source
    # chunk/document being deleted or reindexed later.
    chunk_id: Mapped[uuid.UUID | None] = mapped_column(
        ForeignKey("document_chunks.id", ondelete="SET NULL"), nullable=True,
    )
    document_id: Mapped[uuid.UUID | None] = mapped_column(
        ForeignKey("documents.id", ondelete="SET NULL"), nullable=True,
    )
    rank: Mapped[int] = mapped_column(Integer, nullable=False)
    score: Mapped[float] = mapped_column(Float, nullable=False)
    document_filename: Mapped[str] = mapped_column(String(255), nullable=False)
    excerpt: Mapped[str] = mapped_column(Text, nullable=False)

First, two quick definitions that make the code above readable. A foreign key is a column that points at a row in another table, here chunk_id points at a row in document_chunks, that's how the database knows these two rows are related. ondelete controls what happens to this row when the row it points to gets deleted: CASCADE means "delete me too," while SET NULL means "just blank out the pointer and leave me alone."

This table is worth sitting with, because at first glance it looks like a modeling mistake. Why copy document_filename and an excerpt into the citation row, instead of just storing chunk_id and joining to document_chunks whenever you need to display it (the usual, less repetitive way to do it)?

Because a citation isn't a live pointer: it's a receipt. Think of a store receipt: it keeps showing the price you paid even if that product goes on clearance tomorrow, because it's a record of a moment in time, not a live price lookup. A citation works the same way: it records what evidence the user was actually shown at the moment an answer was generated. If the source document later gets deleted, or re-processed with a better chunker (which deletes and recreates all its chunks, see Part 3), a citation that joined live would either break or silently start pointing at a different chunk that happens to reuse the same ID slot. Copying the display data at write time, and using ON DELETE SET NULL instead of CASCADE on the foreign keys (so a deleted chunk blanks out the link instead of deleting the citation along with it), means old citations keep displaying correctly forever, even after their source evaporates. History shouldn't change just because the present did.


5. Everything running locally, in one Docker Compose file

Everything described above, Postgres, Redis, object storage, the API server, and the worker, needs to run together on a developer's machine without anyone manually installing and configuring six different pieces of software. Docker packages each piece of software into a self-contained "container" that runs the same way everywhere. Docker Compose is a tool that starts a whole group of containers together from one config file, each one pre-wired to find the others.

YAML
services:
  postgres:   { image: pgvector/pgvector:pg16 }
  redis:      { image: redis:7-alpine }
  minio:      { image: bitnamilegacy/minio }   # MinIO's own image stopped being freely pullable
  migrate:    { command: ["uv", "run", "alembic", "upgrade", "head"] }
  backend:    { command: ["uv", "run", "uvicorn", "app.main:app", "--reload"] }
  worker:     { command: ["uv", "run", "arq", "app.workers.worker_settings.WorkerSettings"] }
  frontend:   { command: ["pnpm", "dev"] }

Seven services, one command (docker compose up), and all of it is running. A few small but deliberate touches:

  • migrate (which applies any pending database schema changes, via a tool called Alembic) runs once and finishes, as a "one-shot" service that the backend and worker services both wait on (depends_on: ... condition: service_completed_successfully). That line means: don't start backend or worker until migrate has finished successfully, not just started. Nobody ends up serving traffic against a database schema that isn't up to date yet.
  • The embedding model and tokenizer files get downloaded from the internet the first time they're used. Those downloads are cached in named Docker volumes (a chunk of storage that survives even when its container is thrown away and rebuilt), shared between backend and worker, so restarting a container doesn't mean re-downloading a model every time.
  • .venv (Python's dependency folder) and node_modules (JavaScript's) are also kept in named volumes rather than synced in directly from the developer's own machine. That's because some of their contents are compiled, platform-specific binaries, and a Linux container trying to run binaries compiled for macOS is a classic, confusing way to lose an afternoon.

6. What's next

Part 3 follows one uploaded file all the way through the pipeline that this part's worker only showed the outside of: parsing, cleaning, chunking, and embedding, with the real code for each step and the specific, slightly clever trick used to strip running headers and footers out of a PDF automatically.