Mental model
An IndexedDB vector store is a transactional object store for chunk text, source revisions, embedding-model IDs, and numeric vectors; IndexedDB does not supply nearest-neighbor search. For a small offline corpus, scan normalized vectors for cosine top-k, then attach only fresh, authorized chunks to the answer context.
Learning outcomes
- Design a record key that separates document revisions and embedding-model versions.
- Estimate exhaustive cosine-search work and memory from corpus size, embedding dimensions, and element width.
- Commit or retire a local corpus revision atomically, then label retrieval results whose freshness cannot be verified offline.
Theory
Store retrieval evidence, not just float arrays
IndexedDB provides named object stores, keys, indexes, and transactions. It stores values using structured serialization, so a Float32Array can be persisted with the metadata that explains its meaning. A vector without its embedding-model version or dimension is unsafe to compare: the same text embedded by a different model may occupy a different vector space even when both arrays have 768 numbers.
A useful chunk row includes a stable ID, collection snapshot revision, embedding-model ID, normalized vector, text, source ID, and source revision. The collection revision identifies one locally built retrieval snapshot. A read should query exactly that revision and model, then verify each source revision against the freshest known manifest before using a chunk. When the device is offline, a snapshot can remain useful, but it cannot prove that a remote source has not changed or been revoked since the last sync.
The Retrieval-Augmented Generation pattern retrieves passages before generation and conditions the answer on those passages. The local index is a retrieval aid, not the canonical source: keep source identifiers beside every chunk and return them with the text so the interface can show citations and freshness. Do not treat a high similarity score as a permission check or as proof that the passage entails the generated claim.
Cosine search and its cost
For unit-normalized embeddings, cosine similarity reduces to a dot product:
The query q and stored chunk vector v share dimension d; each component is a dimensionless model coordinate and the resulting score is dimensionless. Normalize both vectors using their L2 norms before scoring. A zero norm or a dimension mismatch should reject the query rather than quietly produce a plausible-looking rank.
With N stored rows, a flat scan performs approximately N × d multiply-adds and costs O(Nd). For N = 10,000 and d = 768, that is 7.68 million multiply-adds. Float32 values alone occupy 10,000 × 768 × 4 = 30,720,000 bytes, or about 29.3 MiB; text, keys, object wrappers, and structured-clone copies add to the peak. This is reasonable for a modest offline notebook, but it is a poor plan for millions of chunks. Larger corpora need a measured approximate-nearest-neighbor structure, often a graph or partition index, and that structure must be versioned and updated with its vectors.
Transactions, updates, and quota
Compute embeddings before opening a write transaction. IndexedDB transactions are scoped to stores and can commit or abort as a unit; they are not a place to await network requests or a long model inference. Stage new rows under a new revision in short batches while the old manifest remains active. After every batch commits, switch the collection's active-revision manifest in a final transaction. If staging fails, readers still follow the old pointer; incomplete unreferenced rows can be cleaned up later. Retain old rows through the switch, then garbage-collect revisions under a separate policy. Handle version upgrades carefully: another open tab can block a schema migration until it closes its older connection.
Browser storage is generally best-effort. navigator.storage.estimate() gives estimates rather than a reservation, and navigator.storage.persist() asks for stronger persistence but may be denied. Quota pressure can abort a transaction with a storage error or remove best-effort data later. Keep a server or user-selected export as the recoverable source, handle quota failure, and make rebuilding a local index an explicit path. A cached vector should never be the only copy of a user's original document.
The following example stores normalized rows and searches only the requested collection revision and model. It deliberately does not claim IndexedDB has a built-in vector index:
typescriptimport { openDB, type DBSchema } from "idb";type ChunkRow = { id: string; collectionId: string; revision: string; modelId: string; text: string; sourceId: string; sourceRevision: string; vector: Float32Array };type ActiveManifest = { collectionId: string; activeRevision: string; modelId: string; rowCount: number };interface VectorDB extends DBSchema {chunks: { key: [string, string, string]; value: ChunkRow; indexes: { bySnapshotModel: [string, string, string] } };manifests: { key: string; value: ActiveManifest };}const dbPromise = openDB<VectorDB>("local-rag", 1, {upgrade(db) {const chunks = db.createObjectStore("chunks", { keyPath: ["collectionId", "revision", "id"] });chunks.createIndex("bySnapshotModel", ["collectionId", "revision", "modelId"]);db.createObjectStore("manifests", { keyPath: "collectionId" });},});function unit(vector: Float32Array): Float32Array {let squared = 0;for (const value of vector) {if (!Number.isFinite(value)) throw new Error("embedding contains a non-finite value"); squared += value * value;}if (squared === 0) throw new Error("embedding has zero norm");const scale = 1 / Math.sqrt(squared);return Float32Array.from(vector, (value) => value * scale);}export async function storeRevision(collectionId: string, revision: string, modelId: string, rows: ChunkRow[]) {if (rows.some((row) => row.collectionId !== collectionId || row.revision !== revision || row.modelId !== modelId))throw new Error("every chunk must belong to the published snapshot");const normalized = rows.map((row) => ({ ...row, vector: unit(row.vector) }));const db = await dbPromise;for (let offset = 0; offset < normalized.length; offset += 250) {const tx = db.transaction("chunks", "readwrite"), batch = normalized.slice(offset, offset + 250);await Promise.all(batch.map((row) => tx.store.put(row)));await tx.done;}const publish = db.transaction("manifests", "readwrite");await publish.store.put({ collectionId, activeRevision: revision, modelId, rowCount: rows.length });await publish.done;}export async function topK(query: Float32Array, collectionId: string, queryModelId: string, limit = 5) {if (!Number.isInteger(limit) || limit < 1) throw new RangeError("limit must be positive");const q = unit(query), db = await dbPromise;const tx = db.transaction(["chunks", "manifests"], "readonly");const snapshot = await tx.objectStore("manifests").get(collectionId);if (!snapshot) { await tx.done; return []; }if (snapshot.modelId !== queryModelId) { await tx.done; throw new Error("query model differs from active corpus"); }const rows = await tx.objectStore("chunks").index("bySnapshotModel").getAll(IDBKeyRange.only([collectionId, snapshot.activeRevision, snapshot.modelId]),);await tx.done;return rows.filter((row) => row.vector.length === q.length).map((row) => ({ row, score: row.vector.reduce((sum, value, i) => sum + value * q[i], 0) })).sort((a, b) => b.score - a.score || a.row.id.localeCompare(b.row.id)).slice(0, limit);}
The read transaction returns candidates for ranking, not proof of current freshness. Before showing a result as current, compare sourceRevision to a manifest last received from the source service. If offline, present the last-checked time and the stale possibility. If a document is deleted or access is revoked, delete its local chunks on the next successful sync and avoid returning them once the revocation manifest arrives.
Trade-offs
A flat scan is simple to audit and rebuild, and can be fast enough when there are a few thousand short chunks. It reads candidate rows into application memory, so its peak can exceed the raw vector-byte calculation. A graph index such as HNSW can reduce comparisons but adds adjacency records, update bookkeeping, and a recall-versus-latency parameter. In the browser, that extra index is only worthwhile after testing recall on the actual corpus and measuring its storage and rebuild costs.
The device may be online when an embedding is created and offline when it is retrieved. Use the same model ID for query and corpus vectors, record collection and source revisions, and define an expiry or stale-content display policy. The retrieval score ranks semantic proximity; the generator still needs the original passage, citation metadata, and explicit source policy.
Failure modes and misconceptions
| Failure | Consequence | Recovery |
|---|---|---|
| Query vector uses a different model or dimension | Dot products rank unrelated coordinate spaces | Reject mismatched model IDs and dimensions |
| A read transaction scans an oversized corpus | getAll creates a large structured-clone working set | Bound the corpus, page candidates, or build a measured ANN index |
| Quota is reached during a revision write | The transaction aborts before the new snapshot is complete | Retain the previous revision and retry after storage cleanup |
| An offline passage was deleted remotely | Cached text can be stale or no longer permitted | Mark last-known freshness and apply the next revocation manifest |
IndexedDB does not guarantee vector similarity search, permanent retention, or remote freshness. Also avoid starting a transaction and then awaiting embedding or fetch work: browsers can make an idle transaction inactive before the next database request. Perform computation first, then issue the small set of storage operations and await tx.done to observe commit or abort.
Decision scenario
A field notebook stores 10,000 chunks with 768-dimensional float32 embeddings. The raw vectors need about 29.3 MiB and one query scans roughly 7.68 million coordinates; this is plausible for a measured offline collection but does not include text or temporary clones. The product receives a new collection revision while the user is online, but storage runs out halfway through the write. Keep the old revision active, show its last-checked time while offline, and publish the new revision only after its transaction completes. Add a graph index only if device benchmarks show the scan misses the latency or memory budget at the required recall.