From the blog

Multi-Tenant RAG in Elixir: Keep Each Customer's Documents Isolated in pgvector

By Liam Killingback ·

Multi-Tenant RAG in Elixir: Keep Each Customer’s Documents Isolated in pgvector

A single-user RAG demo has one table of chunks and one query. The day you sell it to a second company, that design becomes a liability: every customer’s contracts, support tickets and internal docs sit in the same vector index, and the only thing standing between Acme’s question and Globex’s answer is whether somebody remembered a where clause.

Multi-tenant RAG in Elixir is mostly a data isolation problem with a retrieval quality problem hiding inside it. This post covers both: how to model tenant-owned chunks in Postgres with pgvector, how to make the tenant filter impossible to forget in Ecto, why a filtered vector search can quietly return too few results, how to add Row Level Security as a second lock, and how to test that one tenant can never retrieve another’s text.

It assumes you already have basic retrieval working. If not, RAG in Elixir with pgvector and Postgres covers the setup, and this post picks up where that one stops.

What goes wrong in a shared index

There are three separate ways a shared index leaks, and they need different fixes.

  1. A missing filter. Someone writes a new retrieval path (a “related documents” sidebar, an admin search, a background summariser) and forgets the tenant condition. Similarity search does not care who owns a row. It returns the nearest vectors, and the model happily quotes them.
  2. A filter applied too late. The query has the tenant condition, but the vector index returns its nearest candidates first and Postgres filters afterwards. A small tenant in a large index gets two results instead of eight, or none. Nothing leaks, but answers get worse and nobody can tell why.
  3. A leak around the database. The chunks are isolated, but a cache, a conversation memory table or a log line is keyed without the tenant. The model’s answer for one customer is served to another.

The rest of this post handles them in that order.

One table, one tenant column

For most SaaS products the right model is the plain one: a single chunks table with an org_id on every row. A schema or database per tenant sounds safer, but it multiplies migrations, connection pools and indexes by your customer count, and it is rarely needed below the level of a compliance contract that demands it.

defmodule MyApp.Repo.Migrations.CreateChunks do
  use Ecto.Migration

  def up do
    execute "CREATE EXTENSION IF NOT EXISTS vector"

    create table(:chunks) do
      add :org_id, references(:orgs, on_delete: :delete_all), null: false
      add :document_id, references(:documents, on_delete: :delete_all), null: false
      add :position, :integer, null: false
      add :content, :text, null: false
      add :embedding, :vector, size: 1536, null: false
      timestamps(updated_at: false)
    end

    create index(:chunks, [:org_id, :document_id])
    execute "CREATE INDEX chunks_embedding_idx ON chunks USING hnsw (embedding vector_cosine_ops)"
  end

  def down do
    drop table(:chunks)
  end
end

Two details matter here. org_id is null: false, so a chunk without an owner cannot exist. And the chunk carries its own org_id instead of relying on a join through documents. That is deliberate denormalisation: the filter has to be on the same table as the vector column for Postgres to combine them well, and for Row Level Security to work later.

The schema uses the pgvector Hex package for the column type:

defmodule MyApp.Rag.Chunk do
  use Ecto.Schema

  schema "chunks" do
    field :org_id, :id
    field :document_id, :id
    field :position, :integer
    field :content, :string
    field :embedding, Pgvector.Ecto.Vector
    timestamps(updated_at: false)
  end
end

Make the tenant filter impossible to forget

A convention (“always pass org_id“) fails the first time someone is in a hurry. Ecto has a better tool: the repo’s prepare_query/3 callback runs on every query, so the repo itself can add the tenant condition or refuse to run without one. This is the pattern from Ecto’s own multi-tenancy guide.

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.Postgres

  require Ecto.Query

  @tenant_key {__MODULE__, :org_id}

  def put_org_id(org_id), do: Process.put(@tenant_key, org_id)
  def get_org_id, do: Process.get(@tenant_key)

  @impl true
  def default_options(_operation), do: [org_id: get_org_id()]

  @impl true
  def prepare_query(_operation, query, opts) do
    cond do
      opts[:skip_org_id] || opts[:schema_migration] ->
        {query, opts}

      org_id = opts[:org_id] ->
        {Ecto.Query.where(query, org_id: ^org_id), opts}

      true ->
        raise "expected org_id or skip_org_id to be set"
    end
  end
end

Now set the tenant once per request, in the plug or on_mount hook that already loads the current organisation:

def on_mount(:put_tenant, _params, _session, socket) do
  MyApp.Repo.put_org_id(socket.assigns.current_org.id)
  {:cont, socket}
end

From here, Repo.all(Chunk) returns only the current tenant’s chunks, and a query in a process with no tenant raises instead of returning everyone’s data. The failure mode has flipped from “silent leak” to “loud crash”, which is the whole point.

Three caveats, because this pattern has sharp edges:

  • The tenant lives in the process dictionary, so it does not follow you into a Task or an Oban job. Pass org_id explicitly and call put_org_id/1 at the top of the job.
  • Tables without an org_id (users, orgs themselves, Oban’s own tables) need skip_org_id: true, or a second repo module for global data. Be strict about who is allowed to type that option.
  • prepare_query/3 covers queries, not Repo.insert/2. Set org_id in your changesets from the same source.

The retrieval query

With the repo doing the scoping, the retrieval function stays short:

defmodule MyApp.Rag do
  import Ecto.Query
  import Pgvector.Ecto.Query

  alias MyApp.Rag.Chunk
  alias MyApp.Repo

  def search(question, k \\ 8) do
    embedding = MyApp.Embeddings.embed!(question)

    Chunk
    |> order_by([c], cosine_distance(c.embedding, ^Pgvector.new(embedding)))
    |> limit(^k)
    |> select([c], %{id: c.id, document_id: c.document_id, content: c.content})
    |> Repo.all()
  end
end

There is no org_id in sight, and that is fine: the repo adds WHERE org_id = $1. If you prefer the condition to be visible at the call site, pass the org as an argument and keep prepare_query/3 as the backstop. Either way, there is exactly one retrieval function, and every feature that needs context goes through it.

The embedding call is ordinary Req:

defmodule MyApp.Embeddings do
  def embed!(text) do
    Req.post!("https://api.openai.com/v1/embeddings",
      auth: {:bearer, System.fetch_env!("OPENAI_API_KEY")},
      json: %{model: "text-embedding-3-small", input: text}
    ).body["data"]
    |> hd()
    |> Map.fetch!("embedding")
  end
end

The quiet problem: filtered search returns too few results

Here is the part most tutorials skip. An HNSW index knows nothing about org_id. When you ask for the eight nearest chunks WHERE org_id = 42, Postgres walks the index, collects a candidate list (40 by default, set by hnsw.ef_search), and then throws away every candidate that belongs to another tenant.

If org 42 owns half the table, that works. If org 42 owns 0.5% of the table, the 40 nearest vectors in the whole index probably contain none of theirs. The query returns zero or one row, the model answers “I could not find that in your documents”, and your smallest customers (often your newest ones, still deciding whether to pay) get the worst product.

You have three fixes, in rising order of effort.

1. Iterative index scans

pgvector 0.8 added iterative scans: when filtering leaves too few rows, the index keeps scanning until it has enough or hits a limit. Turn it on per transaction, next to the query:

def search(question, k \\ 8) do
  embedding = MyApp.Embeddings.embed!(question)

  {:ok, rows} =
    Repo.transaction(fn ->
      Repo.query!("SET LOCAL hnsw.iterative_scan = strict_order")

      Chunk
      |> order_by([c], cosine_distance(c.embedding, ^Pgvector.new(embedding)))
      |> limit(^k)
      |> Repo.all()
    end)

  rows
end

strict_order keeps results in exact distance order. relaxed_order is faster and allows slight reordering, which is acceptable if you rerank afterwards. hnsw.max_scan_tuples caps how far the scan goes. This is the first thing to try, and for many apps it is the only thing needed. Check your pgvector version with SELECT extversion FROM pg_extension WHERE extname = 'vector' before relying on it.

2. Skip the vector index for small tenants

A tenant with 3,000 chunks does not need approximate search at all. An exact scan over 3,000 rows using the org_id b-tree index takes a few milliseconds and returns perfect results. Postgres often picks this plan by itself when the filter is selective enough, and you can check with EXPLAIN ANALYZE. Exact search for small tenants is not a compromise. It is better recall than HNSW gives anyone.

3. Partition by tenant

When a handful of tenants hold millions of chunks each, give the table hash partitions on org_id, each with its own HNSW index:

CREATE TABLE chunks (
  id bigserial,
  org_id bigint NOT NULL,
  document_id bigint NOT NULL,
  content text NOT NULL,
  embedding vector(1536) NOT NULL,
  PRIMARY KEY (org_id, id)
) PARTITION BY HASH (org_id);

CREATE TABLE chunks_p0 PARTITION OF chunks FOR VALUES WITH (MODULUS 16, REMAINDER 0);
-- ...repeat for remainders 1 to 15, then index each partition

A query with org_id = 42 touches one partition, so each index is a sixteenth of the size and far more likely to contain the tenant’s rows near the top. The cost is real: the primary key must include org_id, index builds multiply, and repartitioning later is a migration project. Reach for it when measurements say so, not on day one.

Row Level Security as the second lock

prepare_query/3 protects every query that goes through Ecto. It does not protect a raw Repo.query!/2, a query run with skip_org_id: true by mistake, or a psql session during an incident. Postgres Row Level Security closes that gap by enforcing the same rule inside the database.

ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE chunks FORCE ROW LEVEL SECURITY;

CREATE POLICY chunks_tenant_isolation ON chunks
  USING (org_id = current_setting('app.current_org', true)::bigint);

The policy reads a session setting, which you set inside the transaction that runs the search:

def with_tenant(org_id, fun) do
  Repo.transaction(fn ->
    Repo.query!("SELECT set_config('app.current_org', $1, true)", [to_string(org_id)])
    fun.()
  end)
end

The third argument true makes the setting local to the transaction, so a pooled connection never carries one tenant’s id into the next checkout. With no setting present, current_setting(..., true) returns NULL, the comparison is not true, and the query returns nothing. Again, the failure mode is an empty result, not a leak.

Two things to know before you ship it. Table owners bypass RLS unless you add FORCE ROW LEVEL SECURITY, and superusers bypass it always, so your app should connect as an ordinary role. And RLS adds a condition to every query on the table, including your ingestion jobs, so they need with_tenant/2 as well. For many teams RLS on the chunks and documents tables alone is a sensible middle ground: the highest-risk data gets two locks without converting the whole app.

Ingestion carries the tenant too

Embedding happens in a background job, and a job has no request context. Put the tenant in the job arguments and restore it first thing:

defmodule MyApp.Workers.EmbedDocument do
  use Oban.Worker, queue: :embeddings, max_attempts: 5

  alias MyApp.{Rag, Repo}

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"org_id" => org_id, "document_id" => document_id}}) do
    Repo.put_org_id(org_id)

    document = Repo.get!(Rag.Document, document_id)

    rows =
      document
      |> Rag.Chunker.split()
      |> Enum.with_index()
      |> Enum.map(fn {text, position} ->
        %{
          org_id: org_id,
          document_id: document.id,
          position: position,
          content: text,
          embedding: Pgvector.new(MyApp.Embeddings.embed!(text)),
          inserted_at: DateTime.utc_now(:second)
        }
      end)

    Repo.insert_all(Rag.Chunk, rows)
    :ok
  end
end

Repo.get!/2 runs through prepare_query/3, so a job enqueued with a mismatched org_id and document_id raises Ecto.NoResultsError instead of embedding one tenant’s document into another tenant’s index. That check costs nothing and catches a whole class of bugs in whatever code enqueues the job. Chunk sizing is its own topic, covered in text chunking for RAG in Elixir.

Leaks around the database

Once retrieval is scoped, check everything that sits next to it:

  • Caches. An answer cache or a semantic cache keyed only on the question will serve Acme’s answer to Globex when both ask “what is our refund policy”. The tenant id belongs in every cache key and in the WHERE clause of every cache lookup.
  • Conversation history and memory. Stored chat turns and extracted memories are tenant data. Give those tables an org_id and let the same repo rule cover them.
  • Shared knowledge. Product documentation that every customer may read is a legitimate shared corpus. Model it explicitly (a reserved org, or a second table searched separately and merged) instead of making org_id nullable, which turns “no tenant” into a valid state.
  • Logs and traces. Prompt logs contain retrieved text. Tag every trace with the tenant and restrict who can read them.
  • Fine-tuning and evals. Never build a shared fine-tune or a few-shot prompt from one customer’s documents.

Per-user permissions inside a tenant (the finance folder that only finance may search) are a further layer: store an access list or folder id on the chunk and filter on it in the same query. The pattern is identical, only the key changes.

Test the isolation, not the happy path

Isolation is a property worth a permanent test. Seed two tenants with near-identical text, search as one, and assert that nothing from the other ever appears:

defmodule MyApp.RagIsolationTest do
  use MyApp.DataCase, async: true

  alias MyApp.{Rag, Repo}

  test "search never returns another tenant's chunks" do
    acme = insert(:org)
    globex = insert(:org)
    vector = Pgvector.new(List.duplicate(0.1, 1536))

    for org <- [acme, globex] do
      doc = insert(:document, org_id: org.id)

      Repo.insert_all(Rag.Chunk, [
        %{
          org_id: org.id,
          document_id: doc.id,
          position: 0,
          content: "Refund policy for #{org.name}",
          embedding: vector,
          inserted_at: DateTime.utc_now(:second)
        }
      ])
    end

    Repo.put_org_id(acme.id)
    results = Rag.search_by_vector(vector, 8)

    assert length(results) == 1
    assert Enum.all?(results, &(&1.content =~ acme.name))
  end

  test "a query with no tenant raises" do
    Repo.put_org_id(nil)
    assert_raise RuntimeError, ~r/expected org_id/, fn -> Repo.all(Rag.Chunk) end
  end
end

The identical embeddings are intentional. They are the worst case: the other tenant’s chunk is exactly as near as your own, so only the filter can keep it out. Splitting search/2 into an embedding step and a search_by_vector/2 step also keeps the test off the network. Add a third test with one tenant at 20 chunks and another at 20,000 to catch the “too few results” problem before a customer does.

Summary

Multi-tenant RAG in Elixir comes down to five decisions. Put org_id on the chunk row itself. Let prepare_query/3 add the tenant filter to every Ecto query and raise when it is missing. Fix filtered recall with iterative scans first, exact search for small tenants second, and partitions only when the numbers demand them. Add Row Level Security on the tables that hold customer text so a raw query cannot leak either. And scope every cache, memory table and log by tenant, with a test that proves it.

If you would rather start from a working document pipeline, pdfai is a Phoenix LiveView starter with PDF upload, text extraction, embeddings and chat over your documents already wired together, so the tenant scoping in this post is the main thing left to add. For the retrieval quality side, hybrid search in Elixir pairs well with a tenant filter, because full-text search uses the same org_id condition.

Building more than one product on Phoenix? The Builder Pass includes every PhxTemplates starter, AI templates included, for one lifetime price.