ML Systems: Deployment Patterns, Feature Stores, Model Serving, Vector Databases
"Developing and deploying ML systems is relatively fast and cheap, but maintaining them over time is difficult and expensive." — D. Sculley et al., Hidden Technical Debt in Machine Learning Systems, NeurIPS 2015
Summary: A production ML system is mostly not the model. It is the data checks, feature pipelines, feature store, training pipeline, registry, serving tier, rollout machinery and monitoring around a small piece of learned code, and each of them has system-design decisions with numbers attached. Focus: The lifecycle and MLOps levels, hidden technical debt, training-serving skew, feature stores (offline/online, entity keys, TTL, point-in-time correctness), batch and streaming features, data validation, model registry and lineage, batch/online/streaming/edge inference, shadow/canary/A/B/bandit/champion-challenger rollouts, model servers (Triton, KServe, TF Serving, TorchServe, Seldon, BentoML, vLLM), dynamic batching and GPU utilisation, caching and autoscaling, LLM serving and RAG, vector databases and ANN indexes (HNSW, IVF-PQ, DiskANN), drift monitoring, responsible ML, MLOps CI/CD and cost, with Go and Laravel code and a worked recommendation design. Learning goal: Draw the full path from raw event to served prediction for a real product, put a latency and cost number on every box, say where skew, leakage, drift and silent failure enter, and pick the rollout, serving and retrieval technology for each with a reason.
This chapter sits in the Domain Systems group next to Search Systems (scoring, BM25 and learning-to-rank, which this page links instead of re-teaching) and Feeds. It treats ML as a system-design problem, not a modelling one: no gradient maths, plenty of queues, caches and budgets. Mechanics that other chapters own are linked in one sentence: stream windows and watermarks in Stream Processing, batch vs stream architectures in Big Data Architectures, pgvector internals in Vector Search & pgvector, the hands-on Go RAG build in RAG & LLM Apps in Go, SSE in Real-Time Communication, Kubernetes in Containers & Kubernetes, and p99 arithmetic in Latency Budgets & Tail Latency.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why ML systems rot faster than other code | Why it exists, Hidden technical debt |
| Sculley 2015, Rules of ML, MLOps levels, HNSW, FAISS, DiskANN | Where it comes from |
| Lifecycle, skew, feature store, point-in-time joins | Lifecycle, Skew, Feature store, Point-in-time |
| Feature pipelines, backfills, data validation | Feature pipelines, Data validation |
| Registry, lineage, reproducibility | Model registry |
| Batch, online, streaming, edge inference | Deployment modes |
| Shadow, canary, A/B, bandits, blue/green | Rollouts |
| Triton, KServe, TF Serving, TorchServe, Seldon, BentoML, vLLM | Model serving |
| Batching, GPUs, quantisation, caching, cold starts | Batching, Caching and autoscaling, Feature fetching |
| LLMs, prompt caching, RAG, guardrails | LLM serving, RAG |
| Embeddings, HNSW, IVF, PQ, DiskANN, filters, hybrid search | Vector databases, ANN indexes, Filtering and hybrid |
| Drift, delayed labels, feedback loops | Monitoring |
| Bias, SHAP, PII | Responsible ML |
| CI/CD, Airflow, Kubeflow, Dagster, cost | MLOps CI/CD, Cost |
| Knobs and numbers | Mechanics |
| Code | Go, Laravel |
| Fixes for the classic failures | Solving the classic problems |
| A full recommendation-service design | Worked design |
| Which option to pick | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The lifecycle, box by box.
| Stage | In plain words | Typical product | What goes wrong |
|---|---|---|---|
| Data validation | Check inputs before they become features | Great Expectations, TFDV | Silent schema or unit change upstream |
| Feature pipelines | Turn raw events into model inputs | Spark, dbt, Flink, Feast transformations | Pipeline jungle; different code for training and serving |
| Feature store | One definition, offline history + online latest | Feast, Tecton, Hopsworks, Vertex AI Feature Store | Leakage from naive joins; stale online values |
| Training | Fit the model on point-in-time correct data | Kubeflow Pipelines, Airflow, Dagster, SageMaker | Not reproducible: unknown data snapshot or seed |
| Evaluation | Gate: is it better than the champion, on which slices? | MLflow evaluate, custom | Average improves, one segment collapses |
| Model registry | Versions, lineage, aliases like @champion | MLflow Model Registry, Vertex AI, SageMaker | "Which model made this prediction?" has no answer |
| Serving | Answer predictions under a latency budget | Triton, KServe, TF Serving, BentoML, vLLM | GPU at batch 1; no fallback; cold starts |
| Monitoring | Watch inputs, outputs, freshness, latency, cost | Evidently, WhyLabs, Prometheus | Model degrades silently; labels arrive weeks later |
| Retraining | Close the loop on schedule or on drift | Pipeline trigger, continuous training (CT) | Feedback loop retrains on the model's own choices |
Deployment and rollout patterns.
| Pattern | Who sees the new model | Learns | Use when |
|---|---|---|---|
| Batch scoring | Everyone, from a precomputed table | Offline metrics only | Scores change slowly; daily churn or lead scores |
| Online inference | Each request, synchronously | Latency, live behaviour | Input known only at request time (fraud, ranking) |
| Streaming inference | Each event, asynchronously | Throughput, lag | Score every transaction or click off a Kafka topic |
| Edge inference | The device, offline | On-device metrics | Privacy, no network, sub-10 ms (keyboard, camera) |
| Shadow deployment | Nobody; copy of traffic, logged | Latency, errors, score diff | First production contact for a new model |
| Canary | 1-10%, increasing | Health under real load | Every rollout of a model server or version |
| A/B test | Random sticky split | Business metric, with significance | Deciding whether the model is actually better |
| Multi-armed bandit | Split adapts to reward | Optimises while learning | Many arms, short-lived content (headlines, promos) |
| Champion/challenger | Champion serves, challenger competes | Comparison on the same traffic | Standing process for every retrain |
Serving and retrieval in one table.
| Concern | Knob | Product example | Number to remember |
|---|---|---|---|
| Throughput on GPU | Dynamic batching delay and size | Triton max_queue_delay_microseconds, preferred_batch_size | A few ms of delay can multiply throughput (measure it) |
| LLM memory | KV-cache paging, continuous batching | vLLM PagedAttention | Paper: 2-4x throughput at the same latency |
| Repeated prompts | Prefix (prompt) caching | vLLM Automatic Prefix Caching | Reuses KV blocks for an identical prefix |
| Feature fetch | One round trip per request | Redis HMGET, DynamoDB BatchGetItem | Budget a few ms of the total |
| ANN recall vs latency | Search width | pgvector hnsw.ef_search (default 40), ivfflat.probes (default 1) | Raise until recall@k meets the target |
| Filtered vector search | Iterative scan / filter-aware graph | pgvector hnsw.iterative_scan, Qdrant payload index | Post-filtering can return fewer than k |
| Billion-scale ANN | Graph on SSD | DiskANN, Milvus DISKANN | Paper: 1B points, 64 GB RAM, under 3 ms mean |
The picture is the loop the rest of the page walks through. The dashed box in the middle is the model code; Sculley et al. drew it as "the small black box in the middle" of a much larger system, and the arrows around it are where the engineering effort goes.
Why it exists
Ordinary software fails loudly: a null pointer, a 500, a failed test. An ML system usually fails quietly: it keeps returning numbers, they are just worse. The causes are not in the code you can diff but in the data: an upstream team changes a unit, a feature is computed one way in Spark and another way in PHP, the world changes after a holiday, the model starts training on its own recommendations. Sculley et al. put it as "Hidden debt is dangerous because it compounds silently." The architecture in this chapter exists to make those failures visible and cheap to fix.
| A plain service | An ML service |
|---|---|
| Behaviour is defined by code | Behaviour is defined by code + data + training config |
| A test proves a function | Tests prove the code; monitoring proves the model still fits the world |
| Bugs throw errors | Bugs produce plausible wrong numbers |
| One artefact: the binary | Three artefacts: code, data snapshot, model weights |
| Deploy once, works until changed | Degrades without any deploy (drift) |
| Latency mostly I/O | Latency often compute-bound on GPUs; batching matters |
| Rollback = previous binary | Rollback = previous model and the features it expects |
| Inputs come from the request | Inputs come from a feature store that must match training |
The analogy we reuse on this page: a restaurant kitchen. The model is the recipe. Features are the mise en place, the prepared ingredients; the feature store is the walk-in fridge with labelled, dated containers (offline: every batch ever prepared with its date; online: the tray on the pass with today's prep). Training-serving skew is a recipe tested with fresh herbs and served with dried ones. Point-in-time correctness is tasting yesterday's dish with yesterday's ingredients, not today's. The registry is the recipe book with versions and who wrote them. Shadow deployment is a new chef cooking every order in parallel while only the old chef's plates leave the kitchen. Drift is the supplier quietly changing the tomatoes.
Three common misunderstandings, up front
- "The hard part is the model." In mature systems the model is a small part of the code; Sculley et al. estimate a mature system "might end up being (at most) 5% machine learning code and (at least) 95% glue code". The hard part is data, features and operations.
- "If offline accuracy is good, production will be good." Offline evaluation uses features computed by the training pipeline on historical data; production uses features computed by the serving path on live data. Any difference between them is skew, and Google's Rules of ML spend a whole section on it.
- "Vector search is exact search, only faster." Approximate nearest neighbour indexes trade recall for speed. pgvector's README says it directly: an approximate index "trades some recall for speed. Unlike typical indexes, you will see different results for queries after adding an approximate index."
Where it comes from
| Year | Source | What it added |
|---|---|---|
| 2015 | Sculley et al., Hidden Technical Debt in Machine Learning Systems, NeurIPS | The vocabulary: entanglement, CACE, undeclared consumers, data dependencies, feedback loops, glue code, pipeline jungles, configuration debt |
| 2016 | Malkov & Yashunin, HNSW (arXiv 1603.09320) | Multi-layer proximity graphs with "logarithmic complexity scaling"; the default ANN index in most vector databases today |
| 2017 | Johnson, Douze, Jégou, Billion-scale similarity search with GPUs (FAISS, arXiv 1702.08734) | GPU brute force, IVF and "compressed-domain search based on product quantization" |
| n.d. (web guide) | Martin Zinkevich, Google, Rules of Machine Learning | Engineering rules: launch without ML first, log features at serving time, measure training/serving skew |
| 2019 | Subramanya et al., DiskANN, NeurIPS | SSD-resident graph index: a billion points on one 64 GB machine |
| 2024 (last reviewed) | Google Cloud, MLOps: Continuous delivery and automation pipelines in machine learning | MLOps levels 0, 1, 2; CI, CD and continuous training (CT); feature store as a pipeline component |
| 2023 | Kwon et al., PagedAttention / vLLM, SOSP 2023 (arXiv 2309.06180) | KV-cache paging for LLM serving; 2-4x throughput at the same latency |
Feature stores grew out of the same pain: Google's MLOps guide defines one as "a centralized repository where you standardize the definition, storage, and access of features for training and serving" that "needs to provide an API for both high-throughput batch serving and low-latency real-time serving". Open-source Feast, managed Tecton and Hopsworks, and the cloud vendors' stores (Vertex AI Feature Store, SageMaker Feature Store) all implement that sentence. The book-length treatment is Chip Huyen's Designing Machine Learning Systems (O'Reilly, 2022), cited here as background reading, not quoted.
The debt catalogue from Sculley et al., with the system-design fix.
| Debt item | What it means | Architecture answer on this page |
|---|---|---|
| Entanglement / CACE | "Changing Anything Changes Everything": features are not independent | Version everything; evaluate per slice; shadow before rollout |
| Correction cascades | Model B learns a fix on top of model A | Feature in one model, or a separate model; registry lineage shows the chain |
| Undeclared consumers | Other systems silently read your predictions | Serve through an API with auth; log consumers; no shared prediction tables without contracts |
| Unstable data dependencies | Input signals change under you | Versioned feature definitions; data validation at the boundary |
| Underutilized data dependencies | Features that add little but can break things | Leave-one-feature-out evaluation; delete features |
| Feedback loops (direct, hidden) | The model influences its own future training data | Exploration traffic, holdout groups, bandits, logging propensities |
| Glue code, pipeline jungles | Most code moves data in and out of packages | Feature store and orchestrated pipelines with one definition |
| Dead experimental codepaths | Old if branches for experiments | Rollout flags with expiry; registry aliases instead of code branches |
| Configuration debt | Config lines outnumber code lines | Configs reviewed and diffed like code; pipeline parameters in the registry |
| Changes in the external world | Fixed thresholds, drift | Monitoring with alerts; learned thresholds; continuous training |
| Monitoring and testing debt | Unit tests are "not sufficient to provide evidence that a system is working as intended" | Prediction bias, action limits, upstream SLOs (Sculley's three starting points) |
| Reproducibility debt | Cannot re-run training and get the same model | Data snapshot ids, seeds, container digests in lineage |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a flow, real scenarios, how products provide it, and the fix.
The ML lifecycle and MLOps levels Must-know
In plain words: an ML system is a loop: collect data, make features, train, evaluate, register, serve, watch, retrain. MLOps is doing that loop with the same automation and discipline as CI/CD for code.
Common misunderstanding: "MLOps means deploying a model." Deploying a model is the last step of level 0. Google's guide says the real artefact at higher levels is the pipeline: "CD is no longer about a single software package or a service, but a system (an ML training pipeline) that should automatically deploy another service (model prediction service)."
Definition: Google Cloud's MLOps guide defines MLOps as "an ML engineering culture and practice that aims at unifying ML system development (Dev) and ML system operation (Ops)" and describes three maturity levels: level 0 (manual process), level 1 (ML pipeline automation, continuous training), level 2 (CI/CD pipeline automation). It adds a property that plain software does not have: "CT is a new property, unique to ML systems, that's concerned with automatically retraining and serving the models."
Level 0 (manual) Level 1 (pipeline + CT) Level 2 (CI/CD of pipelines)
1 notebook extracts data scheduler or drift alert triggers PR to pipeline code
2 trains on a laptop pipeline: validate -> features -> train CI: unit tests, data tests, build images
3 emails a model.pkl to engineering evaluate vs champion; register v8 CD: deploy the pipeline to prod
4 engineer wraps it in a Flask app deploy v8 to serving if gate passes pipeline runs CT as in level 1
5 no monitoring; retrain "when someone notices" monitoring feeds the trigger monitoring + rollback automatedReal scenario: a churn model retrained by hand twice a year (level 0) that silently decays after a pricing change; a fraud model retrained nightly by an Airflow DAG with a precision gate (level 1); a platform team with many models whose pipeline code passes through CI and is promoted across environments (level 2).
What provides it:
| Product | Role in the loop | Note |
|---|---|---|
| Kubeflow Pipelines | Pipeline definition and execution on Kubernetes | Containerised steps, artefact tracking |
| Apache Airflow | General DAG scheduler | Most common orchestrator for feature and training jobs |
| Dagster | Asset-oriented orchestration | Models features and models as data assets with lineage |
| MLflow | Tracking, registry, evaluation | Open source; managed on Databricks |
| Vertex AI / SageMaker | Managed pipelines, registry, endpoints | Cloud lock-in for less operations |
Fix / how to use it: aim for level 1 before your second model: the training pipeline is code in Git, it runs on a schedule or trigger, it validates data, gates on evaluation and writes to a registry. Treat level 2 as the goal for a platform, not for a single team's first model.
Hidden technical debt Must-know
In plain words: ML systems collect debt that is not in the code: in data dependencies, in who reads the predictions, in loops between the model and the world.
Common misunderstanding: "We refactor the code regularly, so we have no debt." Sculley et al.: "This debt may be difficult to detect because it exists at the system level rather than the code level."
Definition: ML-specific technical debt is the long-term maintenance cost created by boundary erosion, entanglement, hidden feedback loops, undeclared consumers, data dependencies, configuration issues, changes in the external world and system-level anti-patterns (the paper's abstract lists exactly these).
Team A (search ranking model) Team B (ads) World
1 publishes ranking scores to a table
2 quietly uses the score as a feature (undeclared consumer)
3 retrains; score scale changes 0..1 -> logits
4 ads CTR model degrades; no error anywhere
5 users click different results (hidden feedback loop)
6 next training set reflects ads changes, ranking drifts againReal scenario: a product-numbering migration where the old id stays as a feature and is deleted a year later (the paper's own example: "This will not be a good day for the maintainers of the ML system"); a threshold tuned once by hand that becomes wrong after a retrain; two recommenders on the same page influencing each other's clicks.
What provides it (mitigations):
| Debt | Mitigation | Product feature |
|---|---|---|
| Undeclared consumers | Predictions only through an authenticated API | API gateway auth; KServe/Seldon endpoints |
| Unstable inputs | Versioned features with owners | Feast feature views, Tecton feature definitions |
| Data dependency tracking | Lineage graph | MLflow lineage, Dagster assets, OpenLineage |
| Dead experimental paths | Flags with an owner and expiry | Laravel Pennant, LaunchDarkly, registry aliases |
Fix / how to use it: keep a debt register per model (features, consumers, thresholds, owners); run leave-one-feature-out evaluations; never let a prediction leave your service without a contract.
Training-serving skew Must-know
In plain words: the model sees different inputs in production than it saw in training, so it behaves worse than your offline numbers said.
Common misunderstanding: "Skew is drift." Drift is the world changing over time; skew is your system producing different features for the same moment. Skew exists on day one; drift appears later.
Definition: Rules of ML: "Training-serving skew is a difference between performance during training and performance during serving. This skew can be caused by: A discrepancy between how you handle data in the training and serving pipelines. A change in the data between when you train and when you serve. A feedback loop between your model and your algorithm."
Training (Spark, nightly) Serving (PHP, per request)
1 orders_7d = count(orders) per UTC calendar day orders_7d = count where created_at > now() - 168h, local TZ
2 missing country -> "UNK" bucket missing country -> null -> crashes encoder -> default 0
3 price in cents price in euros (new API)
4 model learns orders_7d in [0, 40] sees 37 for a user who has 5 by the training definition
5 offline AUC 0.81 live AUC 0.71; no error loggedReal scenario: a recommendation model whose "time since last visit" is computed in seconds offline and in milliseconds online; a fraud model trained on a joined table that changed after training (Rules of ML #31: "the data in the table may change"); text normalised with a different tokenizer version at serving time.
What prevents it:
| Technique | How | Product |
|---|---|---|
| One feature definition for both paths | Define once; offline and online read the same logic | Feast feature views, Tecton, Hopsworks |
| Log features at serving time | Train on what serving saw (Rules of ML #29) | Prediction log to Kafka/warehouse |
| Re-use code | Same library in both pipelines (Rules of ML #32) | Shared feature package, on-demand transforms |
| Measure skew | Compare logged vs recomputed features | TFDV skew detection, Evidently drift reports |
Fix / how to use it: log the exact feature vector with every prediction (the Go gateway's Event, the Laravel prediction_log), and run the skew query in the SQL snippet daily. Rules of ML #29: "The best way to make sure that you train like you serve is to save the set of features used at serving time, and then pipe those features to a log to use them at training time."
Feature store: offline store, online store, entity keys, TTL Must-know
In plain words: one place where each feature is defined once and stored twice: the full history for training, and the latest value per user or item for serving.
Common misunderstanding: "A feature store is a Redis cache." Redis may be the online half. Without the offline half with history, the shared definitions and the materialization job, you have a cache, and caches do not give you point-in-time correct training data.
Definition: Feast: "Feast uses online stores to serve features at low latency. Feature values are loaded from data sources into the online store through materialization ... for each entity key, only the latest feature values are stored. No historical values are stored." The offline store is "an interface for working with historical time-series feature values", used for "Building training datasets from time-series features" and "Materializing (loading) features into an online store". An entity key (Feast join_keys, e.g. driver_id, user_id) is the primary key that features hang off. A TTL bounds how old a value may be and still count.
Pipelines Offline store (BigQuery) Online store (Redis) Serving
1 batch job writes 42@20:00=5 row (42, 20:00, 5) appended
2 materialize 20:00..21:00 HSET fv:user_ctr:42 orders_7d 5
3 stream job: 42 bought @20:07 push to offline push: orders_7d 6 (push source)
4 HMGET fv:user_ctr:42 -> 6
5 training at 02:00 point-in-time join reads historyReal scenario: ride-hailing driver stats (trips today, acceptance rate) served to a dispatch model; a bank's "transactions in the last hour" for card fraud; e-commerce user embeddings and item popularity for ranking; the same features reused by three teams instead of re-implemented three times.
What provides it:
| Product | Offline store | Online store | Notes |
|---|---|---|---|
| Feast (open source) | BigQuery, Snowflake, Redshift, Spark, Postgres, files | Redis, DynamoDB, Bigtable, Postgres, others | Library + optional feature server; you run the infra |
| Tecton (managed) | Managed on the warehouse/lake | Managed (DynamoDB or Redis backed) | Batch, streaming and real-time feature definitions |
| Hopsworks | Offline feature groups (lakehouse tables) | RonDB online | Feature store plus model registry ("connected by a shared feature store and model registry") |
| Vertex AI / SageMaker Feature Store | BigQuery / S3 | Managed online serving | Cloud-native, IAM-integrated |
| DIY | Warehouse tables with event timestamps | Redis hashes or DynamoDB items | Fine for one or two models; you own consistency |
Fix / how to use it: pick the entity keys first (they are your join and shard keys), give every feature an event timestamp, an owner and a TTL, and keep online reads to one round trip per request (Redis HMGET, DynamoDB BatchGetItem). Redis as a data structure server is covered in Redis.
Point-in-time correctness Must-know
In plain words: every training example must see the feature values as they were at that example's moment, never later ones.
Common misunderstanding: "Join labels to the feature table on user id." That gives every row the latest value, so January's examples are trained with December's knowledge. Offline metrics look great; production does not. This is label (data) leakage.
Definition: Feast: "Feast is able to reproduce the state of features at a specific point in the past ... Feast will scan backward in time from the entity dataframe timestamp up to a maximum of the TTL time specified." With filter_by_created_timestamp=True it also adds "a created_timestamp <= entity_timestamp condition", which keeps "backfilled values from leaking into training data".
Feature rows for driver d1 Label row Naive join As-of join (TTL 2h) + created filter
1 08:00 trips=3 (written 08:00) 07:00 -> label 0 25 none (before data) none
2 12:00 trips=9 (written 12:00) 13:00 -> label 1 25 9 9
3 14:00 trips=11 (written next day!) 15:00 -> label 1 25 11 (backfill leaks) 9
4 20:00 trips=25 (written 20:00) 23:00 -> label 0 25 none (3h > TTL) none-- As-of join in PostgreSQL: newest row at or before the label, inside the TTL.
SELECT i.impression_id, i.clicked, f.orders_7d
FROM impressions i
LEFT JOIN LATERAL (
SELECT orders_7d FROM user_features uf
WHERE uf.user_id = i.user_id
AND uf.event_ts <= i.shown_at
AND uf.event_ts > i.shown_at - interval '2 hours'
AND uf.created_ts <= i.shown_at
ORDER BY uf.event_ts DESC LIMIT 1
) f ON true;Real scenario: a credit model that used "number of late payments" joined at today's value (it learned the future); a CTR model where item popularity was joined as of training day, so new items looked unpopular; a backfill that corrected a bug and silently leaked corrected values into old rows.
What provides it:
| Product | Point-in-time API | Note |
|---|---|---|
| Feast | get_historical_features(entity_df, features) | TTL relative to each entity row; optional filter_by_created_timestamp |
| Tecton | get_features_for_events style historical retrieval | Managed as-of joins |
| Spark / Databricks | As-of joins, window functions | You write the logic |
| PostgreSQL | LEFT JOIN LATERAL ... ORDER BY event_ts DESC LIMIT 1 | Needs an index on (entity, event_ts) |
| Snowflake / BigQuery | ASOF JOIN (Snowflake), window + filter | Engine-specific |
Fix / how to use it: store history, never only latest; join "as of"; add the created-timestamp condition when backfills exist. The Go package pit reproduces the four rows above in its tests (Go).
Batch features, streaming features and backfills Important
In plain words: some features are recomputed daily from the warehouse, some update within seconds from an event stream, and some are computed at request time from the request itself.
Common misunderstanding: "Everything should be real time." Streaming features cost a stream processor, state, exactly-once concerns and on-call. Rules of ML #8 asks first: "Know the freshness requirements of your system. How much does performance degrade if you have a model that is a day old?"
Definition: batch features are computed on a schedule over historical data (Spark, dbt, BigQuery); streaming features are computed continuously from events with windowed aggregations (Flink, Kafka Streams, Spark Structured Streaming; mechanics in Stream Processing); on-demand features are computed at request time from request data (Feast on-demand feature views). A backfill recomputes historical feature values for a new or fixed definition so training has history.
t Event Batch feature (daily 02:00) Streaming feature (Flink, 1-min window)
1 10:00 user 42 views 5 items views_today = (yesterday's) views_10min = 5
2 10:05 user 42 adds to cart cart_adds_1h = 1 -> online store in ~seconds
3 02:00+1 nightly job views_today = 37 -> offline + online
4 later new feature "views_30d" backfill 2 years of history so training has 30-day valuesReal scenario: session-intent features for a shop (minutes matter: streaming); account age and lifetime value (daily is fine: batch); "amount vs user's average" computed from the request amount and a stored average (on-demand); a 2-year backfill when a feature is added.
What provides it:
| Feature type | Compute | Store path | Freshness |
|---|---|---|---|
| Batch | Spark, dbt, BigQuery SQL | Offline, then materialize to online | Hours to a day |
| Streaming | Flink, Kafka Streams, Spark Structured Streaming | Push to online and offline (Feast push source) | Seconds |
| On-demand | Request-time Python or Go transform | Not stored, or logged | Request time |
| Backfill | Batch job over history | Offline only (then materialize latest) | n/a |
Fix / how to use it: default to batch; add streaming only for features whose freshness measurably moves the metric; when a stream feature exists, write it to both stores, and backfill it from the raw log so training has the same definition (the Kappa idea, see Big Data Architectures).
Data validation Important
In plain words: check the data like you test code: schema, types, ranges, null rates, distributions, before it trains or serves a model.
Common misunderstanding: "The upstream team has tests." Their tests check their code; your model depends on the meaning and distribution of their data. Sculley et al.: "If data replaces code in ML systems, and code should be tested, then it seems clear that some amount of testing of input data is critical."
Definition: data validation is a set of declared expectations evaluated on every batch (and sampled online): schema (columns, types), value constraints (ranges, enums, uniqueness), and distribution checks (drift vs a reference). Great Expectations calls them Expectations; TensorFlow Data Validation (TFDV) infers a schema from statistics and detects anomalies, drift and training-serving skew.
Pipeline step Check (expectation) Outcome
1 load orders partition column price exists, type float pass
2 price between 0 and 100000 FAIL: 3% rows = price * 100 (cents bug)
3 stop pipeline no training on this partition; alert owner
4 model keeps serving v7 (champion untouched)Real scenario: a currency field switched from cents to euros; a country column that suddenly has 40% nulls after a mobile release; an enum gaining a new value the encoder has never seen.
What provides it:
| Product | Style | Note |
|---|---|---|
| Great Expectations (GX Core) | Declarative expectation suites in Python | Runs in Airflow/Dagster steps |
| TFDV | Schema inference + anomaly, drift and skew detection | Part of TFX |
| Evidently | Data quality and drift test suites | Also monitoring dashboards |
| dbt tests | SQL tests on warehouse models | not_null, accepted_values, custom |
| Pandera / Deequ | DataFrame schemas (Python / Spark) | Library-level checks |
Fix / how to use it: validate at three boundaries: on ingestion, before training (block the run), and on a sample of serving features (alert). Keep the schema in Git next to the feature definitions.
Model registry, versioning, lineage and reproducibility Must-know
In plain words: a catalogue of every model version with where it came from and which one is live, so you can answer "which model made this prediction, trained on what?"
Common misunderstanding: "We keep model files in S3 with dates in the name." Files have no lineage, no stage, no approval, no link to the run, data and code that produced them.
Definition: MLflow: "A registered model has a unique name, contains versions, aliases, tags, and other metadata." "Each registered model version is linked to the MLflow run, logged model or notebook that produced it, enabling full reproducibility." "Model aliases allow you to assign a mutable, named reference to a particular version of a registered model", for example models:/MyModel@champion. Lineage is the graph data snapshot → features → run → model version → deployment. Reproducibility means re-running the pipeline with the same inputs gives an equivalent model, which needs data snapshot ids, code commit, container digest, hyper-parameters and seeds recorded.
Step Registry state (MLflow)
1 pipeline run r-981 trains on snapshot s-2026-11-20, commit a1b2c3
2 registers ctr version 8 (lineage: r-981, s-2026-11-20, a1b2c3) ctr: v7 @champion, v8 (no alias)
3 evaluation gate passes; set alias @challenger -> v8 ctr: v7 @champion, v8 @challenger
4 shadow + canary healthy; move @champion -> v8 ctr: v8 @champion, v7 (kept for rollback)
5 incident: move @champion -> v7; serving reloads by alias rollback in minutes, no rebuildReal scenario: an auditor asks why a loan was declined; a regression after retrain needs a one-command rollback; two teams argue about which features a model uses.
What provides it:
| Product | Versions | Stage/alias | Lineage |
|---|---|---|---|
| MLflow Model Registry | Yes | Aliases (@champion), tags | Run, logged model, dataset |
| Vertex AI Model Registry | Yes | Aliases, version default | Vertex pipelines metadata |
| SageMaker Model Registry | Model packages | Approval status | Pipeline lineage |
| Hopsworks | Yes | Tags | Tied to feature groups |
| Weights & Biases | Artifacts | Aliases | Run graph |
Fix / how to use it: serving resolves a model by alias, not by file path; every prediction log line carries the version; the registry entry links the feature view versions it expects, so a rollback also rolls back the features contract.
Deployment modes: batch scoring, online, streaming and edge inference Must-know
In plain words: you can compute predictions ahead of time for everyone, at request time for one, as events flow past, or on the user's device.
Common misunderstanding: "Real-time inference is always better." Precomputed scores are cheaper, simpler and faster to read; online inference only pays off when the input is known only at request time.
Definition: batch scoring runs the model over a table on a schedule and writes scores to a store the application reads; online inference answers a synchronous request within a latency budget; streaming inference consumes an event stream and emits scores to another stream or store; edge inference runs the model on the device (phone, browser, car) with on-device runtimes.
Mode Trigger Path Latency the user feels
1 Batch 02:00 cron warehouse -> Spark + model -> scores table -> Redis read: ~1 ms
2 Online HTTP/gRPC request gateway -> features -> model server -> response budget: 10-100 ms
3 Streaming Kafka event consumer -> features -> model -> topic/alert seconds (async)
4 Edge on-device input app -> on-device model (Core ML, TF Lite, ONNX) < 10 ms, works offlineReal scenario: nightly churn and lead scores (batch); fraud check during card authorisation, search ranking (online); scoring every payment event for later review, anomaly detection on IoT telemetry (streaming); keyboard suggestions, photo classification (edge).
What provides it:
| Mode | Common stack | Main cost |
|---|---|---|
| Batch scoring | Spark, BigQuery ML, Airflow + model library | Compute per run; stale between runs |
| Online inference | Triton, KServe, TF Serving, BentoML behind a gateway | Always-on capacity, GPUs |
| Streaming inference | Kafka + Flink or a consumer service calling a model server | Consumer lag, exactly-once concerns |
| Edge inference | TensorFlow Lite / LiteRT, Core ML, ONNX Runtime, ExecuTorch | Model size, device fragmentation, update rollout |
Fix / how to use it: start with batch if the score is per entity and changes slowly; move a model online only when the request carries information the batch run cannot know. Streaming inference uses the broker patterns from Kafka.
Safe rollouts: shadow, canary, A/B, bandits, blue/green, champion/challenger Must-know
In plain words: never switch all traffic to a new model at once; first let it watch, then let it serve a few, then let it compete.
Common misunderstanding: "A canary proves the model is better." A canary proves it is healthy (no errors, latency ok). Whether it is better needs an A/B test with a business metric and enough samples; whether it behaves the same needs shadow.
Definition: shadow deployment mirrors requests to the new model and logs its answers without returning them; canary routes a small, increasing share of traffic with automatic rollback on health metrics; A/B test randomly assigns users (sticky, usually by hashing the user id) to variants and compares a pre-registered metric; multi-armed bandit shifts traffic toward the arm with the better observed reward while still exploring (Sculley et al. note bandits as the "theoretically correct" answer to direct feedback loops); blue/green keeps two full environments and flips all traffic; champion/challenger is the standing process in which the current best model (champion) is continuously compared with candidates (challengers).
Day Stage Traffic to v8 Gate to continue
1 D0 shadow 0% (100% mirrored) p99 < 50 ms, error < 0.1%, score diff sane
2 D2 canary 5% -> 25% no SLO burn, no error spike (auto rollback)
3 D3 A/B 50%, sticky by user CTR +1.5% at p < 0.05 after N users
4 D17 promote 100%, alias @champion v7 kept warm one week for rollbackReal scenario: a new ranking model first runs in shadow to catch a 4x latency regression; a fraud model canaries on 5% of low-value transactions; headline variants on a news front page use a bandit because each headline lives only hours.
What provides it:
| Product | Shadow | Canary | A/B / bandit |
|---|---|---|---|
| KServe | Via Knative/Istio mirroring | canaryTrafficPercent on InferenceService | External |
| Seldon Core 2 | Experiments with mirror | Traffic splitting | Experiments |
| Istio / Envoy | mirror route | Weighted routes | Header-based routing |
| AWS SageMaker endpoints | Shadow variants | Production variants with weights | Variant weights |
| Application code | Gateway sampling (this page's Go and Laravel code) | Feature flag | Experiment platform, Pennant |
Fix / how to use it: shadow first, canary for health, A/B for value; log model version on every prediction; keep the previous champion loaded for fast rollback. KServe: "Apply model v2 with canaryTrafficPercent: 10" and "If the canary model is healthy/passes your tests, you can promote it by removing the canaryTrafficPercent field".
Model serving: the servers Must-know
In plain words: a model server loads model files, exposes REST/gRPC endpoints, batches requests, runs them on CPU or GPU and reports health and metrics.
Common misunderstanding: "Wrap the model in Flask." That works for a demo; it gives you no batching, no GPU scheduling, no model versioning, no standard protocol, and one Python process per model.
Definition: a model server is a long-running process that hosts one or more model versions, speaks a standard inference protocol (the Open Inference Protocol, also called KServe v2: POST v2/models/<model_name>[/versions/<model_version>]/infer, plus v2/health/ready), and implements scheduling (dynamic batching, multiple instances per GPU), model loading and warm-up.
Gateway Triton (GPU) Registry / storage
1 POST /v2/models/ctr/versions/8/infer (batch of 24 rows)
2 dynamic batcher: queue 3 ms, forms batch 32
3 instance_group: 2 instances on GPU 0
4 200 {outputs: [{data: [...]}]}
5 model v9 published model repository updated
6 load v9, run ModelWarmup, then report readyReal scenario: a vision model on GPUs behind Triton; a scikit-learn fraud model on CPUs in KServe with scale-to-zero for a low-traffic tenant; an LLM on vLLM's OpenAI-compatible server; a Python team shipping a BentoML service.
What provides it:
| Server | Strength | Protocols | Note |
|---|---|---|---|
| NVIDIA Triton Inference Server | Many frameworks (TensorRT, ONNX, PyTorch, TF, Python), dynamic batching, ensembles | HTTP/gRPC, Open Inference Protocol | GPU-first; Model Analyzer for tuning |
| KServe | Kubernetes InferenceService CRD, autoscaling, canary, scale to zero | Open Inference Protocol, OpenAI-compatible for LLMs | Runs Triton, vLLM, MLServer and others as runtimes |
| TensorFlow Serving | "flexible, high-performance serving system" for TF SavedModels | gRPC, REST | Version policies, batching |
| TorchServe | PyTorch handlers | REST, gRPC | Repository marked "Limited Maintenance": "no longer actively maintained" |
| Seldon Core 2 | "Kubernetes-native MLOps framework", pipelines, experiments | Open Inference Protocol (MLServer) | Inference graphs, Kafka-based pipelines |
| BentoML | "Python library for building online serving systems" | HTTP, gRPC | Adaptive batching, packaging to containers |
| vLLM | LLM serving: PagedAttention, continuous batching, prefix caching | OpenAI-compatible HTTP | See LLM serving |
Fix / how to use it: use a standard protocol so the gateway does not care which server sits behind it (the Go HTTPModel speaks the Open Inference Protocol); pick Triton for GPU throughput, KServe for Kubernetes operations, vLLM for LLMs; avoid new projects on TorchServe given its maintenance status. gRPC trade-offs are in gRPC & Protocol Buffers.
Latency vs throughput: dynamic batching, GPU utilisation, quantisation Must-know
In plain words: a GPU is fast at doing many rows at once and wasteful at doing one; batching trades a few milliseconds of waiting for many times more throughput. Quantisation makes each row cheaper.
Common misunderstanding: "GPU utilisation 100% means we are efficient." nvidia-smi utilisation says a kernel was running, not that the GPU did useful batched work. A GPU serving batch size 1 can look busy and still deliver a fraction of its throughput.
Definition: Triton: "Dynamic batching is a feature of Triton that allows inference requests to be combined by the server, so that a batch is created dynamically. Creating a batch of requests typically results in increased throughput." The delay knob: "the dynamic batcher will delay sending the batch as long as no request is delayed longer than the configured max_queue_delay_microseconds value". Quantisation (US spelling: quantization) stores weights and activations in fewer bits (FP16, BF16, INT8, FP8, INT4) to cut memory and compute, at some accuracy cost; vLLM lists "FP8, MXFP8/MXFP4, NVFP4, INT8, INT4, GPTQ/AWQ, GGUF".
t (ms) Requests arriving Batcher (max 8, delay 5 ms) GPU
1 0.0 r1 start timer
2 1.2 r2, r3 batch = 3
3 3.9 r4..r8 batch = 8 = max -> send now run batch 8 (~same time as batch 1)
4 4.1 r9 start timer
5 9.1 timer expired -> send batch of 1 run batch 1Real scenario: an image model that serves 4x more images per GPU after enabling dynamic batching with a 2 ms delay (measure your own; numbers vary per model); an INT8 quantised ranking model that fits on a cheaper GPU; a batcher delay set too high for a 20 ms budget that consumes a quarter of it.
What provides it:
| Layer | Knob | Product |
|---|---|---|
| Server-side batching | dynamic_batching { max_queue_delay_microseconds, preferred_batch_size }, max_batch_size | Triton |
| Queue policy | max_queue_size, default_timeout_microseconds, priority_levels | Triton |
| Instances | instance_group [{ count: 2, kind: KIND_GPU }] | Triton |
| LLM batching | Continuous batching, chunked prefill | vLLM |
| Client-side batching | Batcher with max size + max delay | This page's Go Batcher |
| Quantisation | TensorRT INT8/FP8, AWQ/GPTQ, ONNX Runtime quantization | Triton, vLLM, ONNX Runtime |
| Utilisation metrics | DCGM exporter (DCGM_FI_DEV_GPU_UTIL), Triton metrics (nv_inference_queue_duration_us) | Prometheus |
Fix / how to use it: set the batch delay from the latency budget (a delay of 2-5 ms inside a 50 ms budget is common; measure); cap the queue and shed load instead of queueing forever (Load Shedding); judge efficiency by throughput per GPU at the target p99, not by utilisation alone.
Prediction caching, warm-up, cold starts and autoscaling Important
In plain words: do not recompute what you just computed, do not send real users to a model that has not loaded, and add GPUs before the queue explodes, not after.
Common misunderstanding: "Autoscale on CPU like any service." GPU inference is usually bound by GPU or queue time; CPU may be idle while the queue grows. And GPU nodes take minutes to start, so reactive scaling alone is late.
Definition: a prediction cache stores scores keyed by model version and input (or entity) with a TTL; warm-up sends synthetic requests to a freshly loaded model before it is marked ready (Triton ModelWarmup: "Triton will not show the model as being ready for inference until model warmup has completed"); a cold start is the first slow requests after a scale-up or load (container pull, weight download, CUDA context, lazy initialisation); autoscaling adjusts replicas from metrics (Kubernetes HPA on custom metrics such as queue time, in-flight requests or GPU utilisation; KServe/Knative on concurrency, including scale to zero).
t Event Without care With care
1 09:00 traffic ramps 3x HPA on CPU: no change HPA on queue time: +2 pods
2 09:01 new pod starts pulls 8 GB image, loads weights image pre-pulled, weights on local NVMe
3 09:04 pod Ready first requests 4 s (lazy init) warm-up ran; first request normal
4 09:04 cache every page view rescored same user within 60 s: cache hitReal scenario: a home-feed model scoring the same user on every scroll (cache by user + model version, 30-60 s TTL); a GPU pool that cannot scale fast enough for a TV ad spike (keep headroom, schedule pre-scaling); scale-to-zero for internal models used a few times a day.
What provides it:
| Concern | Mechanism | Product |
|---|---|---|
| Prediction cache | Key = model version + entity or input hash; TTL | Redis, in-process LRU, CDN for public scores |
| Warm-up | Synthetic requests before ready | Triton ModelWarmup, readiness probes |
| Cold start | Pre-pulled images, model on local disk, min replicas | Kubernetes, KServe minReplicas |
| Autoscaling | HPA on custom/external metrics | Kubernetes HPA, KEDA, Knative KPA |
| Scale to zero | Activator buffers first request | KServe on Knative |
Fix / how to use it: cache with the model version in the key (the Go PredictionCache and Laravel examples do), never cache predictions made from stale or default features, autoscale on queue time or concurrency, keep minReplicas above zero for user-facing models. General cache patterns are in Caching, autoscaling in Scaling Strategies.
Feature fetching at request time Important
In plain words: before the model can score, the service must look up the user's and item's features; this lookup is often slower than the model itself.
Common misunderstanding: "Feature fetch is a database read, it is fast." Ranking 500 candidate items means 500 item feature reads; one round trip each blows the budget.
Definition: request-time feature fetching reads online-store rows for each entity key in the request (user, item candidates, context), fills defaults for missing values, checks freshness, and assembles the model input, ideally in one batched round trip per store.
Step Naive Batched
1 user features GET user:42 1 RTT HMGET fv:user:42 ... 1 RTT
2 500 candidate item features 500 x HMGET 500 RTT pipeline / MGET 1 RTT
3 context (time, device) computed computed
4 total at 0.3 ms per RTT (estimate) ~150 ms ~1 ms + transferReal scenario: ranking candidates for a home feed; fraud scoring needing card, merchant and device features; an ads auction with strict 10 ms budgets.
What provides it:
| Store | Batched read | Note |
|---|---|---|
| Redis | HMGET per hash, pipelining, MGET | Hash per entity keeps one key per row |
| DynamoDB | BatchGetItem (up to 100 items) | Single-digit ms typical; check your region |
| Cassandra / ScyllaDB | IN queries per partition, async parallel reads | Partition by entity key |
| Feast feature server | get_online_features with many entity rows | One call for many entities |
Fix / how to use it: one round trip per store per request; defaults for cold-start entities; flag stale features in the log; budget the fetch explicitly in the latency budget.
LLM serving architecture Must-know
In plain words: an LLM call is a long, streaming, expensive request whose cost scales with tokens; the architecture is about reusing work, bounding tokens, streaming the answer and checking what goes in and out.
Common misunderstanding: "It is just another model server." LLM requests vary 1000x in size, hold GPU memory (KV cache) for their whole duration, and are generated token by token; classic per-request batching does not fit.
Definition: vLLM's PagedAttention paper: "existing systems struggle because the key-value cache (KV cache) memory for each request is huge and grows and shrinks dynamically ... we propose PagedAttention, an attention algorithm inspired by the classical virtual memory and paging techniques". Continuous batching adds and removes sequences from the running batch each step. Prompt (prefix) caching: vLLM's design doc: "we cache the kv-cache blocks of processed requests, and reuse these blocks when a new request comes in with the same prefix". A token budget caps input + output tokens per request and per tenant. A streaming response returns tokens as they are generated (SSE, see Real-Time Communication). Guardrails are input and output checks (prompt injection, PII, policy, schema validation). Evaluation is offline test sets plus online signals, often with an LLM-as-judge.
Gateway vLLM server Client
1 check tenant token budget (8k in, 1k out)
2 input guardrail: PII redaction, injection heuristics
3 build prompt: fixed system prompt + retrieved context + question
4 prefix cache hit on system prompt blocks
5 continuous batching with 60 other sequences
6 stream tokens SSE: data: {"delta":"The"} ...
7 output guardrail: JSON schema, policy; log tokens and cost per tenantReal scenario: a support assistant where every request shares a 2,000-token system prompt (prefix caching saves its prefill each time); a per-tenant monthly token quota enforced in the gateway; an output schema check that retries once and then falls back to a template answer.
What provides it:
| Concern | Product / mechanism | Note |
|---|---|---|
| Serving | vLLM, NVIDIA TensorRT-LLM / Triton, Hugging Face TGI, SGLang | vLLM: OpenAI-compatible server |
| Memory | PagedAttention, quantisation (AWQ, GPTQ, FP8) | Bigger batches per GPU |
| Prompt caching | vLLM Automatic Prefix Caching; hosted APIs' prompt caching | Order prompts: static prefix first |
| Response cache | Exact-match or semantic cache in Redis | Risky for personalised answers |
| Token budgets | Gateway counters per tenant | Same algorithms as Rate Limiting |
| Guardrails | Input/output validators, policy models | Run in the gateway, not in the prompt |
| Evaluation | Golden sets, LLM-as-judge, MLflow LLM evaluation | Regression gate before rollout |
Fix / how to use it: put static instructions first so prefix caching works, enforce token budgets before calling the model, stream to the client, validate outputs against a schema, and gate model or prompt changes on an evaluation set exactly like any other model rollout. Company-level examples of LLM serving belong to Case Study: OpenAI.
RAG pipelines Important
In plain words: retrieval-augmented generation looks up relevant documents first and gives them to the LLM, so answers come from your data instead of the model's memory.
Common misunderstanding: "RAG removes hallucinations." It reduces them when retrieval finds the right chunks; when retrieval fails, the model answers confidently from the wrong context. Retrieval quality (recall@k) is the first metric to measure.
Definition: a RAG system has an ingestion path (parse, chunk, embed, index with metadata) and a query path (embed the query, retrieve top-k with filters, optionally re-rank, build the prompt within the token budget, generate, cite sources).
Ingestion (async) Query (sync, budget 2 s to first token)
1 doc uploaded -> parse -> chunk 500 tokens embed question (embedding model v3) 20 ms
2 embed chunks with model v3 vector search top-50, filter tenant_id=7 15 ms
3 upsert into vector DB with tenant_id, acl hybrid: + BM25 top-50, fuse (RRF) 10 ms
4 re-rank to top-5 with cross-encoder 60 ms
5 prompt = system + 5 chunks (3k tokens) + q LLM streamsReal scenario: internal documentation search; a support bot over product manuals; contract Q&A with per-customer access control enforced by metadata filters.
What provides it:
| Step | Choice | Note |
|---|---|---|
| Chunking | Fixed tokens with overlap, structure-aware | Chunk size trades context vs precision |
| Embeddings | Hosted embedding APIs or open models | Re-embed everything when the model changes |
| Store | pgvector, Qdrant, Milvus, Weaviate, Pinecone, Elasticsearch | See Vector databases |
| Retrieval | Vector + keyword (hybrid), metadata filters | ACL as a filter, never in the prompt |
| Re-ranking | Cross-encoder | Small model, big recall gain |
Fix / how to use it: measure retrieval recall on a labelled question set before tuning prompts; enforce access control as a metadata filter; store the embedding model version with each vector. The full Go build is in RAG & LLM Apps in Go.
Embeddings and vector databases Must-know
In plain words: an embedding turns a thing (text, image, user, item) into a list of numbers so that similar things are close; a vector database finds the closest ones fast.
Common misunderstanding: "We need a dedicated vector database." For millions of vectors with relational filters, PostgreSQL with pgvector is often enough; dedicated engines win at hundreds of millions of vectors, heavy filtering, or when you want managed scaling.
Definition: an embedding is a dense vector produced by a model; similarity is measured by cosine, inner product or L2 distance. kNN (k-nearest neighbours) returns the k closest vectors; exact kNN scans everything; ANN (approximate nearest neighbour) uses an index to return most of the true neighbours much faster. A vector database stores vectors with metadata, builds ANN indexes, filters, shards and replicates them.
Write path Read path
1 item 991 text -> embedding model v3 -> 384 floats query text -> same model v3 -> 384 floats
2 INSERT (991, category 12, in_stock, vector) ANN search: top-10 by cosine, category = 12
3 HNSW insert: link to m neighbours per layer greedy graph walk, ef_search candidates
4 replicate to followers (async) result: ids + distances -> fetch item rowsReal scenario: "similar products" on an item page; candidate generation for a recommender (user embedding vs item embeddings); semantic search and RAG; image deduplication.
What provides it:
| Product | Index types | Filtering | Scale model |
|---|---|---|---|
| PostgreSQL + pgvector | HNSW, IVFFlat; vector up to 2,000 dims indexed, halfvec 4,000 | SQL WHERE, iterative index scans (0.8.0+) | Postgres replicas; shard with Citus |
| Qdrant | HNSW with filterable (payload-aware) edges | Payload indexes; planner picks full scan under full_scan_threshold | Shards + replicas |
| Milvus | FLAT, IVF_FLAT, IVF_SQ8, IVF_PQ, HNSW, SCANN, DISKANN, GPU indexes | Scalar indexes and expressions | Distributed, separated storage/compute |
| Weaviate | HNSW, flat, dynamic (flat that switches to HNSW past a threshold) | Inverted index filters | Shards + replication |
| Pinecone | Managed (serverless) | Metadata filters | Fully managed |
| Elasticsearch / OpenSearch | HNSW dense_vector, knn with k and num_candidates | Filters + BM25 in one engine | Shards + replicas |
Fix / how to use it: start in Postgres if your data already lives there (Vector Search & pgvector covers the internals); move to a dedicated engine when the vector count, filter selectivity or update rate needs it; never mix vectors from two embedding models in one index.
ANN indexes: HNSW, IVF, product quantisation, DiskANN; recall vs latency Must-know
In plain words: HNSW is a layered "who is near whom" graph you walk downhill; IVF groups vectors into buckets and searches only the nearest buckets; product quantisation compresses vectors so more fit in memory; DiskANN puts the graph on SSD.
Common misunderstanding: "Recall is a property of the database." Recall is a property of your index settings on your data: ef_search, nprobe, m, lists, quantisation, filters. The same engine gives 0.6 or 0.99 depending on them.
Definition: HNSW (Malkov & Yashunin) "incrementally builds a multi-layer structure consisting from hierarchical set of proximity graphs (layers) for nested subsets of the stored elements"; search starts at the top layer and descends. IVF (inverted file) clusters vectors with k-means into nlist lists and scans the nprobe closest lists. Product quantization (PQ) splits each vector into sub-vectors and replaces each with a code from a small codebook (FAISS: "compressed-domain search based on product quantization"); IVF-PQ combines both. DiskANN stores a graph index on SSD: "index, store, and search a billion point database on a single workstation with just 64GB RAM and an inexpensive solid-state drive". Recall@k = share of the true k nearest neighbours that the index returned.
Measured by this page's Go IVF (20,000 x 64-dim clustered vectors, nlist=128, laptop; see Lab)
1 nprobe recall@10 vectors scanned per query
2 flat 1.000 20000 ~550 us
3 1 0.50 165 ~12 us
4 8 0.94 1237 ~47 us
5 32 0.997 4906 ~170 usReal scenario: a product catalogue of 5M items on HNSW in pgvector with ef_search 100; 1B image embeddings in Milvus with DiskANN or IVF-PQ to fit hardware; a recall regression after someone lowered ef_search to cut latency.
What provides it:
| Index | Memory | Build | Query speed / recall | Updates |
|---|---|---|---|---|
| Flat (exact) | Vectors only | None | Slow, recall 1.0 | Trivial |
| HNSW | Vectors + graph (m links per node) | Slow, memory-heavy | Fast, high recall | Incremental inserts; deletes leave tombstones |
| IVF-Flat | Vectors + centroids | Fast (k-means), build after data loads | Good; nprobe trades recall | Lists drift as data changes; rebuild periodically |
| IVF-PQ | Compressed codes | Train codebooks | Fast, lower recall; re-rank with full vectors | Retrain on distribution change |
| DiskANN | PQ in RAM, graph + vectors on SSD | Heavy | Fast for billion scale | Engine-dependent (Fresh-DiskANN variants) |
Fix / how to use it: decide a recall target (for example recall@10 ≥ 0.95 on a held-out query set), then tune: pgvector hnsw.ef_search (default 40) or ivfflat.probes (default 1, "can be set to the number of lists for exact nearest neighbor search"); measure recall against exact search regularly, as in the lab.
Metadata filtering and hybrid search Important
In plain words: real queries say "similar to this, but in stock, in my language, that I am allowed to see"; and some queries need exact words, not meaning.
Common misunderstanding: "Add a WHERE clause and you are done." With approximate indexes the filter may be applied after the index returned its candidates. pgvector: "If a condition matches 10% of rows, with HNSW and the default hnsw.ef_search of 40, only 4 rows will match on average."
Definition: metadata filtering restricts ANN results by attributes; strategies are pre-filtering (filter then exact search on the subset), post-filtering (ANN then filter; can return fewer than k), and filter-aware search (iterative scans, filterable HNSW, filtering during IVF list scans). Hybrid search combines keyword (BM25) and vector results, usually with reciprocal rank fusion (RRF) or a re-ranker; scoring theory lives in Search Systems and Full-Text Search.
Query: similar to item 991, category = 12 (10% of rows), k = 10
1 post-filter: HNSW top-40 -> keep category 12 -> ~4 results (too few)
2 iterative scan (pgvector 0.8+): keep scanning until 10 match (10 results, more work)
3 filterable HNSW (Qdrant): graph has extra edges per payload value (10 results, efficient)
4 very selective filter (0.1%): exact scan of the 0.1% is cheapest (planner: full scan)Real scenario: multi-tenant RAG where tenant_id must always filter; marketplace search for "red running shoes size 42" (keyword + vector); legal search where exact clause numbers matter.
What provides it:
| Product | Filtered ANN | Hybrid |
|---|---|---|
| pgvector | hnsw.iterative_scan = strict_order / relaxed_order, hnsw.max_scan_tuples (20,000 default) | Combine with Postgres full-text search; RRF or cross-encoder |
| Qdrant | Payload indexes + filterable HNSW (build payload indexes first) | Sparse + dense vectors, fusion |
| Elasticsearch | knn with filter; num_candidates | BM25 + kNN in one query, RRF |
| Weaviate | Pre-filter with inverted index | hybrid query with alpha weighting |
| Milvus | Boolean expressions on scalar fields | Multi-vector / sparse + dense |
Fix / how to use it: know your filter selectivity; enable iterative scans or filter-aware indexes; for very selective filters use a B-tree on the filter column and exact search; for hybrid, fuse with RRF first and add a re-ranker if needed (the SQL snippet shows RRF in Postgres).
Monitoring: data drift, concept drift, delayed labels, feedback loops Must-know
In plain words: watch what goes into the model, what comes out, how fresh the features are and how fast it answers, because the true accuracy often arrives weeks later.
Common misunderstanding: "We monitor accuracy." For many models the label arrives late (a loan defaults in months, a fraud chargeback in weeks) or never (you only see clicks on what you showed). You need proxies that are available now.
Definition: data drift (covariate shift) is a change in the input distribution P(X); concept drift is a change in the relationship P(y | X), so the same inputs now mean something else; prediction drift is a change in the output distribution; delayed labels are ground truth that arrives long after the prediction; a feedback loop is when predictions change the data the next model trains on (Sculley et al.: direct and hidden feedback loops). Sculley's starting points for monitoring: prediction bias ("the distribution of predicted labels is equal to the distribution of observed labels"), action limits and up-stream producers.
Week Inputs Predictions Labels (delayed 30 days) Alert
1 W1 baseline mean score 0.031 — —
2 W2 new mobile app: country=null 18% mean 0.044 — data drift on country (PSI 0.3)
3 W3 same mean 0.046 W-1 labels: precision ok prediction drift
4 W6 same — W2 labels arrive: precision -9% performance alert -> retrainReal scenario: a fraud model after a new payment method launches (data drift); demand forecasting after a pandemic (concept drift); a recommender that only learns from items it already showed (feedback loop; mitigate with exploration traffic and holdouts); feature freshness falling because the materialization job died.
What provides it:
| Signal | Metric | Product |
|---|---|---|
| Data drift | PSI, KS test, Wasserstein, Jensen-Shannon per feature | Evidently ("Test tabular data quality and data drift"), WhyLabs, TFDV |
| Prediction drift / bias | Mean score vs observed rate, per slice | Evidently, custom Prometheus metrics |
| Performance (when labels arrive) | AUC, precision@k, calibration | Batch jobs joining the prediction log |
| Feature freshness | now − last write per feature view | Prometheus gauge from the online store |
| Serving health | p50/p99 latency, error rate, queue time, GPU memory | Prometheus, Triton metrics, DCGM |
| Feedback loop | Share of exploration traffic, holdout comparison | Experiment platform |
Fix / how to use it: alert on freshness and serving health like any SLO (SLOs), alert on drift per important feature with a threshold tuned on history, compute performance when labels land, keep a small random holdout to measure feedback effects. Observability stack details are in Observability.
Responsible ML: bias, explainability, privacy and PII Important
In plain words: a model can be accurate on average and unfair to a group, unexplainable to an auditor, or leak personal data it was trained on; the system must measure and control all three.
Common misunderstanding: "We removed the gender column, so the model is not biased." Other features (postcode, first name, purchase history) can act as proxies; bias is measured on outcomes per group, not by deleting columns.
Definition: bias here is systematically different error rates or outcomes between groups; metrics include demographic parity difference and equalised odds. Explainability attributes a prediction to its inputs; SHAP "(SHapley Additive exPlanations) is a game theoretic approach to explain the output of any machine learning model". PII (personally identifiable information) in training data creates legal and leakage risks: models, embeddings and LLMs can memorise and reveal it.
Step Check Owner
1 dataset assembled PII scan: emails, phones, ids -> drop/hash data platform
2 model trained per-group recall, FPR; gap > 5 pts blocks ML team + review
3 model served SHAP values logged for declined applications serving
4 user requests deletion remove from feature store, logs, next training set; re-embed privacyReal scenario: a lending model with a higher false-decline rate for one age group; a regulator asking for reasons for an adverse decision; a support LLM that repeats a customer's phone number from fine-tuning data.
What provides it:
| Concern | Tool | Note |
|---|---|---|
| Explainability | SHAP, LIME, model-native importances | KServe supports explainers alongside predictors |
| Fairness metrics | Fairlearn, AIF360, Evidently slices | Slice metrics in the evaluation gate |
| PII detection | Presidio, DLP APIs, regex + validators | At ingestion and in LLM guardrails |
| Data minimisation | Hashing, aggregation, retention limits | Retention on prediction logs too |
| Access control | Row-level security, column masking | See Database Security |
Fix / how to use it: add slice metrics and a fairness threshold to the evaluation gate, log explanations for high-stakes decisions, scan and minimise PII before it enters the offline store, and include the prediction log and embeddings in deletion workflows. Threat modelling is in Security Foundations.
MLOps CI/CD and pipeline orchestration Important
In plain words: pipeline code, feature definitions and serving config go through review and CI; training runs as an orchestrated DAG; models are promoted by gates, not by hand.
Common misunderstanding: "CI for ML is running unit tests." Google's guide: "CI is no longer only about testing and validating code and components, but also testing and validating data, data schemas, and models."
Definition: ML CI tests code, data contracts and model quality (offline metrics vs champion, slice metrics, latency on target hardware, model size); CD deploys the pipeline and, after gates, the model; orchestration runs the DAG with retries, schedules, backfills and lineage (Airflow DAGs, Kubeflow Pipelines on Kubernetes, Dagster software-defined assets).
Trigger Pipeline (Airflow / Kubeflow / Dagster) Gate
1 PR changes feature code unit tests, feature tests on sample, build image CI green
2 nightly 02:00 validate -> build training set (PIT) -> train -> evaluate AUC >= champion - 0.002, slices ok
3 register v9; latency test on GPU image p99 < 30 ms at batch 16
4 deploy v9 to shadow; after 24 h canary 5% auto rollback on SLO burnReal scenario: a feature change that breaks a downstream model caught by a contract test; a retrain that passes AUC but fails a latency test after a bigger architecture; backfilling a new feature via the orchestrator's backfill command.
What provides it:
| Product | Model | Note |
|---|---|---|
| Apache Airflow | Python DAGs of tasks | Mature scheduler; huge operator ecosystem |
| Kubeflow Pipelines | Containerised components on Kubernetes | Artefacts and metadata built in |
| Dagster | Software-defined assets | Lineage and freshness policies on assets |
| Argo Workflows | Kubernetes-native DAGs | Used under Kubeflow |
| MLflow / DVC | Experiment tracking, data versioning | Reproducibility ids |
| GitHub Actions / GitLab CI | CI for pipeline code and images | Trigger pipeline runs |
Fix / how to use it: put pipeline code, feature definitions and serving config in Git; make the evaluation gate a pipeline step that can fail the run; promote by moving a registry alias; keep infra (GPU node pools, model servers) in Terraform/Helm like the rest of the platform.
Cost: GPUs and cost per prediction Good to know
In plain words: GPUs are the most expensive machines you run; cost per 1,000 predictions (or per 1M tokens) is the number to manage, and batching, quantisation, caching and right-sizing move it most.
Common misunderstanding: "Bigger model, better product." A bigger model may cost 5x per request for a metric change users do not notice; distillation, quantisation or a cheaper model for most traffic plus a big model for hard cases often wins.
Definition: GPU cost per prediction ≈ (GPU hourly price × GPUs) / predictions per hour at the target p99. For LLMs, cost scales with input and output tokens; output tokens are slower to generate than input tokens are to process.
Back-of-envelope (illustrative prices, not a quote)
1 1 GPU at $2.00/h, batch 1: 200 req/s -> 720k req/h -> $0.0028 per 1k predictions
2 same GPU, dynamic batching: 1,200 req/s -> 4.32M req/h -> $0.00046 per 1k (6x cheaper)
3 cache hit rate 40% in front -> GPU load x0.6 -> fewer GPUs at peak
4 peak 3x average, no autoscaling -> pay for peak 24 h a dayReal scenario: a ranking service that halved its GPU fleet after enabling batching and INT8; an LLM feature priced per tenant from logged token counts; nightly batch scoring moved to spot instances.
What provides it:
| Lever | Typical effect | Risk |
|---|---|---|
| Dynamic / continuous batching | Higher throughput per GPU | Added queue latency |
| Quantisation | Less memory, faster kernels | Accuracy loss; must re-evaluate |
| Prediction and prompt caching | Fewer model calls | Staleness; cache key mistakes |
| Smaller / distilled models | Lower cost per request | Quality on hard cases |
| Autoscaling, scale to zero | Pay for use | Cold starts |
| Batch instead of online | Cheap compute, spot | Staleness |
Fix / how to use it: publish cost per 1k predictions per model on the same dashboard as latency; review it at every rollout like a latency regression. The estimation method is in Capacity Estimation.
Mechanics
Latency budget for one online prediction
A 100 ms end-to-end budget for a ranking call, back-of-envelope (measure your own):
| Step | Budget | Note |
|---|---|---|
| Network client to gateway | 10 ms | Same region |
| Prediction cache lookup | 1 ms | In-process or Redis |
| Feature fetch (user + 500 items, pipelined) | 5 ms | One round trip per store |
| Batcher wait | 5 ms | MaxDelay; Triton max_queue_delay_microseconds |
| Model compute on GPU | 20 ms | Batch 32 |
| Post-processing, business rules | 5 ms | Filters, dedupe |
| Logging (async) | 0 ms on path | Buffered producer |
| Headroom for p99 | 54 ms | Tail latency, retries (Tail latency) |
Triton model configuration
# config.pbtxt for a ranking model (knob names from the Triton docs)
max_batch_size: 64
dynamic_batching {
preferred_batch_size: [ 16, 32 ]
max_queue_delay_microseconds: 2000
default_queue_policy { max_queue_size: 256 timeout_action: REJECT default_timeout_microseconds: 40000 }
}
instance_group [ { count: 2 kind: KIND_GPU gpus: [ 0 ] } ]
model_warmup [ { name: "warm" batch_size: 32 inputs { key: "input-0" value: { data_type: TYPE_FP32 dims: [ 48 ] random_data: true } } } ]Triton recommends preferred_batch_size only for batch sizes with a real performance benefit, and Model Analyzer to search the space.
KServe canary
apiVersion: serving.kserve.io/v1beta1
kind: InferenceService
metadata:
name: ctr
spec:
predictor:
canaryTrafficPercent: 10 # 10% to the new revision, 90% to the last ready one
minReplicas: 2 # no scale to zero for user-facing traffic
model:
modelFormat: { name: xgboost }
storageUri: gs://models/ctr/9 # resolved from the registry alias at deploy timepgvector knobs
| Knob | Default | Effect |
|---|---|---|
HNSW m | 16 | Max connections per layer; memory and recall |
HNSW ef_construction | 64 | Build candidate list; recall vs build time |
hnsw.ef_search | 40 | Query candidate list; recall vs latency |
ivfflat lists | none (you set it) | rows / 1000 up to 1M rows, sqrt(rows) above (README guidance) |
ivfflat.probes | 1 | Lists scanned; sqrt(lists) as a start |
hnsw.iterative_scan | off | strict_order or relaxed_order to keep scanning under filters |
hnsw.max_scan_tuples | 20,000 | Upper bound on iterative scanning |
Feast and vLLM knobs
| Knob | Product | Meaning |
|---|---|---|
ttl on a FeatureView | Feast | Max age of a value relative to each entity row in historical retrieval |
feast materialize start end / materialize-incremental | Feast | Copy offline to online for a time range |
| Push source | Feast | Write streaming features directly to online (and offline) |
filter_by_created_timestamp=True | Feast | Exclude values created after the entity timestamp |
--max-num-seqs | vLLM | Sequences in a running batch |
--gpu-memory-utilization | vLLM | Share of GPU memory for weights + KV cache |
--enable-prefix-caching | vLLM | Automatic prefix caching (check your version's default) |
--max-model-len | vLLM | Context length cap; bounds KV cache per sequence |
Error messages you will actually see
| Message | Where | Meaning / fix |
|---|---|---|
context deadline exceeded | Go client to model server | Deadline hit; return fallback, do not retry past the budget |
gateway: batch queue full | This page's Go Batcher | Shed load; scale out; lower delay |
Illuminate\Http\Client\ConnectionException | Laravel HTTP client | Connect/read timeout; fallback score |
UNAVAILABLE / RESOURCE_EXHAUSTED | gRPC to Triton | Server overloaded or queue full (timeout_action: REJECT) |
CUDA out of memory | PyTorch/vLLM | Batch or context too large; lower --max-num-seqs or --gpu-memory-utilization |
expected 384 dimensions, not 1536 | pgvector | Query embedding from a different model than the column |
ERROR: column cannot have more than 2000 dimensions for hnsw index | pgvector | Use halfvec (4,000) or reduce dimensions |
Go
The module academy/ml-systems-architecture has a naive endpoint (before), an inference gateway, a point-in-time join and a tiny vector index. Only the Redis client is a dependency.
Before
A scoring handler that re-implements a feature in the request path, calls the model with http.DefaultClient (no timeout), one request at a time, with no fallback, no model version and no feature log:
// Package main is the "before" version of a scoring endpoint: it works on a
// laptop and fails in production. Every comment marks a debt item.
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
type scoreRequest struct {
UserID int64 `json:"user_id"`
}
var db *sql.DB // opened elsewhere; the OLTP primary, shared with checkout
func score(w http.ResponseWriter, r *http.Request) {
var req scoreRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Debt 1: the feature is re-implemented here. The training job computes
// "orders in the last 7 days" in Spark with UTC day boundaries; this query
// uses a rolling 168 hours in the server's local time zone. Training-serving
// skew is built in on day one.
var orders7d float64
_ = db.QueryRow(`SELECT count(*) FROM orders
WHERE user_id = $1 AND created_at > now() - interval '168 hours'`,
req.UserID).Scan(&orders7d)
// Debt 2: an analytical query on the OLTP primary on every request.
// Debt 3: errors are ignored, so a failed query silently becomes 0.
body, _ := json.Marshal(map[string]any{"features": []float64{orders7d}})
// Debt 4: http.DefaultClient has no timeout; a slow GPU node holds this
// goroutine (and the user) forever.
// Debt 5: one request per call: no batching, so the GPU runs at batch 1.
// Debt 6: no model version in the request or the log; nobody can say which
// model produced a given score.
resp, err := http.Post("http://model:8080/predict", "application/json", bytes.NewReader(body))
if err != nil {
// Debt 7: no fallback; the page fails when the model fails.
http.Error(w, "model down", http.StatusBadGateway)
return
}
defer resp.Body.Close()
var out struct {
Score float64 `json:"score"`
}
_ = json.NewDecoder(resp.Body).Decode(&out)
// Debt 8: the features used for this prediction are not logged, so the
// next training set cannot be built from what serving actually saw.
fmt.Fprintf(w, `{"score": %f, "at": %q}`, out.Score, time.Now().Format(time.RFC3339))
}
func main() {
http.HandleFunc("POST /score", score)
log.Fatal(http.ListenAndServe(":8000", nil))
}After
Online features from Redis, one HMGET per entity, defaults for missing values, AsOf for freshness:
// Package gateway is a small inference gateway: it fetches online features,
// batches requests to a model server, caches predictions, falls back when the
// model is slow and mirrors a sample of traffic to a shadow model.
package gateway
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
// FeatureVector is what the online store returns for one entity key.
type FeatureVector struct {
Values []float64
AsOf time.Time // when the newest value was written (feature freshness)
Missing int // how many values were filled from defaults
}
// FeatureStore is the online-store read path. Implementations must be fast:
// the whole call usually gets a few milliseconds of the request budget.
type FeatureStore interface {
Get(ctx context.Context, entity string) (FeatureVector, error)
}
// ErrNoFeatures means the entity key has no row at all (new user, TTL expired).
var ErrNoFeatures = errors.New("gateway: no features for entity")
// RedisStore reads one Redis hash per entity: key "fv:<view>:<entity>",
// one field per feature plus "_ts" (Unix seconds of the last write).
// This layout is our own, not Feast's internal Redis encoding.
type RedisStore struct {
Client *redis.Client
View string
Names []string
Defaults []float64 // used when a field is absent; len must equal len(Names)
}
func (s *RedisStore) key(entity string) string { return "fv:" + s.View + ":" + entity }
// Get issues a single HMGET, one round trip whatever the feature count.
func (s *RedisStore) Get(ctx context.Context, entity string) (FeatureVector, error) {
fields := append([]string{"_ts"}, s.Names...)
vals, err := s.Client.HMGet(ctx, s.key(entity), fields...).Result()
if err != nil {
return FeatureVector{}, fmt.Errorf("online store: %w", err)
}
if vals[0] == nil {
return FeatureVector{}, ErrNoFeatures
}
ts, err := strconv.ParseInt(vals[0].(string), 10, 64)
if err != nil {
return FeatureVector{}, fmt.Errorf("online store: bad _ts: %w", err)
}
fv := FeatureVector{Values: make([]float64, len(s.Names)), AsOf: time.Unix(ts, 0)}
for i, v := range vals[1:] {
str, ok := v.(string)
f, perr := strconv.ParseFloat(str, 64)
if !ok || perr != nil {
fv.Values[i] = s.Defaults[i]
fv.Missing++
continue
}
fv.Values[i] = f
}
return fv, nil
}
// MemoryStore is an in-process FeatureStore for tests and the lab.
type MemoryStore struct {
mu sync.Mutex
rows map[string]FeatureVector
Reads int
}
// NewMemoryStore returns an empty store.
func NewMemoryStore() *MemoryStore { return &MemoryStore{rows: map[string]FeatureVector{}} }
// Put writes (materializes) the latest values for one entity.
func (m *MemoryStore) Put(entity string, fv FeatureVector) {
m.mu.Lock()
defer m.mu.Unlock()
m.rows[entity] = fv
}
// Get implements FeatureStore.
func (m *MemoryStore) Get(_ context.Context, entity string) (FeatureVector, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.Reads++
fv, ok := m.rows[entity]
if !ok {
return FeatureVector{}, ErrNoFeatures
}
return fv, nil
}A model client for the Open Inference Protocol (Triton, KServe runtimes, Seldon MLServer), with a hard timeout:
package gateway
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// Model scores a batch of feature rows and returns one score per row.
type Model interface {
PredictBatch(ctx context.Context, rows [][]float64) ([]float64, error)
Version() string
}
// HTTPModel calls a model server that speaks the Open Inference Protocol
// (KServe v2 REST): POST /v2/models/<name>/versions/<version>/infer.
// NVIDIA Triton, KServe runtimes and Seldon MLServer accept this shape.
type HTTPModel struct {
BaseURL string
Name string
Ver string
Client *http.Client // must have a Timeout; never http.DefaultClient
}
// NewHTTPModel builds a client with a hard per-call timeout.
func NewHTTPModel(baseURL, name, version string, timeout time.Duration) *HTTPModel {
return &HTTPModel{BaseURL: baseURL, Name: name, Ver: version, Client: &http.Client{Timeout: timeout}}
}
// Version implements Model.
func (m *HTTPModel) Version() string { return m.Name + ":" + m.Ver }
type oipTensor struct {
Name string `json:"name"`
Shape []int `json:"shape"`
Datatype string `json:"datatype"`
Data []float64 `json:"data"`
}
type oipRequest struct {
ID string `json:"id,omitempty"`
Inputs []oipTensor `json:"inputs"`
}
type oipResponse struct {
ModelName string `json:"model_name"`
ModelVersion string `json:"model_version"`
Outputs []oipTensor `json:"outputs"`
}
// PredictBatch sends the whole batch as one [n, d] FP64 tensor.
func (m *HTTPModel) PredictBatch(ctx context.Context, rows [][]float64) ([]float64, error) {
if len(rows) == 0 {
return nil, nil
}
d := len(rows[0])
flat := make([]float64, 0, len(rows)*d)
for _, r := range rows {
if len(r) != d {
return nil, fmt.Errorf("model: ragged batch: %d vs %d", len(r), d)
}
flat = append(flat, r...)
}
body, err := json.Marshal(oipRequest{Inputs: []oipTensor{{
Name: "input-0", Shape: []int{len(rows), d}, Datatype: "FP64", Data: flat,
}}})
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/v2/models/%s/versions/%s/infer", m.BaseURL, m.Name, m.Ver)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := m.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("model: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("model: status %d", resp.StatusCode)
}
var out oipResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return nil, fmt.Errorf("model: decode: %w", err)
}
if len(out.Outputs) == 0 || len(out.Outputs[0].Data) != len(rows) {
return nil, fmt.Errorf("model: expected %d scores", len(rows))
}
return out.Outputs[0].Data, nil
}Client-side dynamic batching with max size, max delay, a bounded queue that sheds load, and abandoned callers dropped before the GPU sees them:
package gateway
import (
"context"
"errors"
"time"
)
// ErrQueueFull is returned instead of queueing without bound (load shedding).
var ErrQueueFull = errors.New("gateway: batch queue full")
// Batcher is client-side dynamic batching: it holds a request for at most
// MaxDelay so that others can join, and sends early when MaxBatch is reached.
// It is the same idea as Triton's dynamic_batching { max_queue_delay_microseconds }.
type Batcher struct {
model Model
maxBatch int
maxDelay time.Duration
timeout time.Duration // per batch call to the model server
reqs chan *call
slots chan struct{} // concurrent batches in flight (model instances)
stop chan struct{}
}
type call struct {
ctx context.Context
row []float64
res chan result
}
type result struct {
score float64
err error
}
// BatcherConfig holds the knobs; all are required.
type BatcherConfig struct {
MaxBatch int
MaxDelay time.Duration
Timeout time.Duration
QueueSize int
InFlight int
}
// NewBatcher starts the batching loop.
func NewBatcher(m Model, c BatcherConfig) *Batcher {
b := &Batcher{
model: m, maxBatch: c.MaxBatch, maxDelay: c.MaxDelay, timeout: c.Timeout,
reqs: make(chan *call, c.QueueSize),
slots: make(chan struct{}, c.InFlight),
stop: make(chan struct{}),
}
go b.loop()
return b
}
// Close stops the loop. Calls already queued get no answer after Close and
// return when their own context ends.
func (b *Batcher) Close() { close(b.stop) }
// Predict enqueues one row and waits for its score or the caller's deadline.
func (b *Batcher) Predict(ctx context.Context, row []float64) (float64, error) {
c := &call{ctx: ctx, row: row, res: make(chan result, 1)}
select {
case b.reqs <- c:
default:
return 0, ErrQueueFull
}
select {
case r := <-c.res:
return r.score, r.err
case <-ctx.Done():
return 0, ctx.Err()
}
}
func (b *Batcher) loop() {
for {
var first *call
select {
case first = <-b.reqs:
case <-b.stop:
return
}
batch := []*call{first}
timer := time.NewTimer(b.maxDelay)
fill:
for len(batch) < b.maxBatch {
select {
case c := <-b.reqs:
batch = append(batch, c)
case <-timer.C:
break fill
case <-b.stop:
timer.Stop()
return
}
}
timer.Stop()
b.slots <- struct{}{} // wait for a free model instance
go b.dispatch(batch)
}
}
func (b *Batcher) dispatch(batch []*call) {
defer func() { <-b.slots }()
// Drop callers that already gave up: no GPU time for abandoned requests.
live := batch[:0]
for _, c := range batch {
if c.ctx.Err() == nil {
live = append(live, c)
}
}
if len(live) == 0 {
return
}
rows := make([][]float64, len(live))
for i, c := range live {
rows[i] = c.row
}
// The batch outlives any single caller, so it gets its own deadline.
ctx, cancel := context.WithTimeout(context.Background(), b.timeout)
defer cancel()
scores, err := b.model.PredictBatch(ctx, rows)
for i, c := range live {
if err != nil {
c.res <- result{err: err}
continue
}
c.res <- result{score: scores[i]}
}
}A prediction cache keyed by model version:
package gateway
import (
"sync"
"time"
)
// PredictionCache is a TTL cache keyed by model version and entity. Putting
// the model version in the key means a rollout never serves the old model's
// scores under the new model's name.
type PredictionCache struct {
mu sync.Mutex
ttl time.Duration
max int
items map[string]cacheEntry
now func() time.Time
}
type cacheEntry struct {
score float64
expires time.Time
}
// NewPredictionCache bounds both age and size.
func NewPredictionCache(ttl time.Duration, max int) *PredictionCache {
return &PredictionCache{ttl: ttl, max: max, items: map[string]cacheEntry{}, now: time.Now}
}
func cacheKey(modelVersion, entity string) string { return modelVersion + "|" + entity }
// Get returns a fresh cached score.
func (c *PredictionCache) Get(modelVersion, entity string) (float64, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.items[cacheKey(modelVersion, entity)]
if !ok || c.now().After(e.expires) {
return 0, false
}
return e.score, true
}
// Set stores a score. When full it drops expired entries first, then an
// arbitrary one (map order); a production cache would use LRU or Redis.
func (c *PredictionCache) Set(modelVersion, entity string, score float64) {
c.mu.Lock()
defer c.mu.Unlock()
if len(c.items) >= c.max {
now := c.now()
for k, e := range c.items {
if now.After(e.expires) {
delete(c.items, k)
}
}
for k := range c.items {
if len(c.items) < c.max {
break
}
delete(c.items, k)
}
}
c.items[cacheKey(modelVersion, entity)] = cacheEntry{score: score, expires: c.now().Add(c.ttl)}
}The gateway: cache → features (cold start and staleness flagged) → batcher → fallback, a prediction log with the served features, and sampled shadow traffic with its own context, timeout and concurrency cap:
package gateway
import (
"context"
"errors"
"math/rand/v2"
"sync"
"time"
)
// Event is one prediction log line. Logging the features actually served is
// what makes the next training set match serving (Google Rules of ML, #29).
type Event struct {
Entity string
Model string
Features []float64
Score float64
Source string // "model", "cache", "fallback", "shadow"
Stale bool
At time.Time
}
// EventLog receives prediction events (Kafka producer, file, test recorder).
type EventLog interface{ Log(Event) }
// Result is what the caller gets back.
type Result struct {
Score float64
ModelVersion string
Source string
Stale bool
}
// Config holds the gateway policy.
type Config struct {
Defaults []float64 // feature defaults for cold-start entities
MaxFeatureAge time.Duration // older features are flagged stale
FallbackScore float64 // e.g. a popularity prior when the model fails
ShadowRate float64 // 0..1 share of requests mirrored to the challenger
ShadowTimeout time.Duration
ShadowMax int // concurrent shadow calls; extra samples are dropped
}
// Gateway ties the pieces together.
type Gateway struct {
cfg Config
store FeatureStore
champion *Batcher
champVer string
shadow Model // nil disables shadow traffic
cache *PredictionCache
log EventLog
shadowSem chan struct{}
sample func() float64
now func() time.Time
wg sync.WaitGroup
}
// New builds a gateway. shadow and cache may be nil.
func New(cfg Config, store FeatureStore, champion *Batcher, championVersion string,
shadow Model, cache *PredictionCache, log EventLog) *Gateway {
return &Gateway{
cfg: cfg, store: store, champion: champion, champVer: championVersion,
shadow: shadow, cache: cache, log: log,
shadowSem: make(chan struct{}, max(cfg.ShadowMax, 1)),
sample: rand.Float64, now: time.Now,
}
}
// Score returns a prediction for one entity within the caller's deadline.
func (g *Gateway) Score(ctx context.Context, entity string) Result {
if g.cache != nil {
if s, ok := g.cache.Get(g.champVer, entity); ok {
return Result{Score: s, ModelVersion: g.champVer, Source: "cache"}
}
}
fv, err := g.store.Get(ctx, entity)
stale := false
switch {
case errors.Is(err, ErrNoFeatures):
fv = FeatureVector{Values: g.cfg.Defaults} // cold start: defaults, not an error
stale = true
case err != nil:
fv = FeatureVector{Values: g.cfg.Defaults} // store down: degrade, do not fail
stale = true
case g.now().Sub(fv.AsOf) > g.cfg.MaxFeatureAge:
stale = true // feature freshness SLO missed; still usable, but flagged
}
score, err := g.champion.Predict(ctx, fv.Values)
res := Result{Score: score, ModelVersion: g.champVer, Source: "model", Stale: stale}
if err != nil {
res = Result{Score: g.cfg.FallbackScore, ModelVersion: "fallback", Source: "fallback", Stale: stale}
}
g.log.Log(Event{Entity: entity, Model: res.ModelVersion, Features: fv.Values,
Score: res.Score, Source: res.Source, Stale: stale, At: g.now()})
if res.Source == "model" && g.cache != nil && !stale {
g.cache.Set(g.champVer, entity, score)
}
g.maybeShadow(entity, fv.Values)
return res
}
// maybeShadow mirrors the same features to the challenger, off the request
// path: its own context, its own timeout, a concurrency cap, and its result
// is only logged, never returned.
func (g *Gateway) maybeShadow(entity string, row []float64) {
if g.shadow == nil || g.sample() >= g.cfg.ShadowRate {
return
}
select {
case g.shadowSem <- struct{}{}:
default:
return // shadow is best effort; drop instead of queueing
}
g.wg.Add(1)
go func() {
defer g.wg.Done()
defer func() { <-g.shadowSem }()
ctx, cancel := context.WithTimeout(context.Background(), g.cfg.ShadowTimeout)
defer cancel()
out, err := g.shadow.PredictBatch(ctx, [][]float64{row})
if err != nil {
return
}
g.log.Log(Event{Entity: entity, Model: g.shadow.Version(), Features: row,
Score: out[0], Source: "shadow", At: g.now()})
}()
}
// Wait blocks until in-flight shadow calls finish (tests, graceful shutdown).
func (g *Gateway) Wait() { g.wg.Wait() }Tests: one batch for eight concurrent requests, flush after max delay, shedding, fallback under a slow model, cache by version, cold start/stale, shadow that never changes the answer or its latency, and the Open Inference Protocol shape against httptest:
package gateway
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
// fakeModel sums each row; it records the batch sizes it was called with.
type fakeModel struct {
mu sync.Mutex
batches []int
delay time.Duration
err error
ver string
}
func (f *fakeModel) Version() string { return f.ver }
func (f *fakeModel) PredictBatch(ctx context.Context, rows [][]float64) ([]float64, error) {
f.mu.Lock()
f.batches = append(f.batches, len(rows))
f.mu.Unlock()
select {
case <-time.After(f.delay):
case <-ctx.Done():
return nil, ctx.Err()
}
if f.err != nil {
return nil, f.err
}
out := make([]float64, len(rows))
for i, r := range rows {
for _, v := range r {
out[i] += v
}
}
return out, nil
}
func (f *fakeModel) calls() []int {
f.mu.Lock()
defer f.mu.Unlock()
return append([]int(nil), f.batches...)
}
type recorder struct {
mu sync.Mutex
events []Event
}
func (r *recorder) Log(e Event) {
r.mu.Lock()
defer r.mu.Unlock()
r.events = append(r.events, e)
}
func (r *recorder) bySource(src string) int {
r.mu.Lock()
defer r.mu.Unlock()
n := 0
for _, e := range r.events {
if e.Source == src {
n++
}
}
return n
}
func cfg(maxBatch int, delay time.Duration) BatcherConfig {
return BatcherConfig{MaxBatch: maxBatch, MaxDelay: delay, Timeout: time.Second, QueueSize: 64, InFlight: 2}
}
func TestBatcherCombinesConcurrentRequests(t *testing.T) {
m := &fakeModel{ver: "ctr:7"}
b := NewBatcher(m, cfg(8, 200*time.Millisecond))
defer b.Close()
var wg sync.WaitGroup
for i := range 8 {
wg.Add(1)
go func() {
defer wg.Done()
s, err := b.Predict(context.Background(), []float64{float64(i), 1})
if err != nil || s != float64(i)+1 {
t.Errorf("row %d: score %v err %v", i, s, err)
}
}()
}
wg.Wait()
if got := m.calls(); len(got) != 1 || got[0] != 8 {
t.Fatalf("want one batch of 8, got %v", got)
}
}
func TestBatcherFlushesAfterMaxDelay(t *testing.T) {
m := &fakeModel{ver: "ctr:7"}
b := NewBatcher(m, cfg(32, 5*time.Millisecond))
defer b.Close()
start := time.Now()
if _, err := b.Predict(context.Background(), []float64{1}); err != nil {
t.Fatal(err)
}
if el := time.Since(start); el > 200*time.Millisecond {
t.Fatalf("a lone request waited %v; max delay is 5ms", el)
}
if got := m.calls(); len(got) != 1 || got[0] != 1 {
t.Fatalf("want one batch of 1, got %v", got)
}
}
func TestBatcherShedsWhenQueueFull(t *testing.T) {
m := &fakeModel{ver: "ctr:7", delay: 300 * time.Millisecond}
b := NewBatcher(m, BatcherConfig{MaxBatch: 1, MaxDelay: time.Millisecond, Timeout: time.Second, QueueSize: 1, InFlight: 1})
defer b.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
shed := 0
var mu sync.Mutex
var wg sync.WaitGroup
for range 10 {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := b.Predict(ctx, []float64{1}); errors.Is(err, ErrQueueFull) {
mu.Lock()
shed++
mu.Unlock()
}
}()
}
wg.Wait()
if shed == 0 {
t.Fatal("expected some requests to be shed with ErrQueueFull")
}
}
func newGateway(t *testing.T, champ, shadow *fakeModel, rate float64) (*Gateway, *MemoryStore, *recorder) {
t.Helper()
store := NewMemoryStore()
store.Put("u1", FeatureVector{Values: []float64{2, 3}, AsOf: time.Now()})
rec := &recorder{}
b := NewBatcher(champ, cfg(16, 2*time.Millisecond))
t.Cleanup(b.Close)
var sh Model
if shadow != nil {
sh = shadow
}
g := New(Config{Defaults: []float64{0, 0}, MaxFeatureAge: time.Hour, FallbackScore: 0.01,
ShadowRate: rate, ShadowTimeout: 50 * time.Millisecond, ShadowMax: 4},
store, b, champ.Version(), sh, NewPredictionCache(time.Minute, 100), rec)
return g, store, rec
}
func TestGatewayFallsBackWhenModelIsSlow(t *testing.T) {
g, _, rec := newGateway(t, &fakeModel{ver: "ctr:7", delay: 500 * time.Millisecond}, nil, 0)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
r := g.Score(ctx, "u1")
if r.Source != "fallback" || r.Score != 0.01 {
t.Fatalf("want fallback 0.01, got %+v", r)
}
if rec.bySource("fallback") != 1 {
t.Fatal("fallback must be logged so it shows up in monitoring")
}
}
func TestGatewayCachesByModelVersion(t *testing.T) {
champ := &fakeModel{ver: "ctr:7"}
g, store, _ := newGateway(t, champ, nil, 0)
first := g.Score(context.Background(), "u1")
second := g.Score(context.Background(), "u1")
if first.Score != 5 || second.Source != "cache" || second.Score != 5 {
t.Fatalf("first %+v second %+v", first, second)
}
if store.Reads != 1 || len(champ.calls()) != 1 {
t.Fatalf("cache hit must skip feature fetch and model: reads=%d calls=%v", store.Reads, champ.calls())
}
}
func TestGatewayColdStartAndStaleFeatures(t *testing.T) {
g, store, _ := newGateway(t, &fakeModel{ver: "ctr:7"}, nil, 0)
if r := g.Score(context.Background(), "new-user"); !r.Stale || r.Source != "model" || r.Score != 0 {
t.Fatalf("cold start should use defaults and be flagged: %+v", r)
}
store.Put("u2", FeatureVector{Values: []float64{1, 1}, AsOf: time.Now().Add(-3 * time.Hour)})
if r := g.Score(context.Background(), "u2"); !r.Stale || r.Score != 2 {
t.Fatalf("3h-old features should be flagged stale: %+v", r)
}
}
func TestShadowNeverAffectsTheResponse(t *testing.T) {
champ := &fakeModel{ver: "ctr:7"}
broken := &fakeModel{ver: "ctr:8-shadow", err: errors.New("boom")}
slow := &fakeModel{ver: "ctr:8-shadow", delay: 10 * time.Millisecond}
g, _, rec := newGateway(t, champ, broken, 1.0)
if r := g.Score(context.Background(), "u1"); r.Source != "model" || r.Score != 5 {
t.Fatalf("broken shadow changed the answer: %+v", r)
}
g.Wait()
if rec.bySource("shadow") != 0 {
t.Fatal("failed shadow call must not be logged as a prediction")
}
g2, _, rec2 := newGateway(t, champ, slow, 1.0)
start := time.Now()
g2.Score(context.Background(), "u1")
if el := time.Since(start); el > 8*time.Millisecond+50*time.Millisecond {
t.Fatalf("shadow latency leaked into the request: %v", el)
}
g2.Wait()
if rec2.bySource("shadow") != 1 {
t.Fatal("shadow result should be logged for offline comparison")
}
}
func TestHTTPModelSpeaksOpenInferenceProtocol(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v2/models/ctr/versions/7/infer" {
http.Error(w, "wrong path "+r.URL.Path, http.StatusNotFound)
return
}
var req oipRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
in := req.Inputs[0]
n, d := in.Shape[0], in.Shape[1]
out := make([]float64, n)
for i := range n {
for j := range d {
out[i] += in.Data[i*d+j]
}
}
_ = json.NewEncoder(w).Encode(oipResponse{ModelName: "ctr", ModelVersion: "7",
Outputs: []oipTensor{{Name: "score", Shape: []int{n}, Datatype: "FP64", Data: out}}})
}))
defer srv.Close()
m := NewHTTPModel(srv.URL, "ctr", "7", 200*time.Millisecond)
got, err := m.PredictBatch(context.Background(), [][]float64{{1, 2}, {3, 4}})
if err != nil || len(got) != 2 || got[0] != 3 || got[1] != 7 {
t.Fatalf("got %v err %v", got, err)
}
}Point-in-time join next to the naive join, and tests that reproduce the four-row timeline from Point-in-time correctness:
// Package pit shows point-in-time correct feature joins (what Feast's
// get_historical_features does) next to the naive join that leaks the future.
package pit
import (
"sort"
"time"
)
// FeatureRow is one value of one feature for one entity key.
type FeatureRow struct {
Entity string
EventTime time.Time // when the value became true in the world
Created time.Time // when it was written (later for backfills)
Value float64
}
// LabelRow is one training example: an event and its outcome.
type LabelRow struct {
Entity string
EventTime time.Time
Label int
}
// Joined is a training row.
type Joined struct {
LabelRow
Value float64
Found bool
}
// NaiveLatest joins the newest feature value per entity, whatever its time.
// This is the classic leakage bug: rows from January get December's value.
func NaiveLatest(labels []LabelRow, feats []FeatureRow) []Joined {
latest := map[string]FeatureRow{}
for _, f := range feats {
if cur, ok := latest[f.Entity]; !ok || f.EventTime.After(cur.EventTime) {
latest[f.Entity] = f
}
}
out := make([]Joined, len(labels))
for i, l := range labels {
f, ok := latest[l.Entity]
out[i] = Joined{LabelRow: l, Value: f.Value, Found: ok}
}
return out
}
// AsOf joins, for each label row, the newest feature row with
// EventTime <= label time and label time - EventTime <= ttl.
// With onlyCreatedBefore, rows written after the label time (backfills,
// corrections) are ignored too, which reproduces what the online store
// could have served at that moment (Feast: filter_by_created_timestamp).
func AsOf(labels []LabelRow, feats []FeatureRow, ttl time.Duration, onlyCreatedBefore bool) []Joined {
byEntity := map[string][]FeatureRow{}
for _, f := range feats {
byEntity[f.Entity] = append(byEntity[f.Entity], f)
}
for _, rows := range byEntity {
sort.Slice(rows, func(i, j int) bool { return rows[i].EventTime.Before(rows[j].EventTime) })
}
out := make([]Joined, len(labels))
for i, l := range labels {
out[i] = Joined{LabelRow: l}
rows := byEntity[l.Entity]
// Scan backward from the last row at or before the label time.
k := sort.Search(len(rows), func(j int) bool { return rows[j].EventTime.After(l.EventTime) })
for j := k - 1; j >= 0; j-- {
f := rows[j]
if l.EventTime.Sub(f.EventTime) > ttl {
break // older rows are even further outside the TTL window
}
if onlyCreatedBefore && f.Created.After(l.EventTime) {
continue
}
out[i].Value, out[i].Found = f.Value, true
break
}
}
return out
}package pit
import (
"testing"
"time"
)
var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
func h(n int) time.Time { return t0.Add(time.Duration(n) * time.Hour) }
// Driver d1: trips_today grows during the day; one value was backfilled.
var feats = []FeatureRow{
{Entity: "d1", EventTime: h(8), Created: h(8), Value: 3},
{Entity: "d1", EventTime: h(12), Created: h(12), Value: 9},
{Entity: "d1", EventTime: h(14), Created: h(30), Value: 11}, // backfill written next day
{Entity: "d1", EventTime: h(20), Created: h(20), Value: 25},
}
var labels = []LabelRow{
{Entity: "d1", EventTime: h(7), Label: 0}, // before any feature row
{Entity: "d1", EventTime: h(13), Label: 1}, // should see 9
{Entity: "d1", EventTime: h(15), Label: 1}, // 11 only if backfills may leak
{Entity: "d1", EventTime: h(23), Label: 0}, // 25 is 3h old: outside a 2h TTL
}
func TestNaiveJoinLeaksTheFuture(t *testing.T) {
got := NaiveLatest(labels, feats)
for _, j := range got {
if j.Value != 25 {
t.Fatalf("naive join should give every row the latest value 25, got %v", j.Value)
}
}
}
func TestAsOfJoinIsPointInTimeCorrect(t *testing.T) {
got := AsOf(labels, feats, 2*time.Hour, false)
want := []struct {
found bool
value float64
}{{false, 0}, {true, 9}, {true, 11}, {false, 0}}
for i, w := range want {
if got[i].Found != w.found || got[i].Value != w.value {
t.Errorf("row %d: got (%v, %v) want (%v, %v)", i, got[i].Found, got[i].Value, w.found, w.value)
}
}
}
func TestCreatedTimestampFilterBlocksBackfillLeakage(t *testing.T) {
got := AsOf(labels, feats, 4*time.Hour, true)
if !got[2].Found || got[2].Value != 9 {
t.Fatalf("at 15:00 the online store only had 9 (backfill came at 06:00 next day), got %+v", got[2])
}
if !got[3].Found || got[3].Value != 25 {
t.Fatalf("with a 4h TTL the 20:00 value is usable at 23:00, got %+v", got[3])
}
}A tiny vector index: exact flat search, IVF with k-means, filtering during vs after the scan, and recall:
// Package vectorindex is a teaching vector index: an exact flat (brute force)
// scan and an IVF index (k-means coarse quantizer + inverted lists), with
// metadata filtering done during the scan or after it.
package vectorindex
import (
"container/heap"
"math"
"math/rand/v2"
)
// Hit is one search result. Score is the inner product of unit vectors,
// i.e. cosine similarity: higher is closer.
type Hit struct {
ID int
Score float32
}
// Filter returns true for ids allowed by the metadata predicate (nil = all).
type Filter func(id int) bool
// Normalize scales v to unit length in place so dot product == cosine.
func Normalize(v []float32) {
var s float64
for _, x := range v {
s += float64(x) * float64(x)
}
n := float32(math.Sqrt(s))
if n == 0 {
return
}
for i := range v {
v[i] /= n
}
}
func dot(a, b []float32) float32 {
var s float32
for i := range a {
s += a[i] * b[i]
}
return s
}
// minHeap keeps the best k hits seen so far (the worst on top).
type minHeap []Hit
func (h minHeap) Len() int { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i].Score < h[j].Score }
func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x any) { *h = append(*h, x.(Hit)) }
func (h *minHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
type topK struct {
k int
h minHeap
}
func (t *topK) offer(id int, s float32) {
if len(t.h) < t.k {
heap.Push(&t.h, Hit{id, s})
return
}
if s > t.h[0].Score {
t.h[0] = Hit{id, s}
heap.Fix(&t.h, 0)
}
}
func (t *topK) sorted() []Hit {
out := make([]Hit, len(t.h))
for i := len(out) - 1; i >= 0; i-- {
out[i] = heap.Pop(&t.h).(Hit)
}
return out
}
// Flat is exact kNN: it scores every vector. Recall is 1.0 by definition;
// cost is O(N*d) per query.
type Flat struct{ Vecs [][]float32 }
// Search returns the k nearest allowed vectors.
func (f *Flat) Search(q []float32, k int, allow Filter) []Hit {
t := &topK{k: k}
for id, v := range f.Vecs {
if allow != nil && !allow(id) {
continue
}
t.offer(id, dot(q, v))
}
return t.sorted()
}
// IVF partitions vectors into nlist clusters; a query scans only the nprobe
// clusters whose centroids are closest. This is IVFFlat in pgvector and
// IVF_FLAT in Milvus; FAISS adds product quantization (IVF-PQ) on top.
type IVF struct {
Vecs [][]float32
Centroids [][]float32
Lists [][]int // ids per cluster
}
// BuildIVF trains a k-means coarse quantizer with a fixed seed.
func BuildIVF(vecs [][]float32, nlist, iters int, seed uint64) *IVF {
r := rand.New(rand.NewPCG(seed, seed^0x9e3779b97f4a7c15))
d := len(vecs[0])
cent := make([][]float32, nlist)
for i := range cent {
cent[i] = append([]float32(nil), vecs[r.IntN(len(vecs))]...)
}
assign := make([]int, len(vecs))
for range iters {
for i, v := range vecs {
assign[i] = nearest(cent, v)
}
sums := make([][]float32, nlist)
counts := make([]int, nlist)
for i := range sums {
sums[i] = make([]float32, d)
}
for i, v := range vecs {
c := assign[i]
counts[c]++
for j := range v {
sums[c][j] += v[j]
}
}
for c := range cent {
if counts[c] == 0 {
cent[c] = append([]float32(nil), vecs[r.IntN(len(vecs))]...) // re-seed empty cluster
continue
}
Normalize(sums[c])
cent[c] = sums[c]
}
}
lists := make([][]int, nlist)
for i, v := range vecs {
c := nearest(cent, v)
lists[c] = append(lists[c], i)
}
return &IVF{Vecs: vecs, Centroids: cent, Lists: lists}
}
func nearest(cent [][]float32, v []float32) int {
best, bs := 0, float32(math.Inf(-1))
for i, c := range cent {
if s := dot(c, v); s > bs {
best, bs = i, s
}
}
return best
}
// probe returns the nprobe closest cluster ids.
func (ix *IVF) probe(q []float32, nprobe int) []int {
t := &topK{k: nprobe}
for i, c := range ix.Centroids {
t.offer(i, dot(q, c))
}
hits := t.sorted()
ids := make([]int, len(hits))
for i, h := range hits {
ids[i] = h.ID
}
return ids
}
// Search scans nprobe lists and applies the filter during the scan, so it
// returns k hits whenever k allowed vectors exist in the probed lists.
// Scanned reports how many vectors were scored (the cost).
func (ix *IVF) Search(q []float32, k, nprobe int, allow Filter) (hits []Hit, scanned int) {
t := &topK{k: k}
for _, c := range ix.probe(q, nprobe) {
for _, id := range ix.Lists[c] {
if allow != nil && !allow(id) {
continue
}
scanned++
t.offer(id, dot(q, ix.Vecs[id]))
}
}
return t.sorted(), scanned
}
// SearchPostFilter is the naive alternative: take the index's top k, then
// drop what the filter rejects. With a selective filter it returns fewer
// than k results, the same effect pgvector documents for HNSW with the
// default ef_search of 40 (before iterative index scans).
func (ix *IVF) SearchPostFilter(q []float32, k, nprobe int, allow Filter) []Hit {
top, _ := ix.Search(q, k, nprobe, nil)
out := top[:0]
for _, h := range top {
if allow == nil || allow(h.ID) {
out = append(out, h)
}
}
return out
}
// Recall is |approx ∩ exact| / |exact|: the share of true neighbours found.
func Recall(approx, exact []Hit) float64 {
if len(exact) == 0 {
return 1
}
want := map[int]bool{}
for _, h := range exact {
want[h.ID] = true
}
n := 0
for _, h := range approx {
if want[h.ID] {
n++
}
}
return float64(n) / float64(len(exact))
}
// Clustered generates n unit vectors in d dimensions around c centres,
// a stand-in for real embeddings (which are clustered, not uniform).
func Clustered(n, d, c int, spread float32, seed uint64) [][]float32 {
r := rand.New(rand.NewPCG(seed, seed+1))
centres := make([][]float32, c)
for i := range centres {
centres[i] = make([]float32, d)
for j := range centres[i] {
centres[i][j] = float32(r.NormFloat64())
}
Normalize(centres[i])
}
out := make([][]float32, n)
for i := range out {
base := centres[r.IntN(c)]
v := make([]float32, d)
for j := range v {
v[j] = base[j] + spread*float32(r.NormFloat64())
}
Normalize(v)
out[i] = v
}
return out
}package vectorindex
import "testing"
const (
n, d, k = 5000, 32, 10
nlist = 64
)
func fixture() (*Flat, *IVF, [][]float32) {
vecs := Clustered(n, d, 40, 0.08, 7)
queries := Clustered(50, d, 40, 0.08, 99)
return &Flat{Vecs: vecs}, BuildIVF(vecs, nlist, 8, 1), queries
}
func meanRecall(flat *Flat, ivf *IVF, qs [][]float32, nprobe int, allow Filter) float64 {
var sum float64
for _, q := range qs {
exact := flat.Search(q, k, allow)
approx, _ := ivf.Search(q, k, nprobe, allow)
sum += Recall(approx, exact)
}
return sum / float64(len(qs))
}
func TestFlatSearchIsExactAndSorted(t *testing.T) {
flat, _, qs := fixture()
hits := flat.Search(qs[0], k, nil)
if len(hits) != k {
t.Fatalf("want %d hits, got %d", k, len(hits))
}
for i := 1; i < len(hits); i++ {
if hits[i].Score > hits[i-1].Score {
t.Fatal("hits must be sorted best first")
}
}
}
func TestIVFRecallGrowsWithNprobe(t *testing.T) {
flat, ivf, qs := fixture()
r1 := meanRecall(flat, ivf, qs, 1, nil)
r8 := meanRecall(flat, ivf, qs, 8, nil)
rAll := meanRecall(flat, ivf, qs, nlist, nil)
t.Logf("recall@%d nprobe=1: %.3f nprobe=8: %.3f nprobe=%d: %.3f", k, r1, r8, nlist, rAll)
if r8 < r1 {
t.Fatalf("more probes must not lower recall: %.3f < %.3f", r8, r1)
}
if rAll != 1.0 {
t.Fatalf("probing every list is an exact scan; recall must be 1.0, got %.3f", rAll)
}
if r1 >= 1.0 {
t.Fatal("nprobe=1 should miss some neighbours on clustered data")
}
}
func TestIVFScansFractionOfData(t *testing.T) {
_, ivf, qs := fixture()
_, scanned := ivf.Search(qs[0], k, 4, nil)
if scanned >= n/4 {
t.Fatalf("nprobe=4 of %d lists should scan far less than a quarter, scanned %d", nlist, scanned)
}
}
func TestPostFilterReturnsTooFewResults(t *testing.T) {
flat, ivf, qs := fixture()
tenPercent := func(id int) bool { return id%10 == 0 } // e.g. "in stock in this region"
post := ivf.SearchPostFilter(qs[0], k, 8, tenPercent)
during, _ := ivf.Search(qs[0], k, 8, tenPercent)
if len(post) >= k {
t.Fatalf("post-filtering top-%d with a 10%% filter should lose results, got %d", k, len(post))
}
if len(during) != k {
t.Fatalf("filtering during the scan should still fill k=%d, got %d", k, len(during))
}
if r := Recall(during, flat.Search(qs[0], k, tenPercent)); r < 0.5 {
t.Fatalf("filtered recall unexpectedly low: %.2f", r)
}
}// Command recall prints the recall/latency trade-off of the IVF index:
// go run ./cmd/recall
package main
import (
"fmt"
"time"
"academy/ml-systems-architecture/vectorindex"
)
func main() {
const n, d, k, nlist = 20000, 64, 10, 128
vecs := vectorindex.Clustered(n, d, 100, 0.08, 7)
queries := vectorindex.Clustered(200, d, 100, 0.08, 99)
flat := &vectorindex.Flat{Vecs: vecs}
start := time.Now()
ivf := vectorindex.BuildIVF(vecs, nlist, 10, 1)
fmt.Printf("built IVF nlist=%d over %d x %d in %v\n", nlist, n, d, time.Since(start).Round(time.Millisecond))
exact := make([][]vectorindex.Hit, len(queries))
start = time.Now()
for i, q := range queries {
exact[i] = flat.Search(q, k, nil)
}
flatPer := time.Since(start) / time.Duration(len(queries))
fmt.Printf("%-8s %-10s %-12s %s\n", "nprobe", "recall@10", "scanned", "per query")
fmt.Printf("%-8s %-10.3f %-12d %v\n", "flat", 1.0, n, flatPer.Round(time.Microsecond))
for _, p := range []int{1, 2, 4, 8, 16, 32, nlist} {
var rec float64
var scanned int
start = time.Now()
for i, q := range queries {
hits, s := ivf.Search(q, k, p, nil)
rec += vectorindex.Recall(hits, exact[i])
scanned += s
}
per := time.Since(start) / time.Duration(len(queries))
fmt.Printf("%-8d %-10.3f %-12d %v\n", p, rec/float64(len(queries)), scanned/len(queries), per.Round(time.Microsecond))
}
}The Go angle
| Go feature | Use here | Note |
|---|---|---|
context.Context | Request deadline through feature fetch and model call | Batches get their own context; shadow gets its own |
http.Client{Timeout: ...} | Model server calls | http.DefaultClient has no timeout |
Channels + select with default | Bounded batch queue that sheds load | Never block a request on a full queue |
time.NewTimer | Batch max delay | Stop timers to avoid leaks |
sync.WaitGroup | Wait for shadow calls on shutdown | Gateway.Wait |
github.com/redis/go-redis/v9 | HMGet for online features | One round trip per entity |
google.golang.org/grpc | gRPC to Triton/KServe with generated v2 stubs | grpc.NewClient; pass the request ctx for deadlines |
container/heap | Top-k selection in the vector index | O(n log k) |
math/rand/v2 | Shadow sampling; seeded PCG for reproducible test data | Seed everything you want to reproduce |
net/http/httptest | Fake model server | Protocol tests without a GPU |
Laravel
Before
A controller that recomputes the feature in PHP, calls the model with the default 30-second timeout, has no fallback and logs nothing:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
// Before: works in a demo, fails in production.
class ScoreControllerBefore extends Controller
{
public function __invoke(Request $request)
{
$userId = (int) $request->input('user_id');
// Feature re-implemented in PHP with different semantics than the
// training pipeline (rolling 168h, app time zone) => training-serving skew.
$orders7d = DB::table('orders')
->where('user_id', $userId)
->where('created_at', '>', now()->subHours(168))
->count();
// Default HTTP client timeout is 30 s: a slow model stalls a PHP-FPM
// worker for 30 s. No fallback, no model version, features not logged.
$score = Http::post('http://model:8080/predict', [
'features' => [$orders7d],
])->json('score');
return ['score' => $score];
}
}After
Configuration: feature view, defaults, freshness limit, champion/challenger endpoints, shadow percentage:
<?php
return [
'feature_view' => 'user_ctr_v3',
'features' => ['orders_7d', 'ctr_30d', 'avg_basket'],
'defaults' => [0.0, 0.02, 0.0],
'feature_ttl_seconds' => 2 * 86400,
'max_feature_age_seconds' => 3600,
'champion' => ['url' => env('ML_CHAMPION_URL', 'http://ctr-predictor'), 'model' => 'ctr', 'version' => '7'],
'challenger' => ['url' => env('ML_CHALLENGER_URL', 'http://ctr-predictor-v8'), 'model' => 'ctr', 'version' => '8'],
// 0 disables shadow traffic; the Pennant flag "ctr-shadow" is the kill switch.
'shadow_percent' => (int) env('ML_SHADOW_PERCENT', 10),
'fallback_score' => 0.02,
];The online store on Redis: Redis::pipeline to materialize many entities in one round trip with a TTL, hmget to read one entity with defaults (same key layout as the Go gateway):
<?php
namespace App\Features;
use Illuminate\Support\Facades\Redis;
/**
* Online store on Redis: one hash per entity key, "fv:<view>:<entity>",
* one field per feature plus "_ts". Same layout as the Go gateway.
*/
class OnlineFeatureStore
{
public function __construct(
private string $view,
private array $names,
private array $defaults,
private int $ttlSeconds,
) {}
public static function fromConfig(): self
{
return new self(
config('ml.feature_view'),
config('ml.features'),
config('ml.defaults'),
config('ml.feature_ttl_seconds'),
);
}
private function key(string|int $entity): string
{
return "fv:{$this->view}:{$entity}";
}
/**
* Materialize the latest values for many entities in one round trip.
*
* @param array<string|int, array<string, float>> $rows entity => [feature => value]
*/
public function writeMany(array $rows, int $eventTime): void
{
Redis::pipeline(function ($pipe) use ($rows, $eventTime) {
foreach ($rows as $entity => $values) {
$pipe->hmset($this->key($entity), $values + ['_ts' => $eventTime]);
// TTL: an entity nobody updates for two days falls back to defaults.
$pipe->expire($this->key($entity), $this->ttlSeconds);
}
});
}
/**
* @return array{values: list<float>, as_of: int|null, missing: int}
*/
public function read(string|int $entity): array
{
$raw = array_values(Redis::hmget($this->key($entity), array_merge(['_ts'], $this->names)));
$asOf = ($raw[0] ?? null) ? (int) $raw[0] : null;
$values = [];
$missing = 0;
foreach ($this->names as $i => $name) {
$v = $raw[$i + 1] ?? null;
if ($v === null || $v === false || ! is_numeric($v)) {
$values[] = (float) $this->defaults[$i];
$missing++;
continue;
}
$values[] = (float) $v;
}
return ['values' => $values, 'as_of' => $asOf, 'missing' => $missing];
}
}Calling the model server with connectTimeout() and timeout() in fractions of a second, one fast retry() only on ConnectionException, a fallback score, the served features logged, and shadow traffic behind a Pennant flag and a percentage:
<?php
namespace App\Services;
use App\Features\OnlineFeatureStore;
use App\Jobs\ShadowScore;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Laravel\Pennant\Feature;
/**
* Calls a model server over the Open Inference Protocol (KServe v2 REST,
* also served by NVIDIA Triton and Seldon MLServer) with tight timeouts,
* one fast retry on connection errors, a fallback score and shadow traffic.
*/
class ModelClient
{
public function __construct(private OnlineFeatureStore $features) {}
/**
* @return array{score: float, model: string, source: string, stale: bool}
*/
public function score(int $userId): array
{
$fv = $this->features->read($userId);
$stale = $fv['as_of'] === null
|| now()->getTimestamp() - $fv['as_of'] > config('ml.max_feature_age_seconds');
$c = config('ml.champion');
$model = "{$c['model']}:{$c['version']}";
try {
$response = Http::baseUrl($c['url'])
->acceptJson()
->connectTimeout(0.05) // 50 ms to connect
->timeout(0.15) // 150 ms for the whole call
->retry([20], when: fn ($e) => $e instanceof ConnectionException)
->post("/v2/models/{$c['model']}/versions/{$c['version']}/infer", [
'inputs' => [[
'name' => 'input-0',
'shape' => [1, count($fv['values'])],
'datatype' => 'FP64',
'data' => $fv['values'],
]],
]);
$score = (float) $response->json('outputs.0.data.0');
$source = 'model';
} catch (ConnectionException|RequestException $e) {
Log::warning('ml.fallback', ['model' => $model, 'error' => class_basename($e)]);
$score = (float) config('ml.fallback_score');
$model = 'fallback';
$source = 'fallback';
}
// Log what serving actually saw; training reads this log (Rules of ML #29).
Redis::rpush('prediction_log', json_encode([
'entity' => $userId, 'model' => $model, 'features' => $fv['values'],
'score' => $score, 'source' => $source, 'stale' => $stale, 'at' => now()->getTimestampMs(),
]));
if ($source === 'model' && $this->shouldShadow()) {
// Off the request path: a queued job on its own queue.
ShadowScore::dispatch($userId, $fv['values'], $score)->onQueue('shadow');
}
return ['score' => $score, 'model' => $model, 'source' => $source, 'stale' => $stale];
}
private function shouldShadow(): bool
{
$percent = (int) config('ml.shadow_percent');
return $percent > 0
&& Feature::active('ctr-shadow')
&& random_int(1, 100) <= $percent;
}
}<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
/**
* Sends the same features to the challenger and logs both scores.
* The user never waits for this and never sees its answer.
*/
class ShadowScore implements ShouldQueue
{
use Queueable;
public int $tries = 1; // shadow is best effort; never retry-storm a new model
public function __construct(
public int $userId,
public array $features,
public float $championScore,
) {}
public function handle(): void
{
$c = config('ml.challenger');
try {
$response = Http::baseUrl($c['url'])
->acceptJson()
->timeout(1)
->post("/v2/models/{$c['model']}/versions/{$c['version']}/infer", [
'inputs' => [[
'name' => 'input-0',
'shape' => [1, count($this->features)],
'datatype' => 'FP64',
'data' => $this->features,
]],
]);
} catch (ConnectionException) {
return;
}
if ($response->failed()) {
return;
}
Redis::rpush('prediction_log', json_encode([
'entity' => $this->userId,
'model' => "{$c['model']}:{$c['version']}",
'features' => $this->features,
'score' => (float) $response->json('outputs.0.data.0'),
'champion_score' => $this->championScore,
'source' => 'shadow',
'at' => now()->getTimestampMs(),
]));
}
}pgvector from Laravel 13: the built-in whereVectorSimilarTo, and raw expressions (selectRaw, orderByRaw) with SET LOCAL hnsw.ef_search and iterative scans inside a transaction:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::ensureVectorExtensionExists();
Schema::create('item_embeddings', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('item_id')->unique();
$table->unsignedInteger('category_id')->index();
$table->boolean('in_stock')->default(true);
$table->string('embedding_model', 64); // re-embed everything when this changes
$table->vector('embedding', dimensions: 384);
$table->timestamps();
});
// $table->vector(...)->index() also works (cosine); raw SQL here to
// pin the index type and the HNSW build parameters explicitly.
DB::statement('CREATE INDEX item_embeddings_hnsw ON item_embeddings
USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64)');
}
public function down(): void
{
Schema::dropIfExists('item_embeddings');
}
};<?php
namespace App\Repositories;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Candidate retrieval from pgvector. Two styles: Laravel 13's built-in
* vector clauses, and raw expressions when you need pgvector knobs.
*/
class SimilarItems
{
/**
* Built-in: cosine similarity filter + ordering (PostgreSQL + pgvector).
*/
public function simple(array $embedding, int $k = 10): Collection
{
return DB::table('item_embeddings')
->select('item_id')
->whereVectorSimilarTo('embedding', $embedding, minSimilarity: 0.4)
->limit($k)
->get();
}
/**
* Raw expressions: metadata filter, HNSW search width and iterative scan
* set for this transaction only (SET LOCAL), cosine distance operator <=>.
*/
public function filtered(array $embedding, int $categoryId, int $k = 10): Collection
{
$vector = '['.implode(',', array_map('floatval', $embedding)).']';
return DB::transaction(function () use ($vector, $categoryId, $k) {
DB::statement('SET LOCAL hnsw.ef_search = 100');
DB::statement('SET LOCAL hnsw.iterative_scan = relaxed_order');
return DB::table('item_embeddings')
->select('item_id')
->selectRaw('embedding <=> ?::vector AS distance', [$vector])
->where('category_id', $categoryId)
->where('in_stock', true)
->orderByRaw('embedding <=> ?::vector', [$vector])
->limit($k)
->get();
});
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
Http::timeout() / connectTimeout() | Model calls | Defaults are 30 s and 10 s; far too long for inference |
Http::retry([20], when: ...) | One retry on connection errors only | Never retry a slow model past the budget |
Http::pool() | Parallel calls (several models, ensembles) | Concurrent requests |
Http::fake() | Test the client without a model server | Assert payload shape |
Redis::pipeline() | Materialize features in bulk | One round trip for many commands |
Redis::hmget() | Read one entity's features | Result shape differs between phpredis and Predis; normalise |
Queued job with Queueable | Shadow scoring off the request path | Own queue, $tries = 1 |
Laravel Pennant Feature::active() | Kill switch for shadow or canary | Flags per user or global |
Schema::ensureVectorExtensionExists(), $table->vector() | pgvector schema | ->index() creates a cosine vector index |
whereVectorSimilarTo, selectVectorDistance, orderByVectorDistance | Vector queries | PostgreSQL + pgvector, MariaDB 11.7+ |
selectRaw / orderByRaw with bindings | pgvector operators and knobs | Bind the vector; never interpolate user input |
Solving the classic problems
Offline metrics great, production poor (skew)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Log served features | Prediction log with the exact vector | Train on what serving saw | Storage; needs a join to labels |
| One definition | Feature store views used by both paths | Removes re-implementation | Platform to run |
| Skew monitor | Daily comparison logged vs recomputed | Catches regressions early | Needs both values |
Leakage in training data
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| As-of joins | Feast get_historical_features, LATERAL join | Correct by construction | Needs history with event times |
| Created-timestamp filter | Exclude late-written values | Stops backfill leakage | Needs reliable created_ts |
| Time-based splits | Train on past, validate on later period | Realistic evaluation | Less data for training |
GPUs expensive and underused
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Dynamic batching | Triton dynamic_batching, client batcher | Throughput per GPU up | Adds up to the delay to latency |
| Multiple instances | instance_group count: 2 | Overlap compute and I/O | GPU memory |
| Quantisation | INT8/FP8/AWQ | Smaller, faster | Re-evaluate quality |
| Right-size the fleet | Autoscale on queue time | Pay for load | Cold starts |
Cold starts and stampedes after deploys
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Warm-up | Triton model_warmup, readiness after warm-up | No slow first requests | Slower model updates |
| Min replicas | KServe minReplicas | Always-ready capacity | Idle cost |
| Pre-pulled images, local weights | DaemonSet pre-pull, node cache | Minutes to seconds | Disk, ops |
Filtered vector search returns too few results
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Iterative scans | pgvector hnsw.iterative_scan | Fills k | More work per query |
| Filter-aware index | Qdrant payload index + filterable HNSW | Efficient | Index build order matters |
| Exact search on subset | B-tree filter + exact distance | Perfect recall | Only when the subset is small |
| Partition by filter | Index per tenant/category | Small indexes | Many indexes to manage |
Silent degradation
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Drift monitoring | Evidently/WhyLabs per feature | Early warning | Threshold tuning |
| Prediction bias per slice | Mean prediction vs observed rate | Cheap and effective (Sculley) | Needs labels eventually |
| Freshness SLO | Alert on last write age | Catches dead pipelines | One more alert |
A bad model reaches users
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Shadow first | Gateway sampling, Istio mirror | Zero user impact | No outcome signal |
| Canary with auto rollback | KServe canaryTrafficPercent, Argo Rollouts | Limited blast radius | Needs good health metrics |
| Alias rollback | Move @champion back | Minutes | Old model must stay compatible with features |
LLM bill and latency grow
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Prefix caching | Static prompt first; vLLM APC | Lower prefill cost | Needs stable prefixes |
| Token budgets | Gateway counters per tenant | Bounded spend | Users hit limits |
| Smaller model routing | Classify, route easy cases to a small model | Big savings | Router quality |
| Streaming | SSE | Better perceived latency | Long-lived connections |
SQL: point-in-time joins, prediction log, pgvector
-- Offline store table: every version of a feature, never only the latest.
CREATE TABLE user_features (
user_id bigint NOT NULL, -- entity key
event_ts timestamptz NOT NULL, -- when the value became true
created_ts timestamptz NOT NULL DEFAULT now(), -- when it was written (backfills are late)
orders_7d integer NOT NULL,
ctr_30d real NOT NULL,
PRIMARY KEY (user_id, event_ts)
);
-- Labels (the "entity dataframe"): one row per impression with its outcome.
CREATE TABLE impressions (
impression_id bigint PRIMARY KEY,
user_id bigint NOT NULL,
item_id bigint NOT NULL,
shown_at timestamptz NOT NULL,
clicked boolean NOT NULL
);
-- Point-in-time correct join with a 2-hour TTL: for each impression take the
-- newest feature row at or before shown_at, written before shown_at, and not
-- older than the TTL. Rows with no match keep NULL features (cold start).
SELECT i.impression_id, i.clicked, f.orders_7d, f.ctr_30d
FROM impressions i
LEFT JOIN LATERAL (
SELECT uf.orders_7d, uf.ctr_30d
FROM user_features uf
WHERE uf.user_id = i.user_id
AND uf.event_ts <= i.shown_at
AND uf.event_ts > i.shown_at - interval '2 hours'
AND uf.created_ts <= i.shown_at -- no leakage from backfills
ORDER BY uf.event_ts DESC
LIMIT 1
) f ON true;
-- The leaky version people write first: latest value for everyone.
-- SELECT i.*, f.* FROM impressions i
-- JOIN (SELECT DISTINCT ON (user_id) * FROM user_features
-- ORDER BY user_id, event_ts DESC) f USING (user_id);
-- Serving-time feature log (Rules of ML #29): what the model actually saw.
CREATE TABLE prediction_log (
request_id uuid PRIMARY KEY,
user_id bigint NOT NULL,
model_version text NOT NULL, -- 'ctr:7', 'ctr:8-shadow', 'fallback'
features jsonb NOT NULL,
score real NOT NULL,
source text NOT NULL, -- model | cache | fallback | shadow
served_at timestamptz NOT NULL
);
-- Skew check: compare logged serving features with recomputed offline ones.
SELECT avg(abs((p.features->>'orders_7d')::int - f.orders_7d)) AS mean_abs_skew
FROM prediction_log p
JOIN LATERAL (
SELECT orders_7d FROM user_features uf
WHERE uf.user_id = p.user_id AND uf.event_ts <= p.served_at
ORDER BY event_ts DESC LIMIT 1
) f ON true
WHERE p.source = 'model' AND p.served_at > now() - interval '1 day';CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE item_embeddings (
item_id bigint PRIMARY KEY,
category_id integer NOT NULL,
in_stock boolean NOT NULL DEFAULT true,
embedding_model text NOT NULL, -- vectors from different models are not comparable
embedding vector(384) NOT NULL -- vector: up to 2,000 dims indexed; halfvec: 4,000
);
-- HNSW: m = max connections per layer (default 16), ef_construction (default 64).
CREATE INDEX ON item_embeddings USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Alternative: IVFFlat; build AFTER loading data; lists ~ rows/1000 up to 1M rows.
-- CREATE INDEX ON item_embeddings USING ivfflat (embedding vector_cosine_ops) WITH (lists = 1000);
CREATE INDEX ON item_embeddings (category_id);
-- Top-10 by cosine distance (<=>), filtered, with a wider search and
-- iterative scans so the filter does not starve the result (pgvector >= 0.8.0).
BEGIN;
SET LOCAL hnsw.ef_search = 100; -- default 40
SET LOCAL hnsw.iterative_scan = relaxed_order; -- off | strict_order | relaxed_order
SELECT item_id, embedding <=> $1::vector AS distance
FROM item_embeddings
WHERE category_id = 12 AND in_stock
ORDER BY embedding <=> $1::vector
LIMIT 10;
COMMIT;
-- Measure recall: exact answer by disabling index scans for one query.
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT item_id FROM item_embeddings ORDER BY embedding <=> $1::vector LIMIT 10;
COMMIT;
-- Hybrid search: full-text candidates + vector candidates, fused with RRF (k = 60).
WITH semantic AS (
SELECT item_id, row_number() OVER (ORDER BY embedding <=> $1::vector) AS r
FROM item_embeddings ORDER BY embedding <=> $1::vector LIMIT 50
), keyword AS (
SELECT id AS item_id, row_number() OVER (ORDER BY ts_rank_cd(search_tsv, q) DESC) AS r
FROM items, plainto_tsquery('english', $2) q
WHERE search_tsv @@ q ORDER BY ts_rank_cd(search_tsv, q) DESC LIMIT 50
)
SELECT item_id, sum(1.0 / (60 + r)) AS rrf
FROM (SELECT * FROM semantic UNION ALL SELECT * FROM keyword) u
GROUP BY item_id ORDER BY rrf DESC LIMIT 10;Worked design: a real-time recommendation service
The four steps from The 4-Step Approach, applied to "recommended for you" on an e-commerce home page. All numbers are back-of-envelope estimates.
1. Scope. 20M monthly users, 5M items; home page shows 20 items; p99 under 150 ms server side; recommendations reflect in-session behaviour within a minute; new items recommendable within an hour; explainable "because you viewed X".
2. Estimate.
| Quantity | Estimate | Reasoning |
|---|---|---|
| Peak home-page requests | 3,000/s | 2M DAU × 5 visits ÷ 86,400 s × ~25 peak factor |
| Candidates per request | 500 | Two-tower retrieval top-500 |
| Item feature reads per second | 1.5M | 3,000 × 500 (pipelined, cached hot items) |
| Item embeddings | 5M × 128 × 4 B ≈ 2.6 GB | Fits in RAM of one HNSW node; replicate for QPS |
| Ranking GPU throughput needed | 1.5M rows/s | 3,000 × 500 rows; batch per request |
| Prediction log | 3,000/s × 2 KB ≈ 6 MB/s | Kafka; ~0.5 TB/day before compression |
3. High-level design.
Request path (sync) Offline / async
1 client -> API gateway -> recs service events (views, carts) -> Kafka
2 recs: user features (online store, Redis) + session features (Flink) Flink -> streaming features -> Redis + offline
3 retrieval: user embedding -> ANN (HNSW) top-500, filter in_stock nightly: train two-tower; embed 5M items; rebuild index
4 ranking: item features (pipelined) -> batcher -> Triton GPU nightly: train ranker on PIT training set from prediction log
5 rules: dedupe, diversity, business filters -> top-20 registry: aliases @champion/@challenger
6 log features + scores + model versions -> Kafka monitoring: drift, freshness, CTR by slice
7 fallback: popularity list per category from batch scoring shadow 10% to challenger ranker4. Decisions.
| Decision | Choice | Reason | Alternative |
|---|---|---|---|
| Two-stage retrieval + ranking | ANN top-500 then GPU ranker | Ranking 5M items per request is impossible | Batch-precomputed lists only (stale) |
| Vector store | Qdrant or Milvus cluster (or pgvector at this size) | 5M vectors, filters on stock and category | Elasticsearch kNN if search already runs there |
| Online store | Redis cluster, entity key = user_id / item_id | Sub-ms reads, pipelines | DynamoDB for managed ops |
| Session features | Flink, 1-minute windows | "Within a minute" requirement | Request-time from recent events in Redis |
| Ranker serving | Triton, dynamic batching, 2 instances per GPU | Throughput per GPU | KServe with Triton runtime for K8s operations |
| Rollout | Shadow → canary → A/B on CTR and revenue per session | Health and value separately | Bandit for short-lived promos only |
| Fallback | Batch popularity per category in Redis | Page always renders | Empty module |
| Feedback loop control | 5% exploration traffic, logged propensities | Model not trained only on its own choices | None (loop degrades diversity) |
The fan-out of results into a feed is covered in Feeds; the keyword half of search in Search Systems.
Choosing
Which deployment mode
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Score per entity, changes daily | Batch scoring | Write to Redis; precompute fallbacks | Cheapest and simplest |
| Input only known at request time | Online inference | Feature store + batching | Batch cannot know the input |
| Every event must be scored, no user waiting | Streaming inference | Kafka consumer + model server | Throughput, no sync coupling |
| Privacy or offline use, tiny latency | Edge inference | Quantised model, staged app rollout | No network |
| LLM generation | Online with streaming | vLLM, prefix cache, token budgets | Token-by-token output |
Which serving technology
| Situation | Recommendation | Reason |
|---|---|---|
| GPU models, many frameworks | NVIDIA Triton | Dynamic batching, instance groups, ensembles |
| Kubernetes platform for many teams | KServe (with Triton/vLLM runtimes) | CRD, autoscaling, canary, scale to zero |
| TensorFlow SavedModels only | TensorFlow Serving | Mature, simple |
| Python team, quick productionisation | BentoML | Packaging and adaptive batching |
| Inference graphs, Kafka pipelines | Seldon Core 2 | Pipelines and experiments |
| LLMs | vLLM | PagedAttention, continuous batching, OpenAI API |
| New PyTorch project | Not TorchServe (limited maintenance); Triton or KServe | Maintenance status |
Which vector store
| Situation | Recommendation | Reason |
|---|---|---|
| Under ~10M vectors, data already in Postgres | pgvector (HNSW) | One database, SQL filters, transactions |
| Heavy filtering, self-hosted | Qdrant | Payload indexes, filterable HNSW |
| Hundreds of millions to billions | Milvus (IVF-PQ, DISKANN, GPU) | Distributed, disk-based indexes |
| Search engine already in place, hybrid needed | Elasticsearch / OpenSearch kNN | BM25 + kNN in one query |
| No ops team | Pinecone or a managed Qdrant/Milvus/Weaviate | Managed scaling |
| Built-in hybrid and modules | Weaviate | Hybrid query, dynamic index |
Which feature store
| Situation | Recommendation | Reason |
|---|---|---|
| One or two models, small team | Warehouse tables + Redis, written by your pipeline | Avoid a platform you do not need yet |
| Several teams, open source, own infra | Feast | Definitions, PIT joins, many stores |
| Streaming features at scale, managed | Tecton | Managed stream/batch/real-time features |
| Integrated platform with registry | Hopsworks or the cloud vendor's store | Fewer moving parts |
In architecture: from a single process to a distributed system
ML adds three things to the usual architecture story: a second data path (offline training), a compute-heavy tier (GPUs), and a loop back from production to training.
Monolith: one process, one database
A Laravel shop adds "similar products". Simplest correct version: a nightly Artisan command embeds item descriptions with a hosted embedding API and stores them in a vector column in the same PostgreSQL; the product page calls whereVectorSimilarTo with the item's own embedding and caches the result per item for an hour. No model server, no feature store; the "model" is an API and a table. Correctness rules already apply: store the embedding model name per row, never mix models, and log which items were shown. Batch scoring (a nightly "top sellers per category" table) is the fallback.
Modular monolith: boundaries without the network
The recommendation code becomes a module with its own tables (item_embeddings, user_features, prediction_log) and a public interface (Recommendations::forUser($id)); other modules may not read its tables. This stops undeclared consumers inside one codebase. The training pipeline (Python, outside the monolith) reads a replica or warehouse export and writes features through the module's writer (the OnlineFeatureStore class), so the schema and key layout have one owner.
Microservices: what crosses the boundary
A recs service owns retrieval and ranking; a model server (Triton on KServe) is a separate deployment; the feature store is a platform service. Flow for one request:
1 web -> GET /recs?user=42 (deadline 150 ms) recs service
2 recs -> Redis cluster HMGET fv:user_ctr:42 online store (platform)
3 recs -> Qdrant search (user embedding, filter in_stock) vector service
4 recs -> Triton gRPC ModelInfer (batch 500 rows, deadline 60 ms) model server
5 recs -> Kafka produce predictions {features, scores, model: ranker:9}
6 recs -> web 200 [20 items] (fallback list on any timeout)What does not survive the boundary: transactions between the feature write and the model read (features are eventually consistent; flag staleness), and implicit contracts (the model server's input schema must be versioned with the model in the registry). Timeouts and retries per hop follow Timeouts, Retries & Jitter; a failing model server is isolated with a Circuit Breaker and Bulkheads.
Distributed data: replicas, caches, regions
The online store is replicated per region; materialization writes to each region or the store replicates asynchronously, so a region may serve slightly older features (monitor freshness per region). Vector indexes are sharded by id with replicas for read QPS; an item update must reach the index before it is recommendable, so "new item visible within an hour" is an index-update SLO, and deletes (out of stock, takedown) need a fast path, usually a filter on a frequently updated attribute rather than waiting for re-indexing. Prediction caches must include the model version and be invalidated by rollouts. The offline store is the warehouse; training reads it, never the OLTP primary (OLTP vs OLAP). Replication mechanics are in Replication Topologies, sharding in Sharding at System Level.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x (100 req/s) | Model on CPU in the app or one KServe pod; pgvector; batch features in Postgres; nightly retrain by cron | Simplicity wins; log features from day one |
| 10x (1,000 req/s) | GPU model server with dynamic batching; Redis online store; feature store definitions; orchestrated pipeline; shadow + canary | Batching and feature fetch dominate latency |
| 100x (10,000+ req/s, many models) | KServe/Triton fleet autoscaled on queue time; dedicated vector cluster sharded and replicated; streaming features in Flink; registry-driven CD; per-model cost dashboards; multi-region online stores | GPU cost, freshness across regions and platform governance dominate |
Lab
Steps 1–3 are single-process Go programs and were run on a laptop (outputs below are real). Steps 4–6 need PostgreSQL, Triton or KServe and are written as expected, not run.
1. Gateway tests.
$ cd docs/snippets/system-design/ml-systems-architecture/go && go test ./gateway -v
--- PASS: TestBatcherCombinesConcurrentRequests # 8 concurrent rows -> 1 model call of batch 8
--- PASS: TestBatcherFlushesAfterMaxDelay # a lone row waits ~5 ms, not forever
--- PASS: TestBatcherShedsWhenQueueFull # ErrQueueFull instead of an unbounded queue
--- PASS: TestGatewayFallsBackWhenModelIsSlow # 500 ms model, 30 ms deadline -> fallback 0.01
--- PASS: TestGatewayCachesByModelVersion # second call: no feature read, no model call
--- PASS: TestGatewayColdStartAndStaleFeatures # defaults for new users; 3h-old features flagged
--- PASS: TestShadowNeverAffectsTheResponse # failing or slow shadow: same answer, same latency
--- PASS: TestHTTPModelSpeaksOpenInferenceProtocol
ok academy/ml-systems-architecture/gateway2. Point-in-time join. go test ./pit -v passes three tests: the naive join gives every row the latest value 25, the as-of join returns none/9/11/none with a 2-hour TTL, and the created-timestamp filter returns 9 at 15:00 because the 11 was written the next day.
3. Recall vs latency. go run ./cmd/recall (measured; your timings will differ):
built IVF nlist=128 over 20000 x 64 in 725ms
nprobe recall@10 scanned per query
flat 1.000 20000 549µs
1 0.501 165 12µs
2 0.679 307 16µs
4 0.836 614 27µs
8 0.937 1237 47µs
16 0.983 2462 88µs
32 0.997 4906 169µs
128 1.000 20000 655µsReading it: each doubling of nprobe doubles the work; recall climbs fast and then flattens. Probing every list is an exact scan and is slower than flat because of the centroid step.
4. pgvector recall (expected, not run). Load 1M rows into item_embeddings (schema in the SQL snippet), build HNSW, then for 100 sample queries compare the top-10 from the index with the top-10 under SET LOCAL enable_indexscan = off.
-- expected, not run (shape of the result; numbers depend on data)
ef_search = 10 recall@10 ~0.80 ~1 ms
ef_search = 40 recall@10 ~0.95 ~2 ms (default)
ef_search = 200 recall@10 ~0.99 ~6 ms5. Filter starvation (expected, not run). With a filter matching 10% of rows and default hnsw.ef_search = 40, SELECT ... WHERE category_id = 12 ORDER BY embedding <=> $1 LIMIT 10 returns about 4 rows (pgvector README); after SET LOCAL hnsw.iterative_scan = relaxed_order it returns 10. The Go test TestPostFilterReturnsTooFewResults shows the same effect.
6. Triton batching (expected, not run). Run perf_analyzer -m ctr --concurrency-range 1:32 with dynamic_batching off, then on with max_queue_delay_microseconds: 2000. Expected shape: at concurrency 1 the latency rises by up to ~2 ms; at concurrency 16+ throughput rises several-fold while p99 stays inside budget. Record the curve and pick the delay from it.
Common misconceptions
| Belief | Reality |
|---|---|
| The model is most of the system | Sculley et al.: at most ~5% ML code in a mature system; the rest is glue, data and infrastructure |
| Good offline metrics guarantee production quality | Skew, leakage and drift break that link; log served features and monitor |
| A feature store is just Redis | Redis may be the online half; history, definitions and PIT joins are the point |
| Joining on user id is fine for training data | It leaks the future; use as-of joins |
| Canary proves the model is better | It proves health; A/B with a business metric proves value |
| Shadow traffic is free | It doubles inference cost for the sampled share and must never affect latency |
| GPU utilisation 100% means efficiency | Batch size and throughput at target p99 measure efficiency |
| Vector search is exact | ANN trades recall for speed; measure recall@k |
| Adding a WHERE clause to vector search is enough | Post-filtering can return fewer than k; use iterative or filter-aware search |
| Drift monitoring replaces accuracy monitoring | Drift is a proxy; compute real performance when labels arrive |
| RAG removes hallucinations | Only when retrieval finds the right context; measure retrieval recall |
| Removing a sensitive column removes bias | Proxies remain; measure outcomes per group |
| Retraining more often always helps | Without validation and gates it ships bad data faster; feedback loops get stronger |
Cheat sheet
| Topic | Remember |
|---|---|
| Lifecycle | Validate → features → train (PIT) → evaluate → register → serve → monitor → retrain |
| MLOps levels | 0 manual, 1 pipeline + CT, 2 CI/CD of pipelines |
| Skew | Log served features (Rules of ML #29); one definition for both paths |
| Feature store | Offline history + online latest per entity key, materialization, TTL |
| Point-in-time | As-of join, TTL relative to each row, created-timestamp filter for backfills |
| Registry | Version + lineage + alias; serve by alias; log version per prediction |
| Deployment modes | Batch if slow-changing; online if input arrives with the request |
| Rollouts | Shadow (behaviour) → canary (health) → A/B (value); bandits for short-lived arms |
| Serving | Standard protocol (Open Inference Protocol); Triton/KServe/vLLM; avoid TorchServe for new work |
| Batching | Delay from the budget; bounded queue; shed load |
| Caching | Key includes model version; skip stale features; warm-up before ready |
| LLM | Prefix caching (static prefix first), token budgets, streaming, guardrails, eval gates |
| Vector DB | pgvector to ~10M with SQL filters; dedicated engines beyond; one embedding model per index |
| ANN knobs | pgvector hnsw.ef_search 40, ivfflat.probes 1; tune to recall target |
| Monitoring | Freshness, latency, drift, prediction bias, delayed-label performance, feedback holdout |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name four of the debt items from Sculley et al. and the architectural fix for each. Good to know
Answer
Answer: Undeclared consumers (serve predictions only through an authenticated API), unstable data dependencies (versioned feature definitions and data validation), feedback loops (exploration traffic, holdouts, bandits), glue code and pipeline jungles (feature store and orchestrated pipelines), configuration debt (review configs as code), dead experimental codepaths (flags with expiry, registry aliases). See Hidden technical debt.
2 — What is the difference between training-serving skew and data drift? Must-know
Answer
Answer: Skew is your system computing different features (or seeing different data) for training and serving at the same moment; it exists from day one. Drift is the world changing over time so that the live distribution differs from the training one. See Skew and Monitoring.
3 — Why does an online store keep only the latest value per entity key, and where does history live? Important
Answer
Answer: Serving needs the current value in milliseconds, so the online store is a key-value lookup; Feast: "for each entity key, only the latest feature values are stored". History with event timestamps lives in the offline store, which training reads with point-in-time joins. See Feature store.
4 — A label row is at 15:00. Feature rows exist at 12:00 (written 12:00) and 14:00 (written the next day). TTL is 4 hours. What does a point-in-time join return with and without the created-timestamp filter? Good to know
Answer
Answer: Without the filter: the 14:00 value (it is the newest at or before 15:00 within the TTL). With the filter: the 12:00 value, because the 14:00 row was not available at 15:00. See Point-in-time and the pit tests.
5 — Your canary of a new ranker is healthy. Can you promote it? Important
Answer
Answer: It is safe, not proven better. Run an A/B test on a pre-registered business metric with enough users, or accept the risk explicitly; shadow logs give a score comparison but no outcomes. See Rollouts.
6 — How does Triton's max_queue_delay_microseconds affect latency and throughput? Important
Answer
Answer: When a full or preferred-size batch cannot be formed, Triton waits up to that delay for more requests; batches become larger (higher throughput) at the cost of up to that delay added to latency. At low load it mainly adds latency; at high load batches fill before the delay. See Batching.
7 — Why must a prediction cache key include the model version? Must-know
Answer
Answer: Otherwise, after a rollout, users get the old model's scores labelled as the new model, the logs lie, and an A/B comparison is contaminated. See Caching and autoscaling and the Go PredictionCache.
8 — A pgvector query with WHERE category_id = 12 returns 4 rows instead of 10. Why, and what are two fixes? Important
Answer
Answer: The HNSW index returns ef_search (40) candidates and the filter (10% selectivity) is applied after, leaving about 4. Fixes: enable hnsw.iterative_scan (pgvector 0.8.0+), raise ef_search, use a filter-aware engine (Qdrant payload index), or exact search on a small filtered subset. See Filtering and hybrid.
9 — What does prefix caching require from your prompt design? Good to know
Answer
Answer: An identical prefix: put static content (system prompt, instructions, shared documents) first and variable content (user question) last, so KV-cache blocks for the prefix can be reused. See LLM serving.
10 — Labels for your fraud model arrive 30 days late. What do you monitor in the meantime? Important
Answer
Answer: Input data drift per important feature, prediction distribution (mean score, share above threshold), feature freshness, serving latency and errors, and action limits (e.g. share of transactions blocked); compute real precision/recall when labels arrive. See Monitoring.
11 — In the worked design, why two stages (retrieval then ranking)? Must-know
Answer
Answer: Ranking every one of 5M items per request with a heavy model is far beyond any budget; ANN retrieval cheaply narrows to ~500 candidates that a GPU ranker can score in one batch within tens of milliseconds. See Worked design.
Glossary
| Term | Meaning |
|---|---|
| ML system | The model plus data, features, training, serving and monitoring infrastructure around it |
| MLOps | Practice of automating and monitoring the whole ML lifecycle (Google: unify ML development and operation) |
| Lifecycle | Data → features → training → evaluation → registry → serving → monitoring → retraining |
| Continuous training (CT) | Automatic retraining and redeployment triggered by schedule, new data or drift |
| Hidden technical debt | System-level ML maintenance cost (Sculley et al. 2015) |
| CACE | "Changing Anything Changes Everything": entanglement of features and settings |
| Undeclared consumer | A system silently using a model's outputs |
| Feature | An input value to a model, derived from raw data |
| Feature store | System that defines features once and serves them for training (offline) and serving (online) |
| Offline store | Historical, time-stamped feature values for training and materialization |
| Online store | Latest feature value per entity key for low-latency serving |
| Entity key | Primary key that features belong to (user_id, item_id, driver_id) |
| Materialization | Copying feature values from the offline source to the online store |
| TTL | Maximum age of a feature value that still counts (online expiry, offline join window) |
| Point-in-time correctness | Each training row sees feature values as of its own timestamp |
| As-of join | Join that picks the newest row at or before a timestamp |
| Data leakage | Training data containing information not available at prediction time |
| Training-serving skew | Difference between training and serving behaviour from data or pipeline differences |
| Feature freshness | Age of the newest feature value at serving time |
| Batch features | Features computed on a schedule over historical data |
| Streaming features | Features computed continuously from event streams |
| On-demand feature | Feature computed at request time from request data |
| Backfill | Recomputing historical feature values for a new or fixed definition |
| Data validation | Declared checks on schema, ranges and distributions of data |
| Great Expectations | Python data validation library with expectation suites |
| TFDV | TensorFlow Data Validation: statistics, schema, anomaly, drift and skew detection |
| Model registry | Catalogue of model versions with metadata, aliases and lineage |
| MLflow | Open-source tracking, registry and evaluation platform |
| Model alias | Mutable named pointer to a model version (@champion) |
| Lineage | Graph from data and code to model version to deployment |
| Reproducibility | Ability to re-run training and get an equivalent model |
| Batch scoring | Precomputing predictions for many entities on a schedule |
| Online inference | Synchronous prediction per request within a latency budget |
| Streaming inference | Predictions computed from events flowing through a stream |
| Edge inference | Running the model on the user's device |
| Shadow deployment | Mirroring traffic to a new model whose answers are only logged |
| Canary | Gradual rollout to a small, increasing share of traffic with rollback |
| A/B test | Randomised controlled comparison of variants on a metric |
| Multi-armed bandit | Adaptive allocation of traffic toward better-performing arms |
| Blue/green | Two full environments; traffic flips from one to the other |
| Champion/challenger | Standing comparison of the live model with candidate models |
| Model serving | Hosting models behind an inference API |
| Open Inference Protocol | KServe v2 REST/gRPC inference API (/v2/models/.../infer) |
| NVIDIA Triton | Multi-framework inference server with dynamic batching |
| KServe | Kubernetes model-serving platform (InferenceService) |
| TensorFlow Serving | Serving system for TensorFlow models |
| TorchServe | PyTorch model server, now in limited maintenance |
| Seldon Core 2 | Kubernetes-native MLOps serving framework |
| BentoML | Python library for building model-serving services |
| vLLM | LLM inference and serving engine with PagedAttention |
| Dynamic batching | Server or client combining requests into batches within a delay |
| Continuous batching | LLM batching that adds/removes sequences at each generation step |
| GPU utilisation | Share of time GPU kernels run; not the same as useful throughput |
| Quantisation | Lower-precision weights/activations (INT8, FP8, INT4) to save memory and compute |
| Prediction cache | Cache of scores keyed by model version and input or entity |
| Warm-up | Synthetic requests before a model is marked ready |
| Cold start | Slow first requests after a scale-up or model load |
| Autoscaling | Adjusting replicas from metrics (HPA, KEDA, Knative) |
| Feature fetching | Reading online features for the entities in a request |
| LLM | Large language model |
| PagedAttention | KV-cache memory management in blocks, like virtual memory paging |
| KV cache | Stored attention keys/values of processed tokens |
| Prompt caching | Reusing computation for a repeated prompt prefix |
| Token budget | Limit on input/output tokens per request or tenant |
| Streaming response | Returning tokens as generated (SSE) |
| Guardrails | Input/output checks around an LLM |
| Evaluation | Offline and online measurement of model quality as a release gate |
| RAG | Retrieval-augmented generation: retrieve context, then generate |
| Embedding | Dense vector representation of an object |
| Vector database | Store with ANN indexes, metadata filters, sharding for vectors |
| kNN | k-nearest neighbours; exact when every vector is compared |
| ANN | Approximate nearest neighbour search with an index |
| HNSW | Hierarchical Navigable Small World graph index |
| IVF | Inverted file index: k-means lists, scan nprobe lists |
| Product quantisation | Compressing vectors into codes from sub-vector codebooks (PQ) |
| DiskANN | SSD-resident graph ANN index for billion-scale data |
| Recall | Share of true nearest neighbours returned (recall@k) |
| Metadata filtering | Restricting vector search by attributes |
| Hybrid search | Combining keyword (BM25) and vector results (RRF, re-ranker) |
| RRF | Reciprocal rank fusion: sum of 1/(k + rank) across result lists |
| pgvector | PostgreSQL extension for vectors, HNSW and IVFFlat |
| Qdrant | Vector database with payload indexes and filterable HNSW |
| Milvus | Distributed vector database with many index types |
| Weaviate | Vector database with HNSW, flat and dynamic indexes and hybrid search |
| Pinecone | Managed vector database |
| Data drift | Change in the input distribution |
| Concept drift | Change in the input-to-label relationship |
| Delayed labels | Ground truth arriving long after the prediction |
| Feedback loop | Predictions influencing future training data |
| Prediction bias | Predicted label distribution differing from observed (Sculley) |
| Evidently | Open-source data quality, drift and model monitoring framework |
| WhyLabs | Data and model monitoring platform |
| Explainability | Attributing predictions to inputs |
| SHAP | Shapley-value based explanation method |
| Bias | Systematically different outcomes or errors across groups |
| PII | Personally identifiable information |
| Airflow | DAG-based workflow scheduler |
| Kubeflow | ML platform on Kubernetes; Kubeflow Pipelines for ML DAGs |
| Dagster | Asset-oriented data orchestrator |
| GPU cost | Cost of accelerators, managed as cost per 1k predictions or per 1M tokens |
| Recommendation system | System that retrieves and ranks items for a user |
| Two-tower model | Separate user and item encoders whose embeddings are compared for retrieval |
References
- D. Sculley et al., "Hidden Technical Debt in Machine Learning Systems", NeurIPS 2015 (PDF)
- Google, Rules of Machine Learning: Best Practices for ML Engineering
- Google Cloud, MLOps: Continuous delivery and automation pipelines in machine learning
- Chip Huyen, Designing Machine Learning Systems, O'Reilly 2022 (author's books page; not quoted)
- Feast: Point-in-time joins, Online store, Offline store, Feature view; Tecton docs; Hopsworks docs
- Great Expectations docs; TensorFlow Data Validation
- MLflow: Model Registry, documentation
- KServe: home, canary rollout example; Open Inference Protocol REST spec
- NVIDIA Triton: server repository, dynamic batcher, model configuration
- TensorFlow Serving; TorchServe repository and docs; Seldon Core 2; BentoML
- vLLM: documentation, Automatic Prefix Caching design; W. Kwon et al., "Efficient Memory Management for Large Language Model Serving with PagedAttention", SOSP 2023
- Y. Malkov, D. Yashunin, "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs"; J. Johnson, M. Douze, H. Jégou, "Billion-scale similarity search with GPUs"; S. J. Subramanya et al., "DiskANN", NeurIPS 2019
- pgvector README; Qdrant indexing and filtering; Milvus index overview and DISKANN; Weaviate vector indexing; Pinecone docs; Elasticsearch kNN search
- Evidently docs; WhyLabs docs; SHAP docs
- Orchestration: Apache Airflow, Kubeflow Pipelines, Dagster; Kubernetes Horizontal Pod Autoscaling
- Laravel 13: HTTP Client, Redis, Query Builder (vector similarity clauses), Migrations (vector columns), Pennant
- Go: google.golang.org/grpc, github.com/redis/go-redis/v9