The AI Infra Stack End-to-End: Embeddings, Vector DBs & Serving
Trace one request through the AI infra stack: text to embeddings to vector DB (HNSW/IVF) to reranker to model gateway to inference server. Where latency, cost, and failure concentrate.
Your bar: trace one user query through the whole stack —
text → embedding → vector DB → reranker → model gateway → inference server— and say, at each hop, what it does and where the latency, cost, and failure concentrate. By the end you can answer the foundational interview question:
what actually happens to a request between “user hits enter” and “tokens stream back,” and which hop do you instrument first?1The stack is one straight line. Every hop transforms the request and hands it on:
The Stack Map
The request path is a pipeline of single-purpose hops. Each one transforms the request and hands it forward, and each one is where some specific kind of pain — latency, cost, or failure — concentrates.
The hop-by-hop request path
What each hop does — and what it costs you
| Hop | Its one job | Where the pain lands |
|---|---|---|
| Embedding model | Turn query text into a dense vector | A model/version swap re-indexes the whole corpus |
| Vector DB (ANN) | Return the top-K nearest vectors fast | Recall vs latency vs memory — the core ANN trade |
| Reranker | Re-score the top-K for precision | Fixed cost per candidate; cannot recover a missed doc |
| Model gateway | Auth, route, rate-limit, cache, account | Cost & reliability chokepoint — the blast radius |
| Inference server | Run the GPU forward pass, stream tokens | KV-cache memory caps batch size, caps throughput |
Is The AI infra stack is the chain of services a request crosses from raw text to streamed answer: embed, retrieve (ANN), rerank, gateway, infer, cache.
Why it exists No single service does all of it well. Retrieval needs a vector index; serving needs GPUs and a control plane. Splitting the work lets each tier scale and fail independently.
Like (world) A library request: the catalog narrows millions of books to a shelf (retrieval), a librarian picks the best few (rerank), and a reading room serves them (inference). Each step has its own line and bottleneck.
Like (code) A classic web request path: DNS → LB → app → cache → DB. You profile per hop and optimize the one that dominates p95 — same discipline here.
✓ The model is one hop. Most production latency, cost, and failure live in retrieval and the serving control plane around it, not inside the model call.
✓ Instrument per hop first. The dominant cost is often queue-wait at the inference server or an over-tuned ANN search, not the forward pass itself.
📥 Memory rule: The stack is a pipeline of single-purpose hops. Retrieval picks what; serving governs how — instrument every hop before you optimize one.
Memory check
- Name the hops in order. → text → embedding → vector DB (ANN) → reranker → model gateway → inference server → response cache
- Which half decides what's in the prompt vs how it's served? → embed/retrieve/rerank decide WHAT; gateway/inference decide HOW
- Which hop usually dominates latency? → the inference forward pass (sequential, GPU-bound), with queue-wait next under load — but measure, don't assume
M1 — Walk me through what happens to one user query as it travels through a production RAG stack.
Hit these points: the query text is embedded into a vector by an embedding model → that vector hits the vector DB, which runs approximate nearest-neighbor (HNSW or IVF) over millions of stored vectors to return a top-K candidate set → an optional reranker (a cross-encoder) re-scores that small set jointly with the query for precision → the chosen passages plus the prompt go to the model gateway, which authenticates, rate-limits, routes, and may serve a response-cache hit → on a miss the inference server runs the forward pass with KV cache and continuous batching, streaming tokens back → name where each hop concentrates risk: ANN trades recall for latency, the gateway is the reliability and cost chokepoint, and the inference server is GPU-bound on KV-cache memory and batch occupancy.
Embeddings
An embedding is a dense vector that captures meaning: vectors close together mean similar things. You compute them once at ingest, then similarity at query time is just a distance computation.2
Bi-encoder: embed once, compare cheaply
Why pre-compute? The cost of the alternative
| Approach | When the work happens | Cost per query |
|---|---|---|
| Bi-encoder (embed once) | Documents at ingest; query at search | Embed 1 query + a distance scan — cheap, scales |
| Cross-encoder (joint) | Every query×doc pair, at query time | O(corpus) forward passes — accurate but unscalable |
| Hybrid (this stack) | Bi-encoder first, cross-encoder on top-N | Cheap recall, then precision only where it pays |
Is An embedding is a fixed-length dense vector representing a chunk of text such that semantic similarity maps to vector proximity (cosine or dot product).
Why it exists Keyword match misses meaning (“car” vs “automobile”). Embeddings let you search by what text means, and reduce search to a fast distance computation.
Like (world) Placing books by topic on a map, not alphabetically. Once shelved by meaning, finding “things like this one” is just looking nearby.
Like (code) A pre-built index vs a full table scan: you pay the indexing cost once at write time so reads stay cheap. The embedding model is the index function.
✓ Dimensions cost storage, memory, and ANN latency at scale. Match the model’s dimension to your recall need and budget — bigger is not free and rarely linear in quality.
✓ Query and corpus must share the same model. Swapping it means re-embedding and re-indexing the entire corpus — a migration, not a config change.
📥 Memory rule: Embeddings turn meaning into position. Pre-compute the corpus once; embed only the query at runtime — and never mix embedding models across query and index.
Memory check
- What does proximity in embedding space mean? → semantic similarity — near vectors mean similar things, so similarity becomes a distance computation
- Why is a bi-encoder used for first-stage retrieval? → it embeds each doc independently, so the corpus is pre-computed; query time is one embed + a cheap scan
- What breaks if you change the embedding model? → query and corpus must match — a swap forces re-embedding and re-indexing the whole corpus
M2 — What is an embedding, and why do you pre-compute them at ingest instead of at query time?
Hit these points: an embedding is a dense vector that captures meaning, so vectors close in the space mean similar things and similarity becomes a distance computation → a bi-encoder embeds each document once, independently, so you can pre-compute and index the whole corpus ahead of time → at query time you only embed the query and compare vectors, which is cheap → the alternative, scoring every query-document pair jointly (a cross-encoder), is far more accurate but O(corpus) per query and impossible to run over millions of docs at interactive speed → so the architecture splits the work: cheap pre-computed bi-encoder for first-stage retrieval, expensive cross-encoder only on the small reranked top-N.
This track is the infra/ops view of embeddings — serving, indexing cost, and scale. For the context-engineering angle (how embeddings shape what enters the prompt), see Embeddings, Vector Indexes (HNSW/IVF/PQ) & Cost, and for how you measure retrieval quality, RAG Evaluation: recall@k, RAGAS & Observability.
Vector Databases & ANN
A vector DB indexes embeddings for approximate nearest-neighbor search at scale. Exact k-NN is O(n) per query and collapses; ANN trades a little recall for large speed and memory wins.3
Exact vs approximate — why ANN exists
The two ANN families and their knobs
| Index | How it searches | The recall knob & trade |
|---|---|---|
HNSW (graph) | Layered proximity graphs; greedy descent, logarithmic hops |
|
IVF (clustering) | Partition into cells; probe only the nearest few |
|
Exact (flat) | Brute-force scan of all vectors | No knob — perfect recall, O(n), small corpora only |
The one trade you always tune
effor HNSW, nprobe for IVF) slides you along recall↔latency; build-time degree (M) and quantization trade memory. There is no setting that maximizes all three.3Is A vector DB stores embeddings and serves ANN similarity search with metadata filtering, CRUD, sharding, and replication — the serving substrate retrieval reads from.
Why it exists A flat array + brute-force similarity works as a demo but collapses on latency, freshness, and multi-tenancy. A vector DB makes search sub-linear and operable.
Like (world) A library’s card catalog: you don’t walk every shelf, you follow an index that jumps you near the right section — accepting it occasionally points you one shelf off.
Like (code) A B-tree index on a SQL column: it converts a full scan into a guided lookup. ANN is the same idea for high-dimensional vectors, but approximate by design.
✓ ANN is approximate — it can miss a true neighbor. You buy recall back with the search knob, paying latency for it. Measure recall@k; don’t assume it.
✓ If embeddings fit beside your OLTP data and volume is modest, pgvector in Postgres keeps one store you already operate. Reach for a dedicated system when scale, QPS, or hybrid search force it.
📥 Memory rule: A vector DB trades a little recall for
large speed & memory wins. The search knob (ef/nprobe)
is the dial — and the reranker can only re-order what it returned.
Memory check
- Why doesn't exact k-NN scale? → it's O(n) per query — every query scans the whole corpus, which is fatal past a few hundred thousand vectors at interactive latency
- What does the HNSW
ef/ IVFnprobeknob trade? → recall against latency — a wider search finds more true neighbors but costs more time - Can a reranker fix low first-stage recall? → no — it only re-orders the top-K it was given; a doc the ANN search missed is gone
M3 — Why can’t you just run exact nearest-neighbor search over your embeddings, and what does ANN trade away?
Hit these points: exact k-NN compares the query against every stored vector, so it is
O(n) per query and does not scale past a few hundred thousand vectors at interactive latency
→ ANN indexes (HNSW, IVF) build a structure that searches only a fraction of the
corpus, turning O(n) into roughly logarithmic or cluster-bounded work → the trade is
recall: ANN may miss a true neighbor, so you tune a knob (HNSW ef, IVF
nprobe) that buys recall back at the cost of latency and compute → there is
no free lunch: higher recall means a wider search means more latency, and the reranker can
only re-order what the first stage returned, never recover a doc it missed.
Retrieval practice — test the three modules
Q1. In the standard RAG request path, the hops occur in which order?
- Reranker first, then embed the query, then run the vector search over the corpus
- Inference server first, then gateway, then embed, then a vector similarity search
- Embed the query, vector-DB ANN search, rerank top-K, gateway, then inference
- Gateway first, then inference, then embedding, then a final reranking of results
Q2. Why do you pre-compute document embeddings once at ingest time?
- A bi-encoder embeds each doc alone, so the corpus indexes offline and queries stay cheap
- Because embeddings expire quickly and must be refreshed before every single user query
- So the reranker can skip the cross-encoder stage and score every pair at query time
- To let the model gateway cache the vectors and avoid calling the inference server later
Q3. Exact k-NN search over a large embedding corpus does not scale because it…
- Loses recall as the corpus grows, so it misses most of the true nearest neighbors
- Needs a graph index that becomes too large to hold in memory past a few thousand rows
- Returns approximate results that drift further from correct with every new insert
- Compares the query to every stored vector, making it O(n) per query at any size
Q4. Raising the HNSW ef (or IVF nprobe) search knob will…
- Shrink memory use and latency together while leaving the recall rate exactly the same
- Raise recall by widening the search, at the cost of higher per-query latency and compute
- Let the reranker recover documents the first-stage ANN search had already missed
- Convert the approximate index back into an exact scan with perfect recall and no cost
Q5. The model gateway is best described as the stack's…
- The component that turns query text into the dense vector used for similarity search
- The GPU process that runs the forward pass and manages the KV cache during decoding
- Cost and reliability chokepoint: auth, routing, rate limits, caching, and spend control
- The cross-encoder that re-scores the candidate set returned by the vector database tier
Interview — pick your bar
Answer out loud in ~60s, then reveal. Core = recall · Senior = trade-offs & failure modes · Staff = synthesis under ambiguity · System Design = open design round (a different axis, not a harder level).
Name the hops a query crosses from text to streamed answer, in order.
What is an embedding, and what does proximity in the vector space mean?
What does a vector database give you over a flat array of vectors plus a similarity loop?
Why is exact nearest-neighbor search a non-starter at scale, and what replaces it?
Where does latency concentrate in this stack, and how do you find the dominant hop?
Why is the model gateway the reliability and cost chokepoint, and what belongs in it?
A reranker can only re-order what vector search returned. Why does that constrain the whole pipeline?
What is the KV cache, and why does it dominate GPU memory during inference?
What does continuous (in-flight) batching buy you over static batching, and what's the trade?
The same retrieval corpus, but answer quality differs between two index configs. How do you reason about it before touching the model?
ef/nprobe too low), too-small K, or chunking that split the answer → if recall is fine but ranking is poor, it's the reranker or the assembly order, not retrieval → only after retrieval is sound do you look at the prompt or model → the principle: don't tune the expensive end of the pipeline to compensate for a cheap-end recall gap — fix it where it's caused."We'll just add a bigger model and a longer context — that fixes quality." Tear this apart as a system design.
- Clarify scope: QPS, corpus size, latency SLO, freshness, tenant isolation, and the cost of a wrong answer vs a slow one.
- Retrieval half: embed the query (cache popular embeddings) → ANN search with a tenant_id metadata pre-filter → rerank the top-K with a cross-encoder sized to the budget.
- Serving half: assemble prompt + passages → model gateway (auth, per-tenant rate limit, route, response-cache check) → inference server (KV-cache paging, continuous batching, streaming).
- Name the bottleneck at each hop: ANN recall vs latency, gateway as cost/reliability chokepoint, KV memory capping batch size.
- Build-vs-buy: pgvector vs a dedicated vector DB, hosted vs self-served inference — decide from measured scale, not preference.
- Measure & degrade: per-hop p95, cost per query, recall@k, cache hit ratio; graceful degradation when a provider fails.