Antigravity × Cloudflare Vectorize: Build a Production RAG Pipeline That Runs at the Edge
A production guide to building a RAG pipeline on Cloudflare Vectorize using Antigravity. Chunking, hybrid search, cost design, and observability—covered at a depth a solo developer can actually ship.
"I want to ship vector search to production, but I don't know where to start." If you're a solo developer building a SaaS or a knowledge base, this is a wall you'll hit. When I rebuilt a small Q&A bot on Cloudflare Workers using Vectorize, the first few days were dominated by the realization that something as small as chunk length had an outsized effect on retrieval quality.
Cloudflare Vectorize became generally available in September 2024. It is an edge-optimized vector database integrated with Workers AI. Unlike Pinecone or Weaviate, it lives inside Cloudflare's control plane, which means your Worker and your vector index can run in the same region. Combined with a generous free tier and pay-as-you-go pricing, it's one of the easier vector databases for an indie developer to put into production.
What follows is the path I actually took: letting Antigravity's agents scaffold a RAG pipeline quickly, then growing it into something I could run in production—including the traps I personally fell into along the way. By the end, you'll have ingested your own documents, measured retrieval quality, understood your cost and latency profile, and deployed it all on Cloudflare Workers.
Why Cloudflare Vectorize? The Real Value of Running at the Edge
Vector database options have exploded—Pinecone, Weaviate, Qdrant, Chroma, and many more. Vectorize earns its place by living on the same infrastructure as Workers.
When you call Vectorize from Workers, you connect via a binding rather than an HTTP API. Your Worker doesn't need to hold an API token, and the round trip to a vector database sitting in some other cloud stays inside Cloudflare's network instead. How much faster that is depends on region and setup, so I won't put a number here. If you're weighing a migration, wrap query() with Date.now() in both your current setup and Vectorize, run each 100 times from your own Worker, and decide from that.
It's not a silver bullet. Vectorize caps the number of vectors per index (raised to 10 million in a January 2026 update; check the official Limits page for the current value), limits how many metadata indexes you can create and how large each vector's metadata can be, and doesn't expose the low-level knobs (PQ quantization, IVF tuning) that some workloads demand. If you're trying to squeeze out every last millisecond of accuracy, or running a hundreds-of-millions vector research dataset, a Pinecone Pod or a self-hosted Qdrant will serve you better. Vectorize shines for the specific case where a solo developer wants 100K to a few million vectors served entirely from the Cloudflare stack.
Site search and "related articles" recommendations are where Vectorize fits most naturally. Keeping everything on the same bill and the same dashboard as your Workers, with one fewer external API to depend on, is a real operational win. (As of November 2026, the official Pricing page bills Vectorize by queried and stored vector dimensions.)
A Working RAG in Five Minutes: Scaffold It with Antigravity
Let's get concrete. Open your project in Antigravity's Manager Surface, and prompt the AI agent like this:
Scaffold a RAG pipeline on Cloudflare Workers + Vectorize.Requirements:- TypeScript with Hono- /ingest endpoint that accepts Markdown, chunks it, embeds with Workers AI, and upserts into Vectorize- /query endpoint that takes a question, runs vector search, and passes the top 5 results as context to a Workers AI text-generation model- Generate wrangler.toml as well- Embed with the multilingual @cf/baai/bge-m3 model- Use bindings: VECTORIZE_INDEX, AI
Once Antigravity sets up the project structure, read through the generated code carefully. Don't just run the scaffold—you'll get blocked later when you try to swap the chunker or the embedding model. Spend the first few hours making sure every piece is at a granularity you understand.
Here's the core of src/index.ts, refactored from the version I run in production into something minimal:
// src/index.tsimport { Hono } from "hono";type Bindings = { AI: Ai; VECTORIZE_INDEX: VectorizeIndex; DB: D1Database; // FTS5, used by hybrid search later KV: KVNamespace; // chunk counts, body hashes, and the answer cache};const app = new Hono<{ Bindings: Bindings }>();// Chunk text on paragraph boundaries, targeting ~800 charsfunction chunk(text: string, target = 800, overlap = 120): string[] { const blocks = text.split(/\n{2,}/); const out: string[] = []; let buf = ""; for (const block of blocks) { if ((buf + "\n\n" + block).length > target && buf) { out.push(buf.trim()); const tail = buf.slice(Math.max(0, buf.length - overlap)); buf = tail + "\n\n" + block; } else { buf = buf ? `${buf}\n\n${block}` : block; } } if (buf.trim()) out.push(buf.trim()); return out;}app.post("/ingest", async (c) => { const { docId, title, body } = await c.req.json<{ docId: string; title: string; body: string; }>(); const chunks = chunk(body); // Firing every chunk at once with Promise.all will blow past the Worker's // concurrent subrequest limit. Batches of 8, run sequentially, proved the // most stable setup in my testing. const vectors: VectorizeVector[] = []; const BATCH = 8; for (let start = 0; start < chunks.length; start += BATCH) { const slice = chunks.slice(start, start + BATCH); const embedded = await Promise.all( slice.map(async (text, offset) => { const i = start + offset; const { data } = await c.env.AI.run("@cf/baai/bge-m3", { text: [text], }); return { id: `${docId}#${i}`, values: data[0], metadata: { docId, title, chunkIndex: i, text }, }; }) ); vectors.push(...embedded); } // upsert accepts up to 1,000 vectors per call await c.env.VECTORIZE_INDEX.upsert(vectors); return c.json({ ok: true, chunks: chunks.length });});app.post("/query", async (c) => { const { question, topK = 5 } = await c.req.json<{ question: string; topK?: number; }>(); const { data } = await c.env.AI.run("@cf/baai/bge-m3", { text: [question], }); const result = await c.env.VECTORIZE_INDEX.query(data[0], { topK, returnMetadata: "all", }); const context = result.matches .map((m, i) => `[doc ${i + 1}: ${m.metadata?.title}]\n${m.metadata?.text}`) .join("\n\n---\n\n"); const answer = await c.env.AI.run("@cf/meta/llama-3.1-8b-instruct", { messages: [ { role: "system", content: "Answer only from the provided documents. If the answer isn't there, say 'I don't know.'", }, { role: "user", content: `# Question\n${question}\n\n# Reference Documents\n${context}`, }, ], }); // text-generation returns { response }. Return the object as-is and your UI prints [object Object] return c.json({ answer: (answer as { response?: string }).response ?? "", sources: result.matches.map((m) => ({ id: m.id, score: m.score, title: m.metadata?.title })), });});export default app;
Declare your bindings in wrangler.toml:
# wrangler.tomlname = "vectorize-rag"main = "src/index.ts"compatibility_date = "2026-04-01"[ai]binding = "AI"[[vectorize]]binding = "VECTORIZE_INDEX"index_name = "blog-knowledge"# D1 (FTS5) and KV used later. Replace the ids with the output of wrangler d1 create / wrangler kv namespace create[[d1_databases]]binding = "DB"database_name = "rag-fts"database_id = "YOUR_D1_DATABASE_ID"[[kv_namespaces]]binding = "KV"id = "YOUR_KV_NAMESPACE_ID"
Create the index from the CLI:
# 1024 dimensions, matching the output of bge-m3.# This must equal your embedding model's dimension exactly.wrangler vectorize create blog-knowledge --dimensions=1024 --metric=cosine# Create metadata indexes ahead of timewrangler vectorize create-metadata-index blog-knowledge --property-name=docId --type=stringwrangler vectorize create-metadata-index blog-knowledge --property-name=title --type=string
Run wrangler dev and you have a working RAG. The expected behavior: a single 5,000-character article ingests as 6–8 chunks, and /query returns 5 high-similarity matches.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Go from 'I don't know how to use Vectorize' to having a production-grade RAG pipeline running on Cloudflare Workers, scaffolded with Antigravity
✦You'll learn the hybrid search, reranking, and metadata filtering techniques you need to ship search quality you won't be embarrassed by
✦You can now apply the cold-start mitigation, token cost controls, and observability patterns specific to edge-deployed RAG to your own product
✦You get ahead of the three things that break a scaffold first in production — dimension mismatch, concurrent subrequest limits, and the reranker response shape — with the actual error messages for each
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Ingestion Pipeline: Chunking, Embeddings, and Metadata
The minimal version works, but it's not production. The single biggest factor in retrieval quality is chunking strategy.
I started with fixed 1,000-character chunks. The result: chunks that broke mid-heading, with "title-only fragments" frequently ranking near the top. After much iteration, I settled on a Markdown-aware chunker that respects heading hierarchy and aims for 600–900 chars per chunk on paragraph boundaries.
After switching to this chunker, the "title-only fragment at the top of the results" problem all but disappeared. The reason is unglamorous: keeping the heading at the top of each chunk preserves enough context for the embedding to reflect what the section is actually about. Don't judge the change by feel, though. Compare recall@5 on the eval set described later (questions paired with expected doc IDs) before and after.
Choosing an Embedding Model
The main embedding models available on Workers AI:
@cf/baai/bge-small-en-v1.5 (384 dim, English)
@cf/baai/bge-base-en-v1.5 (768 dim, English)
@cf/baai/bge-large-en-v1.5 (1024 dim, English)
@cf/baai/bge-m3 (1024 dim, multilingual)
If you're indexing Japanese content, bge-m3 is the only sensible choice. I lost a full day in my early days trying to debug poor retrieval on Japanese queries before realizing I was running an English-only model. Lesson: check the language coverage of your embedding model first.
That said, bge-m3 is 1024-dim, which directly increases Vectorize storage costs and query latency. For predominantly English content, bge-base-en-v1.5 (768-dim) is more economical.
Metadata Design You'll Be Glad You Made
The metadata you attach at upsert time becomes the lever you pull later for filtering. The fields I wish I'd added from day one:
docId: stable ID of the source document (essential for updates and deletes)
title: for display
category / tag: for filtered search
lang: to scope queries by language
updatedAt (unix timestamp): for re-indexing decisions
text: the chunk body itself (Vectorize returns only vector IDs, scores, and the metadata you stored, so the body has to live in metadata. Metadata has a per-vector size limit, so for long chunks keep the body in D1 and store only the ID here)
You must create metadata indexes ahead of time with wrangler vectorize create-metadata-index. Adding them later doesn't backfill existing vectors, so be exhaustive before going to production.
Three Places the Scaffold Breaks First in Production: Dimensions, Concurrency, Response Shape
Having just spent a section on chunking, I should admit that the things which actually cost me time came earlier than retrieval quality. Three of them. All are documented, and none of them are visible the moment you run the scaffold. Here's what each one looks like when it hits you, in the hope that it saves someone the same afternoon.
1. Dimension mismatch: "somehow only upsert fails"
This was the first one. I created the index at 768 dimensions and embedded with bge-small-en-v1.5. Embedding generation in /query worked fine; only the upsert in /ingest failed:
VectorizeError: vector dimension mismatch:index expects 768 dimensions, but got 384
The cause is mundane: bge-small-en-v1.5 outputs 384 dimensions. I had assumed "small" meant roughly half of something bigger and created the index with --dimensions=768. Because the failure surfaces at upsert rather than at embedding time, my first instinct was to inspect the chunk contents — which is exactly why it took as long as it did.
You cannot infer a Workers AI model's output dimension from its name. Measuring it once, before you create anything, is worth the thirty seconds:
# Probe the embedding dimension before creating the indexcurl -s -X POST \ "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/ai/run/@cf/baai/bge-m3" \ -H "Authorization: Bearer $CF_API_TOKEN" \ -d '{"text":["dimension probe"]}' | jq '.result.data[0] | length'# => 1024
That one line removes an entire index-rebuild round trip. This article standardizes the scaffold on bge-m3 (1024 dimensions) because any pipeline handling non-English content ends up there anyway. An English-only corpus can start on bge-base-en-v1.5 (768 dimensions) — but note that an index's dimension cannot be changed after creation. When you do have to rebuild, the painful part isn't the vectors themselves; it's paying Workers AI to re-embed the entire corpus.
2. Concurrency: Promise.all bites at around 30 chunks
Embedding every chunk via chunks.map() + Promise.all reads naturally and works fine for ten chunks. Mine broke when a long article pushed past forty:
Error: Too many API requests by single worker invocation.
That is the exact message I got. Workers cap both the number of subrequests and simultaneous connections per invocation (values per plan are on the official Limits page), and Promise.all spends that budget all at once. Worse, short articles never reproduce it, so the symptom presents as "ingestion fails for this one specific document" — the hardest kind of failure to read.
The fix is the one now in /ingest above: split into batches of roughly eight and run them sequentially. It takes a bit longer than going fully parallel, but ingestion isn't something a user sits and waits on. Paying a few seconds to actually finish is the right trade for an ingestion job. There's nothing special about eight, either. Feed in your longest document and find the batch size that doesn't fail.
The upsert call itself accepts up to 1,000 vectors, so batching the embeddings while keeping a single upsert at the end works fine.
3. Reranker response shape: id is an index into what you sent
The third one is smaller and, because it fails silently, more annoying. Workers AI's @cf/baai/bge-reranker-base returns { response: [{ id, score }] }, where id is the index into the contexts array you passed in — not your chunk ID.
I had written it as index, so candidates[r.index] evaluated to undefined and the entire reranking step was quietly producing garbage. It never threw. You get back an array that looks reordered, and nothing tells you otherwise until you read the results yourself.
// ✅ Correct: id indexes into contextsconst ranked = result.response.map((r: { id: number; score: number }) => ({ id: candidates[r.id].id, score: r.score,}));// ❌ Common mistake: there is no `index` property// candidates[r.index] is always undefined
Defects that fail silently instead of throwing are exactly what the evaluation suite below earns its keep on. I only caught this one because recall@5 dropped unnaturally against the previous day — not by reading the code.
Lifting Search Quality to Production: Hybrid Search and Reranking
Pure vector search struggles with proper nouns and version numbers. A query like "Antigravity 1.20" embeds near a lot of vaguely-related content, and unrelated articles bubble up.
I solved this with hybrid search (vector + full-text) + reranking in two stages.
Hybrid Search with D1 as a Full-Text Index
// src/lib/hybrid-search.ts// Wrap the whole input as a single phrase and double any inner quotesexport function toFtsPhrase(q: string): string { return '"' + q.replace(/"/g, '""') + '"';}type HybridResult = { id: string; score: number; source: "vector" | "fts" | "both"; text: string; title: string;};export async function hybridSearch( env: { VECTORIZE_INDEX: VectorizeIndex; DB: D1Database; AI: Ai }, query: string, topK = 10): Promise<HybridResult[]> { // Run vector and FTS in parallel to minimize wall-clock const [vectorRes, ftsRes] = await Promise.all([ (async () => { const { data } = await env.AI.run("@cf/baai/bge-m3", { text: [query] }); return env.VECTORIZE_INDEX.query(data[0], { topK, returnMetadata: "all", }); })(), env.DB.prepare( `SELECT id, title, text, rank FROM chunks_fts WHERE chunks_fts MATCH ?1 ORDER BY rank LIMIT ?2` ) // Passing raw user input to MATCH lets "-" and quotes be parsed as FTS5 syntax and throw .bind(toFtsPhrase(query), topK) .all<{ id: string; title: string; text: string; rank: number }>(), ]); // Reciprocal Rank Fusion (RRF) blends the two. Ranks start at 1, hence i + 1 const map = new Map<string, HybridResult>(); vectorRes.matches.forEach((m, i) => { map.set(m.id, { id: m.id, score: 1 / (60 + i + 1), source: "vector", text: String(m.metadata?.text ?? ""), title: String(m.metadata?.title ?? ""), }); }); (ftsRes.results ?? []).forEach((r, i) => { const existing = map.get(r.id); const ftsScore = 1 / (60 + i + 1); if (existing) { existing.score += ftsScore; existing.source = "both"; } else { map.set(r.id, { id: r.id, score: ftsScore, source: "fts", text: r.text, title: r.title, }); } }); return Array.from(map.values()).sort((a, b) => b.score - a.score);}
On the D1 side, set up an FTS5 virtual table:
-- migrations/0001_chunks_fts.sql-- Use trigram if any content is Japanese. unicode61 splits on whitespace and can't find words inside Japanese sentencesCREATE VIRTUAL TABLE chunks_fts USING fts5( id UNINDEXED, title, text, tokenize='trigram');
Reciprocal Rank Fusion is simple but powerful. It merges results from vector search and FTS using only their ranks, so you don't have to normalize two scoring systems with very different magnitudes. There is one precondition: the id in FTS and the Vectorize ID must be the same ${docId}#${i}. If they differ, nothing ever counts as "found by both," and RRF degenerates into a plain interleave.
Re-Rank the Top N with Workers AI Reranker
Pull a wider net (top 20) with hybrid search, then have a reranker decide which are actually most relevant.
// src/lib/rerank.tsexport async function rerank( env: { AI: Ai }, query: string, candidates: { id: string; text: string }[]): Promise<{ id: string; score: number }[]> { const result = await env.AI.run("@cf/baai/bge-reranker-base", { query, contexts: candidates.map((c) => ({ text: c.text })), }); // response[].id is the *index into the contexts array you sent*, // not your own chunk ID. (I got this wrong once — more on that below.) return result.response .map((r: { id: number; score: number }) => ({ id: candidates[r.id].id, score: r.score, })) .sort((a, b) => b.score - a.score);}
Adding a reranker visibly improved the factual quality of LLM answers in my system. Before reranking, the LLM occasionally "filled in" facts that weren't in the documents at all. After reranking, those hallucinations almost vanished.
Cost Design: Make Tokens, Calls, and Storage Visible
Vectorize cost has three axes:
Queries (vector × topK)
Stored vectors (GB/month)
Workers AI calls (embeddings, LLM, and reranker each metered separately)
You can start small within the free tier and pay-as-you-go pricing. Of the three, the one that balloons if you're not careful is Workers AI. Embeddings, the reranker, and generation are each billed separately, so the first thing to know is how many model calls a single question actually triggers.
Analytics Engine is Cloudflare's pay-as-you-go event store; how much you can write for free depends on your Workers plan (as of November 2026, see the official Pricing page). I thread UsageLogger through every endpoint and surface a usage summary in the response headers during development.
Three Cost Wins That Actually Mattered
The optimizations that moved the needle in my deployment:
Cache layer: Hash the query, look it up in KV before doing anything else. The more uniformly people phrase a question (FAQ-style), the more often it hits
Early return on weak matches: If the top vector score falls below a threshold, return "no match" without calling the LLM. The right threshold depends on model and corpus, so set it by counting, on your eval set, how many answerable questions it would have thrown away
Model downgrade: Route easy questions to llama-3.2-3b-instruct instead of llama-3.1-8b-instruct
If you add only one, add the cache: it stops you from paying for both embedding and generation on every repeat question. The catch is that stale answers survive for the TTL after you update an article, so for a fast-changing corpus either shorten the TTL or change the key prefix on every reindex. The implementation is trivial:
// src/lib/hash.ts// Workers don't ship Node's crypto by default, so use Web Crypto here.// (If you want node:crypto, add the nodejs_compat flag to wrangler.toml.)export async function sha256(input: string): Promise<string> { const buf = await crypto.subtle.digest( "SHA-256", new TextEncoder().encode(input) ); return Array.from(new Uint8Array(buf)) .map((b) => b.toString(16).padStart(2, "0")) .join("");}// src/lib/query-cache.tsimport { sha256 } from "./hash";export async function getCachedAnswer( kv: KVNamespace, query: string): Promise<string | null> { return await kv.get(`q:${(await sha256(query)).slice(0, 32)}`);}export async function setCachedAnswer( kv: KVNamespace, query: string, answer: string, ttlSec = 86400) { await kv.put(`q:${(await sha256(query)).slice(0, 32)}`, answer, { expirationTtl: ttlSec, });}
Observability: Logs, Metrics, and Surfacing Failure Modes
What matters most in production is being able to identify the cause when accuracy drops, costs spike, or latency creeps up. If you want to keep everything inside Cloudflare, this is the stack I recommend:
Tail Workers: forward failed requests to a separate Worker for long-term storage and Slack alerts
Monitoring the distribution of reranker scores is what lets you catch quality regressions early. I once bulk-updated some articles and the chunk boundaries shifted; the distribution of the reranker's top scores visibly shifted downward overnight. Without dashboards I'd have only learned about it from a user complaint days later.
// src/lib/health-check.tsexport async function searchHealthCheck(env: Bindings) { const goldenQueries = [ { q: "How do I get started with Antigravity?", expectedDocId: "antigravity-getting-started" }, { q: "What does Cloudflare Vectorize cost?", expectedDocId: "antigravity-cloudflare-vectorize-rag-production-guide" }, ]; const failures: { q: string; got: string[] }[] = []; for (const { q, expectedDocId } of goldenQueries) { const results = await hybridSearch(env, q, 5); const ids = results.map((r) => r.id.split("#")[0]); if (!ids.includes(expectedDocId)) failures.push({ q, got: ids }); } return { passed: failures.length === 0, failures };}
Run this from a Cron Trigger every hour and post failures to Slack. You'll catch regressions long before users do.
Check the Fusion Locally: A Small Test for RRF and FTS5
The scariest thing about hybrid search is the same thing that bit me with the reranker: it fails quietly. An RRF rank that's off by one, or raw user input fed straight into FTS5, still produces plausible-looking results as long as you only try short queries. Before anything goes onto a Worker, I pull out just the fusion and the input shaping and pin them down with Node.js's built-in test runner. It needs no deploy and no Cloudflare account, which makes it a good first test to run right after Antigravity hands you the scaffold.
// test/rag.test.mjs — node --test test/rag.test.mjsimport { test } from "node:test";import assert from "node:assert/strict";// RRF: blend two result lists using rank only (ranks start at 1)export function rrf(lists, k = 60) { const score = new Map(); for (const list of lists) { list.forEach((id, i) => score.set(id, (score.get(id) ?? 0) + 1 / (k + i + 1))); } return [...score.entries()] .sort((a, b) => b[1] - a[1]) .map(([id, s]) => ({ id, s: +s.toFixed(5) }));}// Wrap user input as a single phrase before handing it to FTS5 MATCHexport function toFtsPhrase(q) { return '"' + q.replace(/"/g, '""') + '"';}test("a document found by both lists rises to the top", () => { const r = rrf([["a#0", "b#1", "c#0"], ["c#0", "d#2"]]); console.log(r); assert.equal(r[0].id, "c#0");});test("rank 3 + rank 1 beats a single rank 1", () => { const r = rrf([["x#0", "y#0", "z#0"], ["z#0"]]); assert.equal(r[0].id, "z#0");});test("input with symbols is shaped so FTS5 won't throw a syntax error", () => { assert.equal(toFtsPhrase('Antigravity "1.20" -beta'), '"Antigravity ""1.20"" -beta"');});
Output on Node.js 22.23:
# [# { id: 'c#0', s: 0.03227 },# { id: 'a#0', s: 0.01639 },# { id: 'b#1', s: 0.01613 },# { id: 'd#2', s: 0.01613 }# ]ok 1 - a document found by both lists rises to the topok 2 - rank 3 + rank 1 beats a single rank 1ok 3 - input with symbols is shaped so FTS5 won't throw a syntax error# tests 3# pass 3# fail 0
c#0 was third on the vector side and first on the FTS side, and the combined score puts it on top. That's exactly what you want RRF to do.
You can also check tokenizer behavior with local SQLite before touching D1. D1 is SQLite-compatible, so FTS5 behaves the same way locally (the run below uses Python's standard sqlite3 on SQLite 3.53; the sample rows are Japanese because that's where the tokenizers differ).
import sqlite3db = sqlite3.connect(":memory:")db.execute("CREATE VIRTUAL TABLE t USING fts5(id UNINDEXED, text, tokenize='trigram')")db.execute("CREATE VIRTUAL TABLE u USING fts5(id UNINDEXED, text, tokenize='unicode61 remove_diacritics 2')")rows = [("a#0", "Vectorize のメタデータインデックスを作る"), ("b#0", "埋め込みモデルの次元を実測する")]for tb in ("t", "u"): db.executemany(f"INSERT INTO {tb} VALUES (?, ?)", rows)for q in ['"メタデータ"', '"次元"', '"インデックス"']: for tb in ("t", "u"): print(tb, q, db.execute(f"SELECT id FROM {tb} WHERE {tb} MATCH ?", (q,)).fetchall())db.execute("SELECT id FROM t WHERE t MATCH ?", ('Antigravity "1.20" -beta',)).fetchall()
t "メタデータ" [('a#0',)]u "メタデータ" []t "次元" []u "次元" []t "インデックス" [('a#0',)]u "インデックス" []sqlite3.OperationalError: no such column: beta
Three things fall out of this. unicode61 can't find a single word inside a Japanese sentence. Even trigram can't find the two-character 次元. And raw input passed to MATCH throws, because -beta is parsed as a column reference. That last one is the kind of defect that returns a 500 the first time a real user types a symbol, and it's the whole reason toFtsPhrase exists.
The line I drew here is simple: anything that doesn't throw can only be protected by a test or an eval set. The code that looks most obviously correct on a read-through is exactly what goes in.
Common Pitfalls
You can read this entire article, feel prepared, and still trip on something. Here are the traps I (and other indie developers I know) have actually fallen into, with fixes.
1. Forgetting to Create Metadata Indexes
returnMetadata: "all" lets you read metadata from results, but using metadata in a filter clause requires that you create a metadata index up front. I missed this initially: my "filtered" queries appeared to ignore the filter entirely. Half a day was lost to it. The Vectorize docs are explicit, but it's an easy thing to glide past.
If you decide to swap embedding models because accuracy isn't great, you can't keep using the old index. Different dimensions can't even upsert; even with the same dimension, the vector spaces are different and similarity becomes meaningless. Always rebuild the index when you change the embedding model. I run a parallel index with a _v2 suffix, then flip the binding on cutover day, like a DNS change.
3. Regretting Your Chunk ID Scheme
I started with simple IDs like ${docId}_${i}. The problem: every time a document was updated, I needed to delete the old chunks before upserting new ones—but Vectorize's deleteByIds requires exact ID matches, so I needed to know how many old chunks existed. I now store the current chunk count in KV under doc:${docId}:chunkCount, and on update I bulk-delete the old range first.
async function reindexDoc(env: Bindings, docId: string, body: string) { const oldCount = parseInt((await env.KV.get(`doc:${docId}:chunkCount`)) ?? "0"); if (oldCount > 0) { const ids = Array.from({ length: oldCount }, (_, i) => `${docId}#${i}`); await env.VECTORIZE_INDEX.deleteByIds(ids); } const chunks = chunk(body); // embedAll is the batched embedding loop from /ingest, extracted into a function const vectors = await embedAll(env, chunks, docId); await env.VECTORIZE_INDEX.upsert(vectors); await env.KV.put(`doc:${docId}:chunkCount`, String(chunks.length));}
4. Embedding Cold Starts Are Real
Sometimes only the first request after a quiet stretch is slow. Workers AI models run on shared infrastructure, and I haven't been able to confirm how much a periodic ping from my side actually keeps anything warm. So I limit it to the health check described below, which hits /health on a Cron Trigger anyway, and I don't add calls purely for warming. If latency is a real problem, first record p95 and p99 separately in Analytics Engine and confirm it really is only the first request.
5. Japanese Queries Don't Work with Default FTS
D1's FTS5 with the unicode61 tokenizer doesn't recognize word boundaries in Japanese, so it returns much less than you'd expect. For Chinese/Japanese/Korean documents, use the trigram tokenizer (tokenize='trigram', available in SQLite 3.34+). The catch: trigram cannot match terms shorter than three characters. Two-character Japanese words like 次元 (dimension) or 料金 (price) return nothing, as the test below shows, so route short terms to LIKE '%term%' or leave them to vector search.
6. Forgetting Idempotent Ingestion
Early on, I let /ingest be called multiple times on the same document without any guard. The result was duplicate chunks in the index, which then dominated search results because they had identical embeddings ranked near each other. The fix is to make ingestion idempotent: always run the delete-then-upsert dance described above, or compute a hash of the body and skip the work if it hasn't changed.
A content hash short-circuits the most expensive part of the pipeline (embedding generation) and saves real money over time, especially when your ingestion job re-scans an entire corpus on a schedule.
7. Underestimating Eval Discipline
The hardest part of RAG isn't building the pipeline—it's knowing whether your changes made things better. Without an eval set, you'll convince yourself that every tweak is an improvement, when in fact several of them silently regress quality.
I keep a small spreadsheet of 30 representative questions and the article ID I expect to be the top hit for each. Every time I touch the chunker, embedding model, reranker, or topK, I run the eval suite and compare the recall@5 number. The discipline is unglamorous but it's what separates "I think this works" from "I can prove it works." How to build that eval set, and how a skewed question mix quietly distorts the numbers, is covered in the RAG retrieval evaluation harness article.
Run this in a Workers Cron daily, store the metrics in Analytics Engine, and you have a regression alarm bell you actually trust.
Troubleshooting Table
The same failures, rearranged so you can look them up by symptom.
Symptom
Likely cause
How to confirm
Fix
Only upsert fails with a dimension mismatch
Index dimensions differ from the embedding model's output
Measure data[0].length with the curl probe above and compare with dimensions from wrangler vectorize get
Recreate the index with the right dimensions and re-ingest (dimensions can't be changed later)
Upsert succeeded but the vector isn't in an immediate query
Vectorize writes are asynchronous and take a moment to apply
Log the mutationId from upsert and rerun the same query a few seconds later
Make post-ingest search checks wait and retry
A filter doesn't narrow anything
No metadata index, or it was created after the vectors were written
Check wrangler vectorize list-metadata-index for the property
Create the index, then upsert the affected vectors again
Only long documents fail to ingest
Firing all embedding calls at once hits the per-invocation limit
Log chunk count and the error text; confirm short documents don't reproduce it
Batch the embedding calls and run batches sequentially
FTS returns nothing for Japanese words
Built with unicode61, or querying terms of two characters or fewer with trigram
Query the same term against local SQLite as in the test above
Rebuild with trigram; send short terms to LIKE or vector search
Only searches containing symbols return 500
Raw user input is passed to FTS5 MATCH
Search Workers Logs for fts5: syntax error or no such column
Wrap it with toFtsPhrase
"Reranked" results are obviously wrong
The reranker's id is being treated as a chunk ID
Log the array you sent next to the returned id values
Map back with candidates[r.id]
The answer shows up as [object Object]
The text-generation return value is returned as-is
JSON.stringify the return value and look at its shape
Return .response
Three Common Misconceptions
Misconception 1: once upsert succeeds, you can search for it right away. Vectorize insert and upsert are asynchronous; what comes back is a mutationId meaning "accepted" (documented in the official Vectorize API reference). If a single test ingests and then searches, build in a wait-and-retry, or you'll have a test that fails only sometimes.
Misconception 2: a metadata index created later also covers existing vectors. It only applies to vectors written after it exists (documented on the official Metadata filtering page). Adding a filter condition to a live index means creating the index and re-upserting the affected vectors.
Misconception 3: Vectorize can be your store for the text too. You get back vector IDs, scores, and whatever metadata you put in, and metadata has a size limit. Keep the source of truth for the text in D1 or R2 and treat Vectorize as the component that answers "which chunks are close." Reindexing and backups both get simpler.
Build It Yourself, or Hand It to AI Search?
As of November 2026, Cloudflare also offers AI Search (formerly AutoRAG), which handles ingestion, retrieval, and generation as a managed service. Building it yourself, as this article does, isn't always the right call.
Approach
Effort
What you control
Good fit when
AI Search (Cloudflare's managed RAG)
Point it at your data and configure
Which data and which models; chunking and fusion details are handled for you
You want people asking questions of your docs quickly
Your own Workers + Vectorize + D1 pipeline (this article)
Implementation plus maintaining an eval set
Chunking, hybrid search, reranking, caching, and evaluation, all of it
You can't afford to miss Japanese proper nouns or version numbers, and you want to tune quality against numbers
External vector DB (Pinecone, Qdrant, etc.) + Workers
A separate contract and credentials to manage
Down to quantization and index tuning
Your vector count or tuning needs exceed what Vectorize allows
The rule I use is one sentence: until you need to tune retrieval quality against your own eval set, the managed option is enough. I moved to my own pipeline because I wanted to fix missed short Japanese terms and version numbers myself, with FTS and tests. Without that need, everything above is just maintenance load.
A Real-World Scenario: A Solo Developer Setup
Putting it all together at a realistic personal-product scale.
Scenario: Site Search and Related-Article Recommendations for a Tech Blog
Cron Trigger (daily 03:00 UTC): golden query regression test
Manual webhook on article add/update: reindex
There are three numbers I check weekly on this setup: Workers AI spend, retrieval-only p95, and the golden-query pass rate. All of them swing widely with scale and region, so I won't give targets here. Use UsageLogger and the health check above to get your own values, and compare them before and after any migration or optimization.
When to Plan for Scale
As the vector count grows, the latency breakdown shifts. For searches you can't narrow with metadata filters, the number of candidates you hand to the reranker ends up dominating latency. If UsageLogger records embedding, retrieval, reranking, and generation time separately, the numbers will tell you where to start.
Ordered by impact:
Re-tune chunk size: bigger chunks, fewer total vectors
Filter early via metadata indexes: scope by category or lang
Make reranking optional: skip reranking when the top-5 score gap is large
Split into multiple indexes: e.g., one per language or category
The upstream half of this pipeline — request routing, caching, and auth — is covered in the Cloudflare Edge SaaS architecture guide. Settling "who calls this search, and how" before you tune the search itself saves a surprising amount of rework. If you later want conversational Q&A with history, put per-session state in the shape described in the Durable Objects stateful agent guide, and you won't have to touch the Vectorize side at all.
What to Do Next
This article covered a lot of ground, but the action you can take tomorrow is simple: take 10–20 documents you already work with—blog posts, Notion exports, Markdown from a wiki—and ingest them into Vectorize. Hit /query with a few questions and see whether the right things come back.
The minimal scaffold is in the first half of this article. Run it as-is on your own data first. Only after you've felt the gap between the minimal version and what you actually need will hybrid search and reranking feel worth the effort. Trying to build the perfect setup from day one almost always stalls.
My own first RAG was sad. Retrieval was bad enough that I genuinely wondered whether the whole approach was viable. Having a scaffold to iterate on—chunking, model selection, reranking, one piece at a time—is what saved it. The biggest reason to use Antigravity is exactly this: the cost of producing the first working scaffold drops to near-zero.
Edge-deployed RAG is one of the most cost-effective ways for an indie developer to deliver search quality competitive with much larger teams. I hope your next product makes use of it.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.