FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Offline-First RAG with a Versioned Browser Index

Build an offline retrieval pipeline that versions source chunks and embeddings in IndexedDB, gates stale records, and grounds local generation in citations.

Freshness: current•14 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

An offline-first retrieval-augmented generation pipeline turns a versioned source snapshot into token-bounded passages, embeds them with a pinned model, and stores text, vectors, and provenance in the browser's IndexedDB database. A query is embedded by the same model, matched against only the selected snapshot, and supplied to a local generator with source identifiers so answers can cite what the device actually retrieved.

Learning outcomes

  • Calculate how token-window size and overlap determine passage count and raw vector storage for a corpus.
  • Build or inspect a retrieval record containing source ID, content hash, corpus revision, embedding revision, and vector dimensions.
  • Decide whether an offline answer is eligible by checking snapshot age, storage state, and citation coverage instead of treating a cached match as current truth.

Theory

RAG conditions a generator on retrieved text rather than relying on the model's parameters alone. In an offline browser, ingest and query must use the same embedding model revision, pooling rule, normalization, and vector dimension; otherwise query and document vectors no longer occupy the same space. Transformers.js exposes feature-extraction pipelines and can return mean-pooled, normalized vectors. For a normalized query vector q and normalized passage vector d_i, cosine retrieval reduces to a dimensionless dot product:

score⁡(q,di)=q⋅di∥q∥2∥di∥2\operatorname{score}(q,d_i)=\frac{q\cdot d_i}{\|q\|_2\|d_i\|_2}

Chunking must respect the generator context and the embedding tokenizer. Let T be a source's token count, C be tokens per chunk, O be overlap tokens, N_chunks be the number of windows, D be embedding dimensions, and S be bytes per vector component. For T greater than C, the window count and vector payload are:

Nchunks=⌈T−OC−O⌉,Bvectors=NchunksDSN_{\text{chunks}}=\left\lceil\frac{T-O}{C-O}\right\rceil,\qquad B_{\text{vectors}}=N_{\text{chunks}}DS

If T is no larger than C, use one window. For a 12,000-token runbook, C=320 and O=48 give ceil((12,000-48)/(320-48)) = 44 passages. A 384-dimensional float32 embedding uses 384 x 4 = 1,536 bytes, so the vectors alone occupy 44 x 1,536 = 67,584 bytes, or 66 KiB. Text, source metadata, IndexedDB indexes, structured-clone overhead, tokenizer files, and the local generator add to the actual storage requirement.

Each stored passage should carry a stable source ID, content hash, token start, corpus revision, embedding model revision, and text. Write a complete document's passage set in one short readwrite transaction so an aborted write does not expose half that document as indexed. Build large corpora in staged revisions: ingest chunks under a new revision, verify the count and checksums, then switch the active revision pointer only after every batch completes. IndexedDB transactions provide atomicity within a transaction; they do not protect data from browser eviction. The example stages one source at a time; its caller must wait for all source writes, check expected counts and hashes, then atomically publish the revision manifest. answerOffline receives that published revision so staged rows remain invisible until validation succeeds.

Version source and tokenizer
Chunk on embedding-model token boundaries
Store text, provenance, and normalized vectors
Filter revision and rank top passages
Generate locally with returned citation IDs
Conceptual teaching model synthesized from:rag-paper,hf-transformers-js-docs,w3c-indexeddb-spec,whatwg-storage-standard

Trade-offs

Design choiceBenefitCost
Short chunks with overlapImproves retrieval around a passage boundaryIncreases vector count and may duplicate context sent to the generator
Normalized float32 embeddingsMakes cosine ranking a dot product and keeps retrieval simpleUses 1,536 raw bytes for each 384-dimensional passage vector
IndexedDB local indexSupports structured, origin-scoped queries without a round tripTransactions, quota, and browser eviction need an explicit recovery plan
Local generationKeeps evidence and prompt on the device after model assets are cachedModel download, storage, and CPU or WebGPU time compete with application resources

For a small corpus, a linear scan across N vectors with D dimensions costs O(ND) multiply-adds and is easy to audit. At 50,000 passages and 384 dimensions, a scan touches about 19.2 million vector components per query. Larger indexes may need a compact approximate-nearest-neighbor structure, but graph or quantized indexes introduce build cost, recall loss, and more complicated snapshot migration.

StorageManager.estimate() returns an estimate, not a reservation. A call to StorageManager.persist() can be denied, so offline readiness should be shown only after the model files and a complete index revision are present. Keep a rebuildable manifest and make enough quota headroom for a replacement snapshot before deleting the active one.

Embedding and generation tokenizers can count the same passage differently. After selecting the top four chunks, retokenize the complete question and evidence with the generator tokenizer. The sample enforces an application budget of 4,096 context tokens, reserving 128 for chat framing and 160 for generated output.

Failure modes and misconceptions

A stale corpus is the most dangerous offline failure. If a document is revoked while a device is disconnected, the browser cannot know about that change. Define an offline lease or a last-verified time; after it expires, either label the answer as an old snapshot or refuse to answer until sync. On reconnect, apply deletion tombstones before promoting a new revision and remove the revoked chunks and cached model artifacts required by policy.

A vector from a different embedding revision or dimension can produce plausible but meaningless similarity scores. Refuse to mix incompatible vectors: check corpus revision, embedding model revision, dimensions, and normalization before ranking. A failed IndexedDB transaction must leave the previous active revision intact; a quota error while writing the new revision must not turn a partial build into the current index.

A successful IndexedDB write does not guarantee permanent offline availability. Browsers may evict best-effort storage, users can clear site data, and persisted storage is a permission decision rather than a universal guarantee. Recheck expected model and index files at startup, surface a missing-offline-data state, and use StorageManager estimates before ingest. Finally, citations identify retrieved passages, but they do not prove that each generated claim is supported; evaluate citation precision and provide the source text for inspection.

Decision scenario

A field-support laptop has been offline for two days with corpus revision r41. Before it disconnected, r42 removed a safety procedure that the device user is no longer authorized to see. A query finds the passage in r41 with a strong cosine score, but the offline lease expired yesterday. Do not present the hit as current guidance. Show that the only available index is stale and require a sync or an approved exception; when the device reconnects, apply the r42 tombstone, verify the new revision, and only then reactivate offline answers.

Implementation: index, retrieve, and answer locally

typescript
import { pipeline } from "@huggingface/transformers";
const DB = "offline-rag-v1", STORE = "passages";
const EMBED_ID = "onnx-community/all-MiniLM-L6-v2", GENERATE_ID = "onnx-community/Qwen2.5-0.5B-Instruct";
const MAX_PROMPT_TOKENS = 4096;
let embedder, generator;
const openIndex = () => new Promise((resolve, reject) => {
const request = indexedDB.open(DB, 1); request.onupgradeneeded = () => { const store = request.result.createObjectStore(STORE, { keyPath: "key" }); store.createIndex("revision", "revision"); };
request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);
});
async function embed(text) {
embedder ??= await pipeline("feature-extraction", EMBED_ID); const output = await embedder(text, { pooling: "mean", normalize: true });
return Float32Array.from(output.data);
}
function chunkText(text) {
const ids = embedder.tokenizer.encode(text, { add_special_tokens: false }), chunks = [];
for (let start = 0; start < ids.length; start += 272) {
chunks.push({ start, text: embedder.tokenizer.decode(ids.slice(start, start + 320), { skip_special_tokens: true }) });
if (start + 320 >= ids.length) break;
}
return chunks;
}
async function indexDocument(source, revision) {
embedder ??= await pipeline("feature-extraction", EMBED_ID);
const chunks = chunkText(source.text);
const rows = [];
for (const chunk of chunks) {
const vector = await embed(chunk.text);
rows.push({ key: revision + ":" + source.id + ":" + chunk.start, revision, sourceId: source.id, contentHash: source.hash, embeddingRevision: EMBED_ID, tokenStart: chunk.start, text: chunk.text, vector });
}
const db = await openIndex();
try {
await new Promise((resolve, reject) => { const tx = db.transaction(STORE, "readwrite"); rows.forEach((row) => tx.objectStore(STORE).put(row)); tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); });
} finally { db.close(); }
// Caller verifies every source, then atomically publishes the revision manifest.
return rows.length;
}
async function answerOffline(question, activeRevision, leaseExpiresAt) {
if (Date.now() > leaseExpiresAt) throw new Error("Offline content lease expired; sync before answering");
const query = await embed(question), db = await openIndex();
const rows = await new Promise((resolve, reject) => { const req = db.transaction(STORE, "readonly").objectStore(STORE).index("revision").getAll(activeRevision); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); });
db.close();
const hits = rows.filter((row) => row.embeddingRevision === EMBED_ID).map((row) => {
if (row.vector.length !== query.length) throw new Error("Embedding dimensions differ");
return { ...row, score: row.vector.reduce((sum, value, i) => sum + value * query[i], 0) };
}).sort((a, b) => b.score - a.score).slice(0, 4);
if (!hits.length) throw new Error("No passages exist for this corpus revision");
generator ??= await pipeline("text-generation", GENERATE_ID, { dtype: "q4" });
const evidence = hits.map((hit) => "[" + hit.sourceId + "#" + hit.tokenStart + "] " + hit.text).join("\n"), prompt = question + "\n\n" + evidence;
if (generator.tokenizer.encode(prompt, { add_special_tokens: true }).length > MAX_PROMPT_TOKENS - 288) throw new RangeError("Retrieved evidence exceeds local context budget");
const conversation = [{ role: "system", content: "Answer only from these passages and cite their IDs; say when evidence is missing." }, { role: "user", content: prompt }];
const result = await generator(conversation, { max_new_tokens: 160, do_sample: false }), generated = result[0]?.generated_text ?? [];
return { answer: generated.at(-1)?.content ?? "", revision: activeRevision, citations: hits.map((hit) => hit.sourceId + "#" + hit.tokenStart) };
}
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next