Google Developer Expert | Cloud Architect | Open Source Enthusiast

Your Vector Search Isn't the Bottleneck: Measuring RAG Latency End to End

When a RAG endpoint feels slow, the vector search is usually the first thing that gets blamed. Open a trace of the whole request and the picture usually flips: the database is the smallest slice.

AlloyDB AI is built to serve RAG retrieval without a standalone vector database. Whether it meets your QPS and latency targets at 1,536 to 3,072 dimensions is something you have to measure, and this post shows how: the architecture, an example latency budget, a reproducible benchmark harness, and the tuning order that moves p99.

Naming note: Google renamed Vertex AI to Gemini Enterprise Agent Platform on April 22, 2026. I’ll say “Agent Platform” throughout; the code uses the Google Gen AI SDK in its Vertex AI mode (vertexai=True).

TL;DR — what end-to-end measurement usually shows:

  • The database is the smallest slice. Query embedding and generation dominate time to first token. A well-indexed, filtered ANN query should fit a budget of tens of milliseconds.
  • p99 breaks on memory and filters, not on row count. Tail latency jumps when the index working set leaves memory, or when a selective filter starves the ANN scan.
  • Dimensions are a cost knob. Matryoshka-trained Gemini embedding models let you store 3,072, 1,536 or 768 dimensions. Choose by measured recall on your own corpus.
  • Latency without recall is meaningless. Every load step must report recall@k against exact search, or a “faster” config may simply return worse context.

Why keep vectors in the operational database

Keeping embeddings in the same rows as the content and permissions they describe removes a sync pipeline, a second security model and a network hop. AlloyDB AI runs pgvector-compatible search, with both HNSW and Google’s ScaNN index, inside PostgreSQL.

Concern Standalone vector database AlloyDB with pgvector + ScaNN
Freshness A CDC or dual-write pipeline syncs vectors; lag and drift are possible Chunk, embedding and ACL commit in one transaction
Filters and joins Metadata is copied into the vector store and kept in sync Native SQL predicates, B-tree and GIN indexes, joins
Access control A second identity model and audit trail Existing IAM, VPC and PSC, CMEK, audit logs, row-level security
Operations Separate backups, HA, upgrades and on-call One backup, PITR, HA and read-pool story
Request path Vector query, then a database round trip to hydrate text One SQL statement returns IDs, text and permissions

The trade-off is shared resources: vector search competes with OLTP for CPU and buffer cache, which is why retrieval runs on a read pool. The section on when a standalone vector database still makes sense lists when the trade stops paying off.

Reference architecture

The diagram below maps the query and ingestion paths across Cloud Run, Agent Platform, and an AlloyDB cluster with a dedicated read pool.

RAG on AlloyDB AI reference architecture: the RAG service embeds the query with Agent Platform, retrieves from an AlloyDB read pool in one SQL statement, then generates with Agent Platform; ingestion writes to the AlloyDB primary

Anatomy of end-to-end query latency

End-to-end latency for a chat-style RAG endpoint is request receipt to first streamed token; for a retrieval API it is request receipt to rows returned. Budget each stage separately, because each has a different owner and a different fix.

The budget below is an example for an interactive assistant with a 1-second p95 time-to-first-token SLO. It is a design target to measure against, not a measurement; derive yours from your SLO.

Stage Example p95 budget What drives it Where to measure
1. Ingress and auth 10 ms Load balancer, token validation Root server span
2. Query embedding 80 ms Region round trip, model, input length, quota retries Client span around the embed call
3. Pool checkout 2 ms Pool size versus concurrency Span around pool.acquire()
4. ANN search with filters 20 ms Index type, partitions or ef_search, filter selectivity, cache residency EXPLAIN (ANALYZE, BUFFERS) plus app span
5. Hydration and ACL join 10 ms Rows and columns fetched, TOAST reads, joins Same SQL statement; separate plan nodes
6. Rerank (optional) 80 ms Candidate count, reranker model Client span
7. Generation to first token 750 ms Model, prompt tokens, region Streaming callback timestamp

Percentiles do not add: the p95 of the whole request is not the sum of stage p95s, so record the root span’s own distribution.

High-dimensional embeddings: what each dimension costs

Dimension count sets bytes per row, index memory and the cost of every distance computation. gemini-embedding-2 (multimodal, up to 8,192 input tokens) and the text-only gemini-embedding-001 both output 3,072 dimensions by default and truncate cleanly thanks to Matryoshka (MRL) training; Google recommends 3,072, 1,536 or 768.

Dimensions vector bytes/row halfvec bytes/row 10M rows, vector 10M rows, halfvec pgvector HNSW can index
768 3,080 1,544 30.8 GB 15.4 GB vector or halfvec
1,536 6,152 3,080 61.5 GB 30.8 GB vector or halfvec
3,072 12,296 6,152 123.0 GB 61.5 GB halfvec only

Sizes are the raw column only (4 × dims + 8 and 2 × dims + 8 bytes, per the pgvector README), before index structures and the rest of the row. pgvector’s HNSW and IVFFlat indexes accept up to 2,000 dimensions on vector and 4,000 on halfvec.

Practical rules:

  • Start at 1,536 for text RAG, then test 768 and 3,072 on held-out queries. Keep the cheapest size that meets your recall target.
  • One model, version, dimensionality and prompt format per column. Query and document vectors must match exactly. gemini-embedding-2 takes task instructions as text prefixes: Google recommends task: search result | query: {text} for queries and title: {title} | text: {text} for documents, applied at both index and query time. A model change is a migration, covered under running it in production.
  • Normalize truncated vectors. A prefix of a unit vector is shorter than unit length. gemini-embedding-2 automatically normalizes vectors truncated via output_dimensionality, whereas gemini-embedding-001 and client-side slices do not. Normalizing defensively at ingestion and query time (pgvector’s l2_normalize() works in SQL) keeps vectors unit-length across models and makes cosine (<=>) and inner product (<#>) rankings equivalent.
  • Mind TOAST. pgvector stores vectors with EXTERNAL storage, so values over about 2 KB live out of line and every heap read of the vector costs an extra lookup. If the whole row fits an 8 KB page, test ALTER TABLE ... ALTER COLUMN embedding SET STORAGE PLAIN; a 3,072-d vector never fits.
  • Size disk with pg_total_relation_size(). pg_relation_size() excludes TOAST and will understate an embeddings table badly.

Indexing: pgvector HNSW versus AlloyDB ScaNN

On AlloyDB, start with a ScaNN index in AUTO mode. Keep HNSW where you need portability to other PostgreSQL hosts or already have it tuned.

Google’s AlloyDB vector search overview claims, against standard PostgreSQL HNSW, up to 10x faster index creation, up to 4x faster vector queries and up to 10x faster filtered queries. Its March 2025 benchmark post reports a 4x smaller memory footprint, and 431 ms versus more than 4 s on BigANN-1B when neither index fit in memory on a 16 vCPU, 128 GB machine.

I’d read those numbers with one caveat: the benchmarks used 100- and 128-dimension datasets (Glove-100 and BigANN-1B). At 1,536 or 3,072 dimensions, distance cost and memory per vector grow 12x to 30x, so rerun the comparison on your own embeddings.

-- Start here: AlloyDB chooses the tree shape and maintains it as data grows
CREATE INDEX chunks_embedding_scann
  ON rag.chunks USING scann (embedding cosine)
  WITH (mode = 'AUTO');

-- Manual tuning, only once measurements justify it (about 10M rows shown)
-- CREATE INDEX chunks_embedding_scann
--   ON rag.chunks USING scann (embedding cosine)
--   WITH (mode = 'MANUAL', num_leaves = 3200, quantizer = 'SQ8',
--         max_num_levels = 1, auto_maintenance = 'ON');

For a 3,072-d column on HNSW, index a halfvec expression and repeat that expression in every query:

CREATE INDEX chunks_embedding_hnsw
  ON rag.chunks USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops)
  WITH (m = 16, ef_construction = 64);

SELECT chunk_id FROM rag.chunks
ORDER BY embedding::halfvec(3072) <=> $1::halfvec(3072)
LIMIT 20;
Knob Index Set at Effect Starting point
mode ScaNN Build AUTO tunes and maintains the tree; MANUAL exposes the knobs below AUTO
num_leaves ScaNN Build Partition count; more gives finer partitions and slower builds √rows for a two-level tree; maximum 30M on PostgreSQL 16 and earlier, 104,857,600 on 17+
quantizer ScaNN Build SQ8 typically loses under 1–2% recall; FLAT for 99%+ recall; AH (Preview) compresses up to 4x more than SQ8 and can query faster with the columnar engine SQ8
scann.enable_pca ScaNN Session (before build) Shrinks stored dimensions automatically On; turn off if recall drops
scann.num_leaves_to_search ScaNN Query Partitions scanned: the main recall-versus-QPS dial 1% of num_leaves, then sweep
scann.pct_leaves_to_search ScaNN Query Partitions to search as a percentage of leaves, managed automatically Alternative dial when an AUTO index chose num_leaves for you
scann.pre_reordering_num_neighbors ScaNN Query Candidates rescored before the final top k 0, or 50 × k with PCA; keep it above k
scann.num_search_threads ScaNN Query Threads per query; helps single-query latency only with spare CPU 2
scann.satisfy_limit ScaNN Database flag relaxed_order keeps scanning until LIMIT is met under filters (Preview) On for filtered traffic
scann.max_pct_leaves_to_search ScaNN Database flag Caps the share of leaves visited while satisfy_limit is on 15 (default)
m, ef_construction HNSW Build Graph degree and build effort 16, 64
hnsw.ef_search HNSW Query Candidate list size: the HNSW recall dial 40, then sweep to 200
hnsw.iterative_scan HNSW Query Keeps scanning when filters discard rows (pgvector 0.8+) relaxed_order

Full parameter definitions are in the ScaNN index reference.

Filtered and multi-tenant search under enterprise query shapes

Filter selectivity, not row count, decides recall and p99 in enterprise RAG. Almost every real query carries a tenant, an access-control and a status predicate.

The trap is post-filtering. An index that hands back k candidates before the WHERE clause runs can return fewer than k rows, or none, when the filter is selective. The query looks fast and silently starves the prompt.

The canonical retrieval statement does filtering, ranking and hydration in one round trip:

SELECT c.chunk_id, c.doc_id, c.content,
       c.embedding <=> $1 AS distance
FROM rag.chunks AS c
WHERE c.tenant_id  = $2
  AND c.status     = 'published'
  AND c.acl_groups && $3::text[]        -- the caller's groups
ORDER BY c.embedding <=> $1
LIMIT $4;

Three tools keep filtered queries both fast and complete:

  • ScaNN inline filtering. AlloyDB builds a bitmap of qualifying rows from B-tree, GIN or GiST indexes on the filter columns (the schema below creates them) and computes distances only inside it. Adaptive filtering learns selectivity at runtime and reorders filter and vector work.
  • scann.satisfy_limit = relaxed_order. When filters leave too few results, the scan continues past num_leaves_to_search, capped by scann.max_pct_leaves_to_search (15% of leaves by default). Google documents both as database flags, so confirm a session-level setting takes effect, or set them on the instance.
  • pgvector iterative scans. For HNSW, hnsw.iterative_scan keeps pulling candidates until enough rows pass, bounded by hnsw.max_scan_tuples (20,000 by default).

For slices too small for ANN, such as tenants you know are small, filter first and compute exact distances: recall is 100% and a few thousand distance computations are cheap. A materialized CTE forces filter-then-rank:

WITH slice AS MATERIALIZED (
  SELECT chunk_id, doc_id, content, embedding
  FROM rag.chunks
  WHERE tenant_id = $2 AND status = 'published' AND acl_groups && $3::text[]
)
SELECT chunk_id, doc_id, content, embedding <=> $1 AS distance
FROM slice
ORDER BY distance
LIMIT $4;

Benchmark each selectivity band separately, because each band fails differently:

Band Rows passing the filter Example Plan to expect Watch
Broad Over 10% Large tenant, open ACL ANN with inline filter Recall close to unfiltered
Moderate 1–10% Mid-size tenant, department ACL ANN with inline filter p99 and short result sets
Narrow 0.1–1% Small tenant or tight ACL Inline filter plus satisfy_limit, or exact The recall cliff
Tiny Under 0.1% One project, a few thousand chunks Filter, then exact distance That the planner or router picks it

If you enforce tenant isolation with row-level security, benchmark with it on, since its predicates change plans.

Benchmark methodology

A benchmark is credible only when its corpus, query mix and arrival pattern look like production.

Run it in two modes. Database-only replays precomputed query vectors straight at AlloyDB and isolates stages 3 to 5; it finds the database’s capacity. End-to-end drives the real service with tracing on and finds the system’s capacity, including Agent Platform calls.

  1. Corpus. Use real chunks at the size you expect in 12 months, embedded with the production model and dimensionality. Avoid random vectors: they lack cluster structure, so ANN indexes behave unrealistically on them.
  2. Queries. Sample at least 10,000 real queries from scrubbed logs and embed them with the same model. Hold out 1,000 for ground truth.
  3. Ground truth. For each held-out query and its filter, compute the exact top k without using the ANN index (below) and cache the result per corpus snapshot. Recall@k is the overlap between ANN and exact results divided by k.
  4. Query mix. Weight filter bands, top-k values and tenants by production traffic, including queries routed to the exact path. A few hot tenants dominate load and cache.
  5. Arrival model. Use an open-loop generator with Poisson arrivals at a fixed offered rate. Closed-loop tools wait for each reply before sending the next request, which hides queueing and flatters p99.
  6. Load steps. Offer 25%, 50%, 75%, 100% and 125% of target peak QPS. Warm up for 5 minutes, then measure for 10 minutes per step.
  7. Background writes. Replay production-rate upserts during every step; indexes and caches behave differently under writes.
  8. Cold start. Repeat the 100% step straight after a restart or failover with --warmup 0 to capture cold-cache p99.
  9. Environment. Put clients, service and AlloyDB in one region. Keep load generators under about 50% CPU, store instance shapes, versions and flags with each run, and record the columns listed under reading the results for every step.

Ground truth only depends on the corpus and held-out queries, not on ANN search knobs—compute it once and reuse it across sweeps. Using a MATERIALIZED filter CTE (as recall.py below does) lets PostgreSQL keep using exact B-tree and GIN indexes for the WHERE predicates while bypassing the ANN index for exact distance ranking; confirm with EXPLAIN that no scann or hnsw index scan appears in the plan.

Benchmark harness

Three small Python files cover both modes: an open-loop load generator, a recall checker and a traced end-to-end request. They need only asyncpg, pgvector, numpy, and for the traced request google-genai and opentelemetry-api.

The schema keeps the chunk, its access control and its vector in one row. Create the ScaNN index after loading data, because AlloyDB won’t build an auto-tuned one below 10,000 rows unless you enable deferred creation (Preview).

-- Installs alloydb_scann and, if missing, the pgvector-based vector extension
CREATE EXTENSION IF NOT EXISTS alloydb_scann CASCADE;
CREATE SCHEMA IF NOT EXISTS rag;

CREATE TABLE rag.chunks (
  chunk_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id   int          NOT NULL,
  doc_id      uuid         NOT NULL,
  status      text         NOT NULL DEFAULT 'published',
  acl_groups  text[]       NOT NULL,
  updated_at  timestamptz  NOT NULL DEFAULT now(),
  content     text         NOT NULL,
  embedding   vector(1536) NOT NULL   -- gemini-embedding-2 at 1,536-d, unit length
);

CREATE INDEX chunks_tenant_status ON rag.chunks (tenant_id, status);
CREATE INDEX chunks_acl ON rag.chunks USING gin (acl_groups);

-- After the bulk load, create the ScaNN index from the indexing section,
-- then update planner statistics for inline/adaptive filter selectivity:
ANALYZE rag.chunks;

Load generator (bench.py)

It replays query vectors at Poisson arrival times, selects the hydrated payload (doc_id, content, and distance) so stage 5 TOAST reads are included, and measures from each request’s scheduled start so pool waits and client queueing count against latency. Pass index knobs with repeated --set flags; each run records the values the server actually applied.

"""Open-loop load generator for AlloyDB filtered vector retrieval.

python bench.py --dsn "$ALLOYDB_DSN" --queries queries.npz --qps 400 \
    --warmup 300 --duration 600 --set scann.num_leaves_to_search=200 --raw run.npz
"""
import argparse
import asyncio
import json
import time

import asyncpg
import numpy as np
from pgvector.asyncpg import register_vector

SQL = """
SELECT chunk_id, doc_id, content, embedding <=> $1 AS distance
FROM rag.chunks
WHERE tenant_id = $2
  AND status = 'published'
  AND acl_groups && $3::text[]
ORDER BY embedding <=> $1
LIMIT $4
"""


def load_queries(path):
    # emb: (N, D) float32, unit length; tenant: (N,) int;
    # acl: (N,) object array of group-name lists; k: (N,) int
    d = np.load(path, allow_pickle=True)
    return list(zip(d["emb"], d["tenant"], d["acl"], d["k"]))


def percentiles(seconds):
    if not seconds:
        return {}
    ms = np.asarray(seconds) * 1000.0
    return {f"p{p}": round(float(np.percentile(ms, p)), 2) for p in (50, 95, 99, 99.9)}


async def run(args):
    gucs = [s.split("=", 1) for s in args.set]

    # Startup parameters survive the RESET ALL that asyncpg runs on release;
    # settings applied with SET or set_config() in init would not.
    pool = await asyncpg.create_pool(
        args.dsn, min_size=args.pool, max_size=args.pool,
        init=register_vector, server_settings=dict(gucs),
    )
    async with pool.acquire() as conn:  # record what the server applied
        applied = {name: await conn.fetchval("SELECT current_setting($1)", name)
                   for name, _ in gucs}
    queries = load_queries(args.queries)
    rng = np.random.default_rng(args.seed)
    total, service, wait = [], [], []
    failures = {"timeout": 0, "error": 0}

    async def one(q, scheduled, record):
        emb, tenant, acl, k = q
        deadline = time.perf_counter() + args.timeout
        try:
            async with pool.acquire(timeout=args.timeout) as conn:
                t_acquired = time.perf_counter()
                remaining = deadline - t_acquired
                if remaining <= 0:
                    raise asyncio.TimeoutError
                await conn.fetch(SQL, emb, int(tenant), list(acl), int(k),
                                 timeout=remaining)
                t_done = time.perf_counter()
        except asyncio.TimeoutError:
            if record:
                failures["timeout"] += 1
            return
        except Exception:
            if record:
                failures["error"] += 1
            return
        if record:
            wait.append(t_acquired - scheduled)
            service.append(t_done - t_acquired)
            total.append(t_done - scheduled)

    tasks, idx, sent = [], 0, 0
    start = time.perf_counter()
    measure_start = start + args.warmup
    measure_end = measure_start + args.duration
    scheduled = start
    while scheduled < measure_end:
        delay = scheduled - time.perf_counter()
        if delay > 0:
            await asyncio.sleep(delay)
        q = queries[idx % len(queries)]
        idx += 1
        record = scheduled >= measure_start
        if record:
            sent += 1
        tasks.append(asyncio.create_task(one(q, scheduled, record)))
        scheduled += rng.exponential(1.0 / args.qps)  # Poisson arrivals
    await asyncio.gather(*tasks)
    elapsed = time.perf_counter() - measure_start  # includes stragglers past --duration
    await pool.close()

    if args.raw:  # merge raw samples across clients; never average percentiles
        np.savez(
            args.raw,
            total=np.asarray(total),
            service=np.asarray(service),
            wait=np.asarray(wait),
        )

    print(json.dumps({
        "offered_qps": args.qps,
        "achieved_qps": round(len(total) / elapsed, 1),
        "sent": sent,
        "failures": failures,
        "total_ms": percentiles(total),
        "service_ms": percentiles(service),
        "pool_wait_ms": percentiles(wait),
        "settings": applied,
        "pool_size": args.pool,
    }, indent=2))


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--dsn", required=True)
    p.add_argument("--queries", required=True)
    p.add_argument("--qps", type=float, required=True)
    p.add_argument("--warmup", type=float, default=300)
    p.add_argument("--duration", type=float, default=600)
    p.add_argument("--pool", type=int, default=64)
    p.add_argument("--timeout", type=float, default=2.0)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--raw", help="write raw samples to this .npz")
    p.add_argument("--set", action="append", default=[],
                   help="GUC=value applied to every session; repeatable")
    asyncio.run(run(p.parse_args()))

One Python process saturates at a few thousand requests per second. Beyond that, run several clients on separate VMs with --raw, concatenate the samples, and compute percentiles once.

Recall checker (recall.py)

It compares the ANN plan against exact search on the held-out set and counts short result sets separately, since they are the visible symptom of filter starvation. Pass --truth to compute exact ground truth once via a materialized filter CTE and reuse it across every sweep setting.

"""Recall@k of the ANN plan against exact search, per held-out query.

python recall.py --dsn "$ALLOYDB_DSN" --queries holdout.npz \
    --truth ground_truth.npz --set scann.num_leaves_to_search=200
"""
import argparse
import asyncio
import os

import asyncpg
import numpy as np
from pgvector.asyncpg import register_vector

from bench import load_queries

ANN_SQL = """
SELECT chunk_id
FROM rag.chunks
WHERE tenant_id = $2
  AND status = 'published'
  AND acl_groups && $3::text[]
ORDER BY embedding <=> $1
LIMIT $4
"""

EXACT_SQL = """
WITH slice AS MATERIALIZED (
  SELECT chunk_id, embedding
  FROM rag.chunks
  WHERE tenant_id = $2
    AND status = 'published'
    AND acl_groups && $3::text[]
)
SELECT chunk_id
FROM slice
ORDER BY embedding <=> $1
LIMIT $4
"""


async def main(args):
    gucs = [s.split("=", 1) for s in args.set]
    conn = await asyncpg.connect(args.dsn, server_settings=dict(gucs))
    await register_vector(conn)
    applied = {name: await conn.fetchval("SELECT current_setting($1)", name)
               for name, _ in gucs}

    queries = load_queries(args.queries)
    cached = (
        list(np.load(args.truth, allow_pickle=True)["exact"])
        if args.truth and os.path.exists(args.truth)
        else None
    )

    exact_all, recalls, short = [], [], 0
    for i, (emb, tenant, acl, k) in enumerate(queries):
        params = (emb, int(tenant), list(acl), int(k))
        ann = [r["chunk_id"] for r in await conn.fetch(ANN_SQL, *params)]
        if cached is not None:
            exact = list(cached[i])
        else:
            exact = [r["chunk_id"] for r in await conn.fetch(EXACT_SQL, *params)]
            exact_all.append(exact)
        if not exact:
            continue
        short += len(ann) < len(exact)
        recalls.append(len(set(ann) & set(exact)) / len(exact))
    await conn.close()

    if args.truth and cached is None:
        np.savez(args.truth, exact=np.array(exact_all, dtype=object))

    r = np.asarray(recalls)
    print(f"queries={len(r)} mean_recall={r.mean():.4f} "
          f"p5_recall={np.percentile(r, 5):.4f} short_results={short} "
          f"settings={applied}")


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--dsn", required=True)
    p.add_argument("--queries", required=True)
    p.add_argument("--truth", help="load or save cached exact ground truth (.npz)")
    p.add_argument("--set", action="append", default=[])
    asyncio.run(main(p.parse_args()))

Report the 5th-percentile recall as well as the mean: a mean of 0.97 can hide a tail of queries that return almost nothing useful.

Traced end-to-end request (rag_trace.py)

In end-to-end mode, give every stage its own OpenTelemetry span so Cloud Trace shows where each slow request spent its time. Create the asyncpg pool with init=pgvector.asyncpg.register_vector.

import time

import numpy as np
from google import genai
from google.genai import types
from opentelemetry import trace

tracer = trace.get_tracer("rag")
# gemini-embedding-2 is served from global, us or eu (no single-region endpoint);
# use a separate client for generation so each model runs in its closest location.
embed_client = genai.Client(vertexai=True, project="PROJECT_ID", location="global")
gen_client = genai.Client(vertexai=True, project="PROJECT_ID", location="us-central1")

EMBED_MODEL = "gemini-embedding-2"
EMBED_DIMS = 1536             # must match the vector(1536) column
# gemini-embedding-2 takes task instructions as text prefixes. Ingestion must
# embed chunks as f"title: {title or 'none'} | text: {chunk}" to match.
QUERY_PREFIX = "task: search result | query: "
GEN_MODEL = "GEN_MODEL_ID"    # your Gemini generation model
RETRIEVE_SQL = """
SELECT c.chunk_id, c.content, c.embedding <=> $1 AS distance
FROM rag.chunks AS c
WHERE c.tenant_id = $2 AND c.status = 'published' AND c.acl_groups && $3::text[]
ORDER BY c.embedding <=> $1
LIMIT $4
"""


def unit(values):
    v = np.asarray(values, dtype=np.float32)
    # Defensive: gemini-embedding-2 auto-normalizes truncated outputs,
    # while gemini-embedding-001 and client-side slices do not.
    return v / np.linalg.norm(v)


def build_prompt(question, rows):
    context = "\n\n".join(f"[{r['chunk_id']}] {r['content']}" for r in rows)
    return ("Answer only from the sources below and cite their ids.\n\n"
            f"{context}\n\nQuestion: {question}")


async def answer(pool, question, tenant_id, groups, k=20):
    with tracer.start_as_current_span("rag.request") as root:
        with tracer.start_as_current_span("rag.embed"):
            r = await embed_client.aio.models.embed_content(
                model=EMBED_MODEL,
                contents=QUERY_PREFIX + question,
                config=types.EmbedContentConfig(output_dimensionality=EMBED_DIMS),
            )
            qvec = unit(r.embeddings[0].values)

        with tracer.start_as_current_span("rag.pool_wait"):
            conn = await pool.acquire()
        try:
            with tracer.start_as_current_span("rag.retrieve") as span:
                rows = await conn.fetch(RETRIEVE_SQL, qvec, tenant_id, groups, k)
                span.set_attribute("rag.k", k)
                span.set_attribute("rag.rows_returned", len(rows))
        finally:
            await pool.release(conn)

        with tracer.start_as_current_span("rag.generate") as span:
            parts, first_token, t0 = [], False, time.perf_counter()
            stream = await gen_client.aio.models.generate_content_stream(
                model=GEN_MODEL, contents=build_prompt(question, rows))
            async for chunk in stream:
                if chunk.text:
                    if not first_token:
                        span.set_attribute("rag.ttft_ms", (time.perf_counter() - t0) * 1000)
                        root.add_event("first_token")
                        first_token = True
                    parts.append(chunk.text)
            # In production, stream each part to the client here instead.
        return "".join(parts)

Notice that pool.release(conn) runs before rag.generate starts: holding a database connection across a streaming LLM response is one of the fastest ways to exhaust a connection pool under load. And the rag.rows_returned attribute matters more than it looks—alert when it falls below k, because that is filter starvation reaching real users.

Reading the results

Log every run as one row with fixed columns, then read three curves: latency against offered QPS, recall against latency, and p99 by filter band.

Column Definition Why it matters
Config Index, mode, knobs, dimensions, instance shape, read pool nodes Makes runs comparable
Offered and achieved QPS Arrival rate sent versus completions per second A gap means saturation
Total p50 to p99.9 Scheduled start to last row What users feel
Service p99 Pool checkout to last row What the database feels
Pool wait p99 Scheduled start to checkout Queueing in front of the database
Recall@k, mean and p5 Against exact search, per filter band Quality at that speed
Short results Share of queries returning fewer than k rows Filter starvation
Errors and timeouts Count and share of requests Dropped requests flatter latency
CPU and cache hit ratio Instance metrics over the step Shows which limit you hit

What the patterns usually mean:

  • Total p99 leaves service p99 behind. That is the knee: requests now queue for connections. Size steady-state peak well below it so bursts and failover still fit; a 30% margin is a sensible starting point.
  • Service p99 rises while CPU stays moderate. The working set has left memory. Check the cache hit ratio, then shrink dimensions, move to halfvec, or add memory.
  • Service p99 rises with CPU near saturation. You are compute-bound. Lower the partitions searched if recall allows, add read pool nodes, or reduce scann.num_search_threads, since extra threads per query compete under load.
  • Recall drops only in the narrow bands. Filters are starving the scan. Enable satisfy_limit or iterative scans, or route that band to the exact path.
  • Cold p99 sits far above warm p99. Expect it after failover and maintenance; replay a slice of traffic before shifting full load.
  • p99 jumps when background writes run. Index maintenance and cache churn are competing with reads; move bulk re-embeds off-peak.

For end-to-end runs, compare the root span’s p95 with the budget. For each request over budget, the largest child span names the stage to fix.

Tuning playbook

Tune in this order, because each step changes what the next one measures. Rerun the recall checker after every change.

  1. Fit the working set in memory. Settle dimensions and vector versus halfvec first, then instance size; nothing later rescues an index that pages from storage.
  2. Use ScaNN in AUTO mode. Switch to MANUAL only with a measured reason, and keep auto-maintenance on.
  3. Set the recall dial. Sweep scann.num_leaves_to_search (or hnsw.ef_search) at target QPS and keep the lowest value that meets your recall@k target. An AUTO index picks its own num_leaves, so read it from the indexconfig column of pg_stat_ann_indexes before choosing sweep values, or sweep scann.pct_leaves_to_search instead.
  4. Set reordering. If recall plateaus below target, raise scann.pre_reordering_num_neighbors above k; it trades CPU for precision.
  5. Fix filtered traffic. Add the B-tree and GIN indexes that inline filtering uses, enable satisfy_limit for narrow bands, and route tiny slices to exact search.
  6. Size the connection pool. Start around twice the vCPU count of the instances you query. Raise it only while pool wait falls and service p99 holds.
  7. Scale reads out. Point retrieval at an AlloyDB read pool and add nodes when CPU, not memory, is the limit. Keep writes on the primary.
  8. Trim the statement. Select only the columns the prompt uses and keep LIMIT tight. Do not return vectors you do not need; each one is a TOAST read plus network bytes.
  9. Cut stage 2. Cache query embeddings keyed by normalized query text and model version, so repeated questions skip the Agent Platform call.
  10. Co-locate. Keep Cloud Run and AlloyDB in one region, and call each model from the closest location it is offered in. gemini-embedding-2 has no single-region endpoint, so compare global with the us or eu multi-region in your end-to-end runs. A cross-region hop costs more than most index tuning saves.

A sweep for step 3 pairs every load run with a recall run at the same setting:

for n in 50 100 200 400; do
  python bench.py --dsn "$DSN" --queries queries.npz --qps 400 \
    --warmup 300 --duration 600 \
    --set scann.num_leaves_to_search=$n --raw "run_$n.npz" > "run_$n.json"
  python recall.py --dsn "$DSN" --queries holdout.npz --truth ground_truth.npz \
    --set scann.num_leaves_to_search=$n > "recall_$n.txt"
done

Before trusting any sweep, run EXPLAIN (ANALYZE, BUFFERS) on a representative query. Confirm the plan uses the ScaNN index, and compare shared buffer hits against reads to see whether you are measuring memory or storage. Then check that latency and recall actually move between sweep settings; if they don’t, the knob is not reaching the session.

Running it in production

Production adds three things a benchmark only samples: recall drift, index churn and model migrations. Each needs a standing control, not a one-off test.

  • Observe every request. Keep the stage spans from the harness and export them to Cloud Trace. Watch the retrieval statement in AlloyDB Query Insights and pg_stat_statements for latency and plan changes.
  • Alert on causes, not only symptoms. Page on rag.rows_returned below k, pool wait p99, service p99 and CPU, alongside request latency.
  • Canary recall nightly. Run recall.py with production settings against a dedicated canary read pool node (or a clone/snapshot when recomputing exact ground truth, so exact scans never evict buffer cache on nodes serving live traffic). Alert when mean or p5 recall falls more than 2 points, and refresh the held-out set from new logs each quarter.
  • Maintain the index. After a bulk load or re-embed, rebuild with REINDEX INDEX CONCURRENTLY. For HNSW on update-heavy tables, keep autovacuum aggressive.
  • Keep authorization in SQL. Apply ACL predicates or row-level security in the retrieval statement, so the model never sees a chunk the caller cannot read. Log retrieved chunk IDs per request for audit.

Change embedding models with a second column, never in place:

  1. Add embedding_v2 with the new dimensionality and backfill it in off-peak batches.
  2. Build its index with CREATE INDEX CONCURRENTLY once the backfill completes.
  3. Shadow-read: compare v1 and v2 retrieval and answer quality on the held-out set.
  4. Switch the query path behind a flag, keep v1 for rollback, then drop it.

When a standalone vector database still makes sense

Keep vectors in AlloyDB by default, and move them out only when a measured limit forces it.

  • Memory economics at extreme scale. Billions of high-dimensional vectors that must stay hot can cost more as database memory than in a purpose-built service.
  • Vectors with no relational context. If queries never filter or join on business data, co-location loses its main advantage.
  • Re-embedding churn the write path cannot absorb. Frequent full re-embeds of a very large corpus load the same database that serves OLTP.
  • A latency target the database stage still misses. If stage 4 alone misses its budget at target QPS after the playbook, benchmark Agent Platform Vector Search (formerly Vertex AI Vector Search) with the same harness.
  • One index shared across many applications and regions. A dedicated retrieval service may fit that ownership model better.

Even then, keep AlloyDB as the source of truth. Treat the external index as a derived copy you can rebuild from the table.

The production readiness checklist

Area Ready when
SLO End-to-end SLO and a per-stage latency budget are written down
Embeddings One embedding model, version, dimensionality and prompt format per column; vectors unit-normalized
Memory Vectors plus index fit in memory on the nodes that serve retrieval
Index ScaNN index auto-tuned with auto-maintenance, or HNSW on a halfvec expression above 2,000 dimensions
Filters B-tree and GIN indexes exist for every filter in the retrieval statement
Ground truth Held-out queries with exact ground truth for each filter band
Load test Open-loop runs at 25–125% of peak, with background writes and a cold-start run
Quality Mean and p5 recall@k plus short-result rate recorded for every run
Topology Retrieval routed to a read pool, with pool size tuned against pool wait
Observability Stage spans in production, an alert on rows returned below k, and a nightly recall canary
Migrations A second-column migration path for the next embedding model

Closing thought

High-QPS, low-latency RAG on AlloyDB is a measurement discipline more than an index choice. Budget each stage, load-test with production-shaped traffic, and never publish latency without recall.

If you run this against your own corpus and your numbers disagree with anything here, I’d like to hear about it, particularly ScaNN versus HNSW at 1,536 and 3,072 dimensions, where Google’s published benchmarks don’t reach.

References