IamBishal

Module 1Lesson 2 of 3Hands-on

1.2 Ingest and search support documents with pgvector

Builds ingest and retrieve for a multi-tenant support assistant: PostgreSQL 17 with pgvector in Docker, a schema whose chunks carry tenant and document ACL tied by a cascading foreign key, paragraph-based chunking with overlap, an embedding provider interface, a cosine HNSW index confirmed with EXPLAIN, and an unprotected /search endpoint that visibly returns another tenant's runbook.

Lesson 1 drew the three stages of a RAG API and the places a multi-tenant assistant leaks. This lesson builds the first two stages for real: ingest, which turns tenant documents into stored chunks with embeddings, and retrieve, which finds the chunks closest to a question.

The endpoint you build here is deliberately unprotected. It searches every tenant's documents, and you will watch it return another tenant's runbook. The schema already carries everything lesson 4 needs to close that leak; the query just doesn't use it yet.

By the end of this lesson you will be able to:

  1. start PostgreSQL with pgvector next to a Node.js project and confirm the extension version
  2. create a schema where every chunk carries its tenant, its document's ACL (the roles allowed to see it) and an embedding sized to the provider
  3. chunk support documents with a size, overlap and boundary rule, and explain what each choice trades away
  4. put embedding generation behind a provider interface, and explain what cosine distance measures
  5. build an HNSW index with the operator class that matches cosine distance, and confirm with EXPLAIN that the query uses it
  6. call /search and read the top-k chunks, distances and source documents
  7. explain why access filtering will have to happen inside this query, not after it

You need Node.js 24.2 or later, Docker, comfort reading SQL (joins, foreign keys, upserts and transactions all appear), and the companion code. The scripts use import.meta.main to tell "run directly" from "imported"; it arrived in Node.js 24.2 and is still marked early development, and package.json declares the minimum.

bash
git clone --filter=blob:none --sparse https://github.com/bishal-saha/tutorials-code
cd tutorials-code
git sparse-checkout set build-a-secure-rag-api
cd build-a-secure-rag-api/01-foundations/02-ingest-and-search-with-pgvector

The code defaults to a deterministic fake embedder (step 3), so nothing here needs an API key.

1. What you're building

A document ACL is the list of roles within a tenant allowed to see a document; this series has two roles, agent and end_user. Two tenants share the service. Acme Analytics has a help article on exports for agents and end users, an agent-only runbook for stuck exports and a help article on API keys. Globex Payroll has an agent-only runbook for stuck exports worded much like Acme's, a billing help article and an SSO runbook. The near-identical runbooks are on purpose: they make a cross-tenant leak easy to see.

the lesson's files
compose.yaml                 PostgreSQL 17 + pgvector, pinned
scripts/schema.sql           tenants, documents, chunks, HNSW index
scripts/migrate.js           creates the schema with the provider's vector size
scripts/ingest.js            the trusted ingest job: one folder per tenant
src/chunker.js               Markdown to chunks
src/embeddings/provider.js   the provider interface (fake.js, http.js implement it)
src/ingest.js                one document in one transaction
src/search.js                top-k by cosine distance (unprotected)
src/server.js                GET /search
data/tenants/{acme,globex}/  documents plus a manifest per tenant

2. Step 1: start PostgreSQL with pgvector

The pgvector project publishes a Docker image that adds the extension to the official Postgres image. Pin both versions in the tag, so the lesson behaves the same next month. The port is published on 127.0.0.1 only: the demo password isn't a secret, so the database shouldn't be reachable from your network.

compose.yaml
services:
  db:
    image: pgvector/pgvector:0.8.7-pg17
    environment:
      POSTGRES_USER: rag
      POSTGRES_PASSWORD: rag
      POSTGRES_DB: rag
    ports:
      - "127.0.0.1:${DB_PORT:-5433}:5432"   # local only; the demo password is not a secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U rag -d rag"]
      interval: 2s
      retries: 30
bash
npm install
npm run db:up
export DATABASE_URL=postgres://rag:rag@localhost:5433/rag
npm run migrate

npm run migrate creates the schema that Step 2 explains. It drops and recreates the three tables, so only run it on a database you're happy to empty. It prints the vector size it used and the extension version. Check the version yourself too, from a psql session inside the container; this series expects 0.8.x:

bash
docker compose exec db psql -U rag -d rag -c "SELECT extversion FROM pg_extension WHERE extname = 'vector';"
output
{ dimensions: 256, pgvector: '0.8.7' }

 extversion 
------------
 0.8.7
(1 row)

3. Embeddings and cosine distance

An embedding model turns text into a fixed-length list of numbers, a vector, so that texts with similar meaning get vectors pointing in similar directions. Cosine distance compares only those directions: it ignores the vectors' lengths and measures the angle between them. pgvector's <=> operator returns it, and because cosine distance is 1 minus cosine similarity, smaller means closer. Try it on two-dimensional vectors:

bash
docker compose exec db psql -U rag -d rag -c "SELECT '[1,0]'::vector <=> '[1,0]' AS same, '[1,0]'::vector <=> '[5,0]' AS longer, '[1,0]'::vector <=> '[0,1]' AS perpendicular, '[1,0]'::vector <=> '[-1,0]' AS opposite;"
output
 same | longer | perpendicular | opposite 
------+--------+---------------+----------
    0 |      0 |             1 |        2
(1 row)

The same direction gives 0 even when one vector is five times longer; perpendicular (unrelated) gives 1; opposite gives 2. Distance measures closeness of meaning and nothing else: it doesn't know who owns a chunk.

4. Step 2: a schema that carries tenant and ACL on every chunk

scripts/schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE tenants (
  id   uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  slug text UNIQUE NOT NULL,
  name text NOT NULL
);

CREATE TABLE documents (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id     uuid NOT NULL REFERENCES tenants (id),
  source_key    text NOT NULL,                -- stable id for re-ingest, e.g. the file name
  title         text NOT NULL,
  allowed_roles text[] NOT NULL,              -- the document ACL
  updated_at    timestamptz NOT NULL DEFAULT now(),
  UNIQUE (tenant_id, source_key),
  UNIQUE (id, tenant_id, allowed_roles),      -- target of the chunks foreign key below
  CHECK (cardinality(allowed_roles) > 0 AND allowed_roles <@ ARRAY['agent', 'end_user'])
);

CREATE TABLE chunks (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  document_id   uuid NOT NULL,
  tenant_id     uuid NOT NULL,
  allowed_roles text[] NOT NULL,
  chunk_index   int NOT NULL,
  content       text NOT NULL,
  embedding     vector(:dimensions) NOT NULL,
  UNIQUE (document_id, chunk_index),
  -- A chunk's tenant and ACL must equal its document's. ON UPDATE CASCADE copies an
  -- ACL change to every chunk; ON DELETE CASCADE removes chunks with their document.
  FOREIGN KEY (document_id, tenant_id, allowed_roles)
    REFERENCES documents (id, tenant_id, allowed_roles) ON UPDATE CASCADE ON DELETE CASCADE
);

-- vector_cosine_ops matches the <=> (cosine distance) operator used by search.
CREATE INDEX chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);

Every chunk repeats its document's tenant_id and allowed_roles. Lesson 4's filter has to sit on the row being ranked, so the chunk needs those columns itself. Copies can drift, so the composite foreign key ties all three columns to the document: a chunk can't claim a different tenant or ACL, an ACL change on the document cascades to every chunk in the same statement, and deleting a document deletes its chunks. You'll test the foreign key and the vector size on real data once Step 4 has ingested it.

The vector size comes from the provider. vector(:dimensions) is filled in by migrate.js from the provider's dimensions. If a provider returns a different size, the insert fails loudly instead of storing something unsearchable.

One limit to know before choosing a model: pgvector's HNSW index supports the vector type up to 2,000 dimensions, so a model with larger vectors needs a different type or a reduced size.

The index names its operator class. pgvector needs one index per distance function, and vector_cosine_ops is the one that serves <=>. An index built with the L2 or inner-product class won't be used by a cosine query. Step 5 explains what this HNSW index trades and confirms the query uses it.

5. Step 3: put the embedding provider behind an interface

Nothing outside src/embeddings/ knows which model is in use. The project depends only on Fastify and the pg driver, so there is no vendor SDK to import, and the only files that call fetch or import a concrete embedder are inside that folder:

output
$ grep -A3 '"dependencies"' package.json
  "dependencies": {
    "fastify": "^5.6.0",
    "pg": "^8.16.0"
  }
$ grep -rlE "fetch\(|(fake|http)\.js'" src
src/embeddings/http.js
src/embeddings/provider.js

Ingest and search call one function:

src/embeddings/provider.js
import { config } from '../config.js';
import { createFakeEmbedder } from './fake.js';
import { createHttpEmbedder } from './http.js';

/**
 * The only contract ingest and search depend on.
 * @typedef {object} EmbeddingProvider
 * @property {number} dimensions  fixed vector length; the chunks.embedding column is created with it
 * @property {(texts: string[]) => Promise<number[][]>} embed  one vector per input, same order
 */

/** @returns {EmbeddingProvider} */
export function createEmbeddingProvider(options = config.embeddings) {
  // The fake is the default for local runs and tests; never let it reach production by accident.
  if (options.provider === 'fake' && process.env.NODE_ENV === 'production') throw new Error('EMBEDDINGS_PROVIDER=fake is not allowed in production');
  if (options.provider === 'fake') return createFakeEmbedder(options.dimensions);
  if (options.provider === 'http') return createHttpEmbedder(options);
  throw new Error(`Unknown EMBEDDINGS_PROVIDER: ${options.provider}`);
}

The series ships two implementations. http.js posts { model, input } to a configured URL and expects { data: [{ embedding }] } back, and checks that every vector has the configured size. Adapt it if your provider uses a different request shape. fake.js is a deterministic embedder for tests and offline runs: it hashes words into a 256-dimensional vector, so texts that share words land close together.

src/embeddings/fake.js (excerpt)
export function createFakeEmbedder(dimensions = 256) {
  const embedOne = (text) => {
    const v = new Array(dimensions).fill(0);
    for (const token of tokenize(text)) {
      const h = fnv1a(token);
      v[h % dimensions] += (h & 0x80000000) ? -1 : 1;
    }
    const norm = Math.hypot(...v) || 1;
    return v.map((x) => x / norm);
  };
  return { dimensions, embed: async (texts) => texts.map(embedOne) };
}

Plugging in a real provider

Set EMBEDDINGS_PROVIDER=http, EMBEDDINGS_URL, EMBEDDINGS_MODEL, EMBEDDINGS_DIMENSIONS and, if needed, EMBEDDINGS_API_KEY (all in .env.example), then migrate and re-ingest: vectors from two models can't be compared. With a hosted provider, every chunk and question leaves your network, which belongs in your data-processing terms with tenants.

The fake knows nothing about meaning. "Reset my password" and "recover account access" share no words, so it won't match them; a real embedding model would typically place them close. That's fine for this series: the tests check the plumbing and the access rules, which don't depend on how clever the model is.

6. Step 4: chunk the documents and ingest them

A chunk is what retrieval returns and what the model reads, so its boundaries decide whether an answer arrives whole. The chunker makes three choices.

src/chunker.js (excerpt)
// Split Markdown into chunks of whole paragraphs, up to maxWords each.
// - A chunk never ends mid-paragraph, so a numbered step stays with its neighbours.
// - Each chunk starts with its heading path ("Title > Section"), so a chunk that says
//   "restart the worker" still says which procedure it belongs to.
// - Trailing paragraphs that fit in overlapWords in total are repeated at the start of the
//   next chunk, so a short step or caveat at the boundary appears in both. Paragraphs are
//   never cut for overlap: an answer longer than the budget can still be split.
// - A single paragraph longer than maxWords is split at sentence boundaries.
const words = (s) => s.split(/\s+/).filter(Boolean).length;

// splitLongParagraph(paragraph, maxWords) cuts at sentence ends; see the companion file.

export function chunkMarkdown(title, markdown, { maxWords = 120, overlapWords = 25 } = {}) {
  const sections = [];
  let heading = null;
  let paragraphs = [];
  const flush = () => {
    if (paragraphs.length) sections.push({ path: heading ? `${title} > ${heading}` : title, paragraphs });
    paragraphs = [];
  };
  for (const block of markdown.split(/\n\s*\n/).map((b) => b.trim()).filter(Boolean)) {
    const h = block.match(/^(#{1,6})\s+(.*)$/);
    if (h && !block.includes('\n')) {
      if (h[1].length === 1) continue; // the document's own title is already in the path
      flush();
      heading = h[2].trim();
    } else {
      paragraphs.push(...(words(block) > maxWords ? splitLongParagraph(block, maxWords) : [block]));
    }
  }
  flush();

  const chunks = [];
  for (const { path, paragraphs: paras } of sections) {
    let current = [];
    const emit = () => {
      chunks.push(`${path}\n\n${current.join('\n\n')}`);
      // carry trailing paragraphs that fit in the overlap budget into the next chunk
      const carry = [];
      for (let i = current.length - 1; i >= 0; i--) {
        if (words([current[i], ...carry].join(' ')) > overlapWords) break;
        carry.unshift(current[i]);
      }
      current = carry.length < current.length ? carry : [];
    };
    for (const p of paras) {
      if (current.length && words([...current, p].join(' ')) > maxWords) {
        emit();
        // never let carried overlap push a chunk past maxWords
        if (current.length && words([...current, p].join(' ')) > maxWords) current = [];
      }
      current.push(p);
    }
    if (current.length) chunks.push(`${path}\n\n${current.join('\n\n')}`);
  }
  return chunks;
}

It works in two passes. The first walks the Markdown blocks, starting a new section at every heading below the title and splitting any over-long paragraph at sentence ends. The second packs each section's paragraphs into chunks. Carried overlap counts toward the limit, and if it would push the next chunk past 120 words it is dropped. The heading path isn't counted, so a chunk's text can be a few words over.

  • Size: up to 120 words. Big enough for a short procedure, small enough not to drag in the next section. Larger chunks give the model more context per hit but dilute the match; smaller ones match precisely but lose the sentence that made them meaningful.
  • Boundary: each heading starts a new chunk, and a chunk holds whole paragraphs. A numbered list written as one Markdown block stays together (a list with blank lines between items is packed item by item), and a paragraph longer than the limit is split at sentence ends. The cost: chunk sizes become uneven, and a two-line section, like the runbook's intro, becomes a chunk too small to answer much on its own.
  • Overlap: short trailing paragraphs carried forward. When a section needs two chunks, any final paragraphs that fit in 25 words also start the next chunk, so a short step or caveat at the boundary appears in both. An answer longer than 25 words can still be split across two chunks. The cost: duplicated text is stored and embedded twice, and two near-identical chunks can take two of the top-k slots.

Ingest is a trusted job, not a public endpoint. It reads one folder per tenant, takes the tenant from the folder it was pointed at, and takes each document's ACL from that tenant's manifest. Nothing inside a document can change where it lands.

src/ingest.js
import { pool, toVector } from './db.js';
import { chunkMarkdown } from './chunker.js';
import { config } from './config.js';

const ROLES = new Set(['agent', 'end_user']);

/**
 * Ingest (or re-ingest) one document for one tenant.
 * tenantId comes from the caller, which is the trusted ingest job, never from the document.
 * Embedding happens before the transaction, so no database lock is held during a slow call.
 */
export async function ingestDocument(provider, { tenantId, sourceKey, title, allowedRoles, markdown }) {
  if (!allowedRoles.length || !allowedRoles.every((r) => ROLES.has(r))) {
    throw new Error(`Invalid document ACL for ${sourceKey}: ${allowedRoles}`);
  }
  const chunks = chunkMarkdown(title, markdown, config.chunking);
  const vectors = await provider.embed(chunks);

  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const { rows: [doc] } = await client.query(
      `INSERT INTO documents (tenant_id, source_key, title, allowed_roles)
       VALUES ($1, $2, $3, $4)
       ON CONFLICT (tenant_id, source_key)
       DO UPDATE SET title = EXCLUDED.title, allowed_roles = EXCLUDED.allowed_roles, updated_at = now()
       RETURNING id, allowed_roles`,
      [tenantId, sourceKey, title, allowedRoles],
    );
    // Replace the old chunks in the same transaction: a reader sees the old set or the new one.
    await client.query('DELETE FROM chunks WHERE document_id = $1', [doc.id]);
    for (const [i, content] of chunks.entries()) {
      await client.query(
        `INSERT INTO chunks (document_id, tenant_id, allowed_roles, chunk_index, content, embedding)
         VALUES ($1, $2, $3, $4, $5, $6)`,
        [doc.id, tenantId, doc.allowed_roles, i, content, toVector(vectors[i])],
      );
    }
    await client.query('COMMIT');
    return { documentId: doc.id, chunks: chunks.length };
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

Inside the transaction the document is upserted and its old chunks are replaced, so re-ingesting a changed document never leaves stale chunks behind. The source_key, here the file name, makes re-ingest an update rather than a second copy. A search running at the same moment sees the old set or the new one, never a mix, because PostgreSQL only shows a transaction's changes once it commits.

Embedding runs before the transaction opens, so no lock is held during the network call.
bash
npm run ingest
output
┌─────────┬──────────┬──────────────────────┬──────────────────┬────────┐
│ (index) │ tenant   │ file                 │ roles            │ chunks │
├─────────┼──────────┼──────────────────────┼──────────────────┼────────┤
│ 0       │ 'acme'   │ 'exports-help.md'    │ 'agent,end_user' │ 3      │
│ 1       │ 'acme'   │ 'exports-runbook.md' │ 'agent'          │ 4      │
│ 2       │ 'acme'   │ 'api-keys-help.md'   │ 'agent,end_user' │ 2      │
│ 3       │ 'globex' │ 'exports-runbook.md' │ 'agent'          │ 4      │
│ 4       │ 'globex' │ 'billing-help.md'    │ 'agent,end_user' │ 3      │
│ 5       │ 'globex' │ 'sso-runbook.md'     │ 'agent'          │ 3      │
└─────────┴──────────┴──────────────────────┴──────────────────┴────────┘

Inspect what was stored before trusting it. scripts/inspect-chunks.sql checks every chunk of every document:

scripts/inspect-chunks.sql
-- One row per document: chunks vs distinct heading paths (sections), the largest and
-- smallest chunk in words (heading path excluded), and chunks that start mid-list.
SELECT d.title,
       count(*) AS chunks,
       count(DISTINCT split_part(c.content, E'\n', 1)) AS sections,
       max(b.words) AS max_words,
       min(b.words) AS min_words,
       count(*) FILTER (WHERE b.body ~ '^[2-9]\. ') AS starts_mid_list
FROM chunks c
JOIN documents d ON d.id = c.document_id,
LATERAL (SELECT substr(c.content, strpos(c.content, E'\n\n') + 2) AS body) s,
LATERAL (SELECT s.body, cardinality(regexp_split_to_array(trim(s.body), '\s+')) AS words) b
GROUP BY d.title
ORDER BY d.title;
bash
docker compose exec -T db psql -U rag -d rag < scripts/inspect-chunks.sql
output
               title               | chunks | sections | max_words | min_words | starts_mid_list 
-----------------------------------+--------+----------+-----------+-----------+-----------------
 Exporting your data               |      3 |        3 |        48 |        32 |               0
 Invoices and billing              |      3 |        3 |        34 |        18 |               0
 Rotating API keys                 |      2 |        2 |        38 |        27 |               0
 Runbook: recovering stuck exports |      4 |        4 |        50 |         3 |               0
 Runbook: SSO login failures       |      3 |        3 |        48 |         3 |               0
 Runbook: stuck data exports       |      4 |        4 |        81 |        13 |               0
(6 rows)

Chunks equal sections in every document, so no section was split and overlap doesn't fire on this data; the exercise below makes it fire. No chunk is near the 120-word limit and none starts mid-list. The 3-word minimums are the boundary rule's cost: each Globex runbook's intro, "Support agents only.", is a chunk of its own that can't answer anything.

Then read the chunk that matters most, the recovery procedure, in full. All four steps should be in one chunk, in order, with the ACL from the manifest:

bash
docker compose exec db psql -U rag -d rag -c "SELECT chunk_index, allowed_roles, content FROM chunks WHERE document_id = (SELECT id FROM documents WHERE title = 'Runbook: stuck data exports') AND chunk_index = 2;"
output
 chunk_index | allowed_roles |                                                                 content                                                                  
-------------+---------------+------------------------------------------------------------------------------------------------------------------------------------------
           2 | {agent}       | Runbook: stuck data exports > Recovering a stuck export                                                                                 +
             |               |                                                                                                                                         +
             |               | 1. Find the export id from the customer's ticket and open it in the admin console.                                                      +
             |               | 2. Check the export worker queue depth. If it is above 500, page the data platform on-call before doing anything else.                  +
             |               | 3. Restart the export worker for the customer's region from the admin console. This releases the lock that ERR-7731 reports.            +
             |               | 4. Requeue the export. Each export can be requeued three times; the retry limit is internal and should not be mentioned to the customer.
(1 row)

Now test the schema's guarantees. Restrict a help article to agents and list its chunks, try to move one chunk to the other tenant, then insert a 3-dimensional vector:

bash
docker compose exec db psql -U rag -d rag \
  -c "UPDATE documents SET allowed_roles = '{agent}' WHERE title = 'Rotating API keys';" \
  -c "SELECT t.slug AS tenant, c.chunk_index, c.allowed_roles FROM chunks c JOIN documents d ON d.id = c.document_id JOIN tenants t ON t.id = c.tenant_id WHERE d.title = 'Rotating API keys' ORDER BY c.chunk_index;" \
  -c "UPDATE chunks SET tenant_id = (SELECT id FROM tenants WHERE slug = 'globex') WHERE chunk_index = 0 AND document_id = (SELECT id FROM documents WHERE title = 'Rotating API keys');" \
  -c "INSERT INTO chunks (document_id, tenant_id, allowed_roles, chunk_index, content, embedding) SELECT id, tenant_id, allowed_roles, 99, 'x', '[1,2,3]' FROM documents LIMIT 1;"
output
UPDATE 1
 tenant | chunk_index | allowed_roles 
--------+-------------+---------------
 acme   |           0 | {agent}
 acme   |           1 | {agent}
(2 rows)

ERROR:  insert or update on table "chunks" violates foreign key constraint "chunks_document_id_tenant_id_allowed_roles_fkey"
DETAIL:  Key (document_id, tenant_id, allowed_roles)=(51a7f61b-25f1-4da3-b0a7-be71b41d6219, 12d814d5-d60a-46b4-a7c0-2fb845fa5218, {agent}) is not present in table "documents".
ERROR:  expected 256 dimensions, not 3

The ACL change reached both chunks, the chunk couldn't be handed to another tenant, and the wrong-sized vector was refused. Run npm run ingest again to restore the article's ACL.

7. Step 5: what the HNSW index trades, and proof the query uses it

Without an index, pgvector compares the question with every row: exact nearest-neighbour search with perfect recall, and a cost that grows with the table. An approximate index trades some index recall, the share of the true nearest neighbours (from an exact scan) that the index search finds, for speed, which also means results can change once the index exists.

HNSW builds a multilayer graph of the vectors. It gives better query performance than pgvector's other index type, IVFFlat, at the price of slower builds and more RAM, and it can be created on an empty table. Three settings control the trade. m, the maximum number of connections per layer, defaults to 16; the pgvector README gives only its default, but by that definition each vector keeps up to m links per layer, so raising it should grow the index and its build time. ef_construction, the candidate list used while building the graph, defaults to 64; a higher value gives better recall but slows index builds and inserts. hnsw.ef_search, the candidate list at query time, defaults to 40; a higher value gives better recall in exchange for slower queries. Leave all three at their defaults until lesson 5's evals tell you retrieval falls short.

With 19 chunks the planner may prefer a plain scan, which is exact search. To prove the index can serve the exact query search.js sends, scripts/explain-search.sql plans it with sequential scans disabled for the session:

scripts/explain-search.sql
-- Plan the exact query src/search.js sends; GENERIC_PLAN keeps its $1/$2 placeholders.
-- The demo table is tiny, so disable sequential scans to see whether the index can serve it.
SET enable_seqscan = off;
EXPLAIN (GENERIC_PLAN, COSTS OFF)
SELECT c.id, c.document_id, d.title, c.chunk_index, c.distance, c.content
FROM (
  SELECT id, document_id, chunk_index, content, embedding <=> $1 AS distance
  FROM chunks
  ORDER BY embedding <=> $1
  LIMIT $2
) c
JOIN documents d ON d.id = c.document_id
ORDER BY c.distance;
bash
docker compose exec -T db psql -U rag -d rag < scripts/explain-search.sql
output
SET
                                   QUERY PLAN                                   
--------------------------------------------------------------------------------
 Nested Loop
   ->  Limit
         ->  Index Scan using chunks_embedding_hnsw on chunks
               Order By: (embedding <=> $1)
   ->  Index Scan using documents_id_tenant_id_allowed_roles_key on documents d
         Index Cond: (id = chunks.document_id)
(6 rows)

Look for Index Scan using chunks_embedding_hnsw with Order By: (embedding <=> $1).

8. Step 6: the /search endpoint, unprotected on purpose

src/search.js
import { pool, toVector } from './db.js';

/**
 * Top-k chunks by cosine distance (<=>; smaller is closer).
 *
 * UNPROTECTED: this searches every tenant's chunks. It exists to show the ranking on its
 * own; lesson 4 adds the tenant and role filter inside this query, plus row-level security.
 * Never deploy it as is.
 */
export async function searchChunks(provider, query, k = 5) {
  const [vector] = await provider.embed([query]);
  const { rows } = await pool.query(
    `SELECT c.id, c.document_id, d.title, c.chunk_index, c.distance, c.content
     FROM (
       SELECT id, document_id, chunk_index, content, embedding <=> $1 AS distance
       FROM chunks
       ORDER BY embedding <=> $1
       LIMIT $2
     ) c
     JOIN documents d ON d.id = c.document_id
     ORDER BY c.distance`,
    [toVector(vector), k],
  );
  return rows.map((r) => ({
    chunkId: Number(r.id),
    documentId: r.document_id,
    title: r.title,
    chunkIndex: r.chunk_index,
    distance: Number(Number(r.distance).toFixed(4)),
    content: r.content,
  }));
}

The inner query ranks and limits on chunks alone, which lets the planner use the index; the outer query joins titles onto just those k rows.

src/server.js
import Fastify from 'fastify';
import { config } from './config.js';
import { createEmbeddingProvider } from './embeddings/provider.js';
import { searchChunks } from './search.js';

export function buildServer(provider = createEmbeddingProvider()) {
  const app = Fastify({ logger: false });
  app.get('/search', {
    schema: {
      querystring: {
        type: 'object',
        required: ['q'],
        properties: {
          q: { type: 'string', minLength: 1, maxLength: 1000 },
          k: { type: 'integer', minimum: 1, maximum: 20, default: 5 },
        },
      },
    },
  }, async (req) => ({ query: req.query.q, results: await searchChunks(provider, req.query.q, req.query.k) }));
  return app;
}

if (import.meta.main) {
  const app = buildServer();
  await app.listen({ port: config.port });
  console.warn('WARNING: /search is unprotected and returns every tenant\'s chunks (fixed in lesson 4).');
  console.log(`listening on http://localhost:${config.port}`);
}

Fastify validates the query string, so an empty question is rejected before any embedding call. k, the number of chunks returned, defaults to five and caps at twenty: too few and the answer may sit at position six, too many and the prompt fills with near-misses.

9. Verify: search for a stuck export

Start the server in one terminal, with DATABASE_URL still exported:

bash
npm start
output
WARNING: /search is unprotected and returns every tenant's chunks (fixed in lesson 4).
listening on http://localhost:3000

Then query it from a second terminal:

bash
curl 'http://localhost:3000/search?q=my%20export%20has%20been%20stuck%20for%20hours&k=3'
response (ids shortened, content truncated)
{
  "query": "my export has been stuck for hours",
  "results": [
    {
      "chunkId": 11,
      "documentId": "f2381ab1…",
      "title": "Runbook: recovering stuck exports",
      "chunkIndex": 1,
      "distance": 0.4551,
      "content": "Runbook: recovering stuck exports > Symptoms\n\nA payroll expo…"
    },
    {
      "chunkId": 7,
      "documentId": "cf1e87d7…",
      "title": "Runbook: stuck data exports",
      "chunkIndex": 3,
      "distance": 0.5101,
      "content": "Runbook: stuck data exports > After recovery\n\nTell the custo…"
    },
    {
      "chunkId": 5,
      "documentId": "cf1e87d7…",
      "title": "Runbook: stuck data exports",
      "chunkIndex": 1,
      "distance": 0.5464,
      "content": "Runbook: stuck data exports > Symptoms\n\nAn export stays in t…"
    }
  ]
}

The distances are those of the fake embedder, which matches words, so treat them as relative, not as a quality score; a real model gives different numbers and better matches for paraphrases. What matters here is the order and the source of each chunk.

Read the top result's title, then check who owns it:

bash
docker compose exec db psql -U rag -d rag -c "SELECT t.slug AS tenant, d.title FROM documents d JOIN tenants t ON t.id = d.tenant_id WHERE d.title LIKE 'Runbook:%export%' ORDER BY t.slug;"
output
 tenant |               title               
--------+-----------------------------------
 acme   | Runbook: stuck data exports
 globex | Runbook: recovering stuck exports
(2 rows)

A user at Acme asked about a stuck export, and the closest chunk is Globex's runbook. All three results are agent-only runbooks, too, so an end user would have seen them just the same: the endpoint leaks across tenants and across roles. Nothing went wrong in the ranking: the words match, so the distance is small. The leak is the missing filter. Run the test suite, which asserts this leak on purpose alongside the schema, chunking, re-ingest and index checks. It migrates and re-ingests the database at DATABASE_URL, so it resets your data to the seeded documents:

bash
npm test
output (summary lines trimmed)
✔ chunks keep whole paragraphs and carry their heading path (1.3491ms)
✔ a section longer than maxWords splits with paragraph overlap (0.379643ms)
✔ every chunk carries its document tenant and ACL (117.547621ms)
✔ an ACL change on a document reaches its chunks in the same statement (13.376385ms)
✔ re-ingesting a document replaces its chunks instead of adding to them (77.87866ms)
✔ the top-k query can use the HNSW index (4.048078ms)
✔ search ranks the matching runbook first (2.671609ms)
✔ UNPROTECTED: search returns other tenants' chunks (lesson 4 fixes this) (3.758636ms)
✔ GET /search returns ranked chunks with distances (108.106865ms)
ℹ tests 9
ℹ pass 9
ℹ fail 0

10. Preview: why the filter has to go inside this query

You could keep this query and drop other tenants' chunks in application code after the top-k cut. That post-filtering fails twice: other tenants' text has already been read into your process, where a log line or an error report can expose it, and the caller gets fewer than k results, or none, when most of the nearest chunks belong to someone else. A WHERE clause on the rows being ranked removes both post-filtering problems, which is why every chunk already carries tenant_id and allowed_roles. It has a separate, smaller limit on an approximate index: pgvector applies the WHERE clause to the candidates the HNSW scan returns (hnsw.ef_search, 40 by default), so a selective filter can still return fewer than k rows. That result is safe, just starved, which is a different problem from post-filtering. Lesson 4 adds the filter, row-level security, and pgvector 0.8's iterative index scans, which keep scanning, up to a limit, when the filter leaves too few rows.

Filtering after LIMIT can only shrink the result set; lesson 4 moves the filter into the query.

11. Common problems

  • expected 256 dimensions, not N. The provider and the column disagree. Set EMBEDDINGS_DIMENSIONS to what your provider returns and run npm run migrate again, which recreates the tables, then re-ingest.
  • The plan shows a sequential scan even with enable_seqscan = off. Check for a missing LIMIT, an ORDER BY on a different expression, or an index built without vector_cosine_ops.
  • Results look random after changing models. Old chunks still hold the previous model's vectors, and distances between two models' vectors mean nothing. Re-ingest everything after any model change.
  • npm start exits silently. Your Node.js is older than 24.2, where import.meta.main doesn't exist; check node --version.

12. Exercise: add a document and check its chunks

Add a Globex help article, exports-help.md, visible to agents and end users, with one section longer than 120 words (several paragraphs under one ## heading). Register it in data/tenants/globex/manifest.json, whose format is a name and a list of documents:

data/tenants/globex/manifest.json (add the last entry)
{
  "name": "Globex Payroll",
  "documents": [
    { "file": "exports-runbook.md", "title": "Runbook: recovering stuck exports", "allowedRoles": ["agent"] },
    { "file": "billing-help.md", "title": "Invoices and billing", "allowedRoles": ["agent", "end_user"] },
    { "file": "sso-runbook.md", "title": "Runbook: SSO login failures", "allowedRoles": ["agent"] },
    { "file": "exports-help.md", "title": "Exporting payroll data", "allowedRoles": ["agent", "end_user"] }
  ]
}

Write the section as four paragraphs of 55, 45, 15 and 50 words, in that order (check each with wc -w), and re-run npm run ingest. Then read the new document's chunks in full: docker compose exec db psql -U rag -d rag -c "SELECT chunk_index, content FROM chunks WHERE document_id = (SELECT id FROM documents WHERE title = 'Exporting payroll data') ORDER BY chunk_index;". Hint: work out which paragraphs fit the 120-word limit, and which trailing ones fit the 25-word overlap budget.

Expected result: the first three paragraphs (115 words) fill the first chunk; the fourth doesn't fit, so the section becomes two chunks, each starting with the heading path, and the 15-word paragraph, which fits the overlap budget, appears at the end of the first and the start of the second. Every chunk has {agent,end_user}. Check the rest with two commands: curl 'http://localhost:3000/search?q=<a phrase from the article>&k=1' returns the new article first, and docker compose exec db psql -U rag -d rag -c "SELECT count(*) FROM chunks;" prints the same number before and after a second npm run ingest.

Common mistake: putting the tenant in the document's front matter. The job ignores it, by design; the tenant is the folder.

13. What lesson 3 builds on

You now have tenant documents stored as chunks with their tenant, ACL and embedding, an index that serves cosine distance, and a search that ranks well and filters nothing. In lesson 3, Generate grounded answers with citations, we pass the top chunks to a model and make it cite the chunks it used.

Key Takeaways

  • Start PostgreSQL with pgvector next to a Node.js project and confirm the extension version
  • Create a schema where every chunk carries its tenant, its document's ACL and an embedding sized to the provider
  • Chunk support documents with a size, overlap and boundary rule, and explain what each choice trades away
  • Put embedding generation behind a provider interface, and explain what cosine distance measures
  • Build an HNSW index with the operator class that matches cosine distance, and confirm with EXPLAIN that the query uses it
  • Call /search and read the top-k chunks, distances and source documents
  • Explain why access filtering has to happen inside the retrieval query, not after it

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.