Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why ML systems rot faster than other codeWhy it exists, Hidden technical debt
Sculley 2015, Rules of ML, MLOps levels, HNSW, FAISS, DiskANNWhere it comes from
Lifecycle, skew, feature store, point-in-time joinsLifecycle, Skew, Feature store, Point-in-time
Feature pipelines, backfills, data validationFeature pipelines, Data validation
Registry, lineage, reproducibilityModel registry
Batch, online, streaming, edge inferenceDeployment modes
Shadow, canary, A/B, bandits, blue/greenRollouts
Triton, KServe, TF Serving, TorchServe, Seldon, BentoML, vLLMModel serving
Batching, GPUs, quantisation, caching, cold startsBatching, Caching and autoscaling, Feature fetching
LLMs, prompt caching, RAG, guardrailsLLM serving, RAG
Embeddings, HNSW, IVF, PQ, DiskANN, filters, hybrid searchVector databases, ANN indexes, Filtering and hybrid
Drift, delayed labels, feedback loopsMonitoring
Bias, SHAP, PIIResponsible ML
CI/CD, Airflow, Kubeflow, Dagster, costMLOps CI/CD, Cost
Knobs and numbersMechanics
CodeGo, Laravel
Fixes for the classic failuresSolving the classic problems
A full recommendation-service designWorked design
Which option to pickChoosing
Monolith to distributed systemIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The lifecycle, box by box.

StageIn plain wordsTypical productWhat goes wrong
Data validationCheck inputs before they become featuresGreat Expectations, TFDVSilent schema or unit change upstream
Feature pipelinesTurn raw events into model inputsSpark, dbt, Flink, Feast transformationsPipeline jungle; different code for training and serving
Feature storeOne definition, offline history + online latestFeast, Tecton, Hopsworks, Vertex AI Feature StoreLeakage from naive joins; stale online values
TrainingFit the model on point-in-time correct dataKubeflow Pipelines, Airflow, Dagster, SageMakerNot reproducible: unknown data snapshot or seed
EvaluationGate: is it better than the champion, on which slices?MLflow evaluate, customAverage improves, one segment collapses
Model registryVersions, lineage, aliases like @championMLflow Model Registry, Vertex AI, SageMaker"Which model made this prediction?" has no answer
ServingAnswer predictions under a latency budgetTriton, KServe, TF Serving, BentoML, vLLMGPU at batch 1; no fallback; cold starts
MonitoringWatch inputs, outputs, freshness, latency, costEvidently, WhyLabs, PrometheusModel degrades silently; labels arrive weeks later
RetrainingClose the loop on schedule or on driftPipeline trigger, continuous training (CT)Feedback loop retrains on the model's own choices

Deployment and rollout patterns.

PatternWho sees the new modelLearnsUse when
Batch scoringEveryone, from a precomputed tableOffline metrics onlyScores change slowly; daily churn or lead scores
Online inferenceEach request, synchronouslyLatency, live behaviourInput known only at request time (fraud, ranking)
Streaming inferenceEach event, asynchronouslyThroughput, lagScore every transaction or click off a Kafka topic
Edge inferenceThe device, offlineOn-device metricsPrivacy, no network, sub-10 ms (keyboard, camera)
Shadow deploymentNobody; copy of traffic, loggedLatency, errors, score diffFirst production contact for a new model
Canary1-10%, increasingHealth under real loadEvery rollout of a model server or version
A/B testRandom sticky splitBusiness metric, with significanceDeciding whether the model is actually better
Multi-armed banditSplit adapts to rewardOptimises while learningMany arms, short-lived content (headlines, promos)
Champion/challengerChampion serves, challenger competesComparison on the same trafficStanding process for every retrain

Serving and retrieval in one table.

ConcernKnobProduct exampleNumber to remember
Throughput on GPUDynamic batching delay and sizeTriton max_queue_delay_microseconds, preferred_batch_sizeA few ms of delay can multiply throughput (measure it)
LLM memoryKV-cache paging, continuous batchingvLLM PagedAttentionPaper: 2-4x throughput at the same latency
Repeated promptsPrefix (prompt) cachingvLLM Automatic Prefix CachingReuses KV blocks for an identical prefix
Feature fetchOne round trip per requestRedis HMGET, DynamoDB BatchGetItemBudget a few ms of the total
ANN recall vs latencySearch widthpgvector hnsw.ef_search (default 40), ivfflat.probes (default 1)Raise until recall@k meets the target
Filtered vector searchIterative scan / filter-aware graphpgvector hnsw.iterative_scan, Qdrant payload indexPost-filtering can return fewer than k
Billion-scale ANNGraph on SSDDiskANN, Milvus DISKANNPaper: 1B points, 64 GB RAM, under 3 ms mean
Data sourcesevents, OLTP, logsData validationschema, rangesFeature pipelinesbatch + streamingFeature storeOffline: full historyOnline: latest per entity keymaterialize offline to onlineTrainingpoint-in-time joinEvaluation + registrymetrics gate, version,lineage, alias @championServingbatch | online |streaming | edgeMonitoringdrift, freshness,latency, costRetrainingschedule, drift,delayed labelsML codea small part of the system(Sculley et al. 2015)online features at request time

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 serviceAn ML service
Behaviour is defined by codeBehaviour is defined by code + data + training config
A test proves a functionTests prove the code; monitoring proves the model still fits the world
Bugs throw errorsBugs produce plausible wrong numbers
One artefact: the binaryThree artefacts: code, data snapshot, model weights
Deploy once, works until changedDegrades without any deploy (drift)
Latency mostly I/OLatency often compute-bound on GPUs; batching matters
Rollback = previous binaryRollback = previous model and the features it expects
Inputs come from the requestInputs 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 ​

  1. "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.
  2. "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.
  3. "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 ​

YearSourceWhat it added
2015Sculley et al., Hidden Technical Debt in Machine Learning Systems, NeurIPSThe vocabulary: entanglement, CACE, undeclared consumers, data dependencies, feedback loops, glue code, pipeline jungles, configuration debt
2016Malkov & Yashunin, HNSW (arXiv 1603.09320)Multi-layer proximity graphs with "logarithmic complexity scaling"; the default ANN index in most vector databases today
2017Johnson, 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 LearningEngineering rules: launch without ML first, log features at serving time, measure training/serving skew
2019Subramanya et al., DiskANN, NeurIPSSSD-resident graph index: a billion points on one 64 GB machine
2024 (last reviewed)Google Cloud, MLOps: Continuous delivery and automation pipelines in machine learningMLOps levels 0, 1, 2; CI, CD and continuous training (CT); feature store as a pipeline component
2023Kwon 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 itemWhat it meansArchitecture answer on this page
Entanglement / CACE"Changing Anything Changes Everything": features are not independentVersion everything; evaluate per slice; shadow before rollout
Correction cascadesModel B learns a fix on top of model AFeature in one model, or a separate model; registry lineage shows the chain
Undeclared consumersOther systems silently read your predictionsServe through an API with auth; log consumers; no shared prediction tables without contracts
Unstable data dependenciesInput signals change under youVersioned feature definitions; data validation at the boundary
Underutilized data dependenciesFeatures that add little but can break thingsLeave-one-feature-out evaluation; delete features
Feedback loops (direct, hidden)The model influences its own future training dataExploration traffic, holdout groups, bandits, logging propensities
Glue code, pipeline junglesMost code moves data in and out of packagesFeature store and orchestrated pipelines with one definition
Dead experimental codepathsOld if branches for experimentsRollout flags with expiry; registry aliases instead of code branches
Configuration debtConfig lines outnumber code linesConfigs reviewed and diffed like code; pipeline parameters in the registry
Changes in the external worldFixed thresholds, driftMonitoring with alerts; learned thresholds; continuous training
Monitoring and testing debtUnit 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 debtCannot re-run training and get the same modelData 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."

text
     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 automated

Real 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:

ProductRole in the loopNote
Kubeflow PipelinesPipeline definition and execution on KubernetesContainerised steps, artefact tracking
Apache AirflowGeneral DAG schedulerMost common orchestrator for feature and training jobs
DagsterAsset-oriented orchestrationModels features and models as data assets with lineage
MLflowTracking, registry, evaluationOpen source; managed on Databricks
Vertex AI / SageMakerManaged pipelines, registry, endpointsCloud 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).

text
     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 again

Real 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):

DebtMitigationProduct feature
Undeclared consumersPredictions only through an authenticated APIAPI gateway auth; KServe/Seldon endpoints
Unstable inputsVersioned features with ownersFeast feature views, Tecton feature definitions
Data dependency trackingLineage graphMLflow lineage, Dagster assets, OpenLineage
Dead experimental pathsFlags with an owner and expiryLaravel 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."

text
     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 logged

Real 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:

TechniqueHowProduct
One feature definition for both pathsDefine once; offline and online read the same logicFeast feature views, Tecton, Hopsworks
Log features at serving timeTrain on what serving saw (Rules of ML #29)Prediction log to Kafka/warehouse
Re-use codeSame library in both pipelines (Rules of ML #32)Shared feature package, on-demand transforms
Measure skewCompare logged vs recomputed featuresTFDV 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.

Batch pipelineSpark / dbt, dailyStreaming pipelineKafka + Flink, secondsRegistry: feature definitionsentity, schema, source, TTL, ownerOffline store (history)BigQuery, Snowflake, Parquet, Postgresuser 42 | 08:00 | orders_7d=3user 42 | 12:00 | orders_7d=4user 42 | 20:00 | orders_7d=5Online store (latest only)Redis, DynamoDB, Bigtable, Cassandrafv:user_ctr:42 -> orders_7d=5TTL 2 days, p99 read in msTrainingpoint-in-time join:value as of eachlabel timestampOnline servingget features byentity key atrequest timematerializepush (stream)
text
     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 history

Real 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:

ProductOffline storeOnline storeNotes
Feast (open source)BigQuery, Snowflake, Redshift, Spark, Postgres, filesRedis, DynamoDB, Bigtable, Postgres, othersLibrary + optional feature server; you run the infra
Tecton (managed)Managed on the warehouse/lakeManaged (DynamoDB or Redis backed)Batch, streaming and real-time feature definitions
HopsworksOffline feature groups (lakehouse tables)RonDB onlineFeature store plus model registry ("connected by a shared feature store and model registry")
Vertex AI / SageMaker Feature StoreBigQuery / S3Managed online servingCloud-native, IAM-integrated
DIYWarehouse tables with event timestampsRedis hashes or DynamoDB itemsFine 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".

text
     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
sql
-- 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:

ProductPoint-in-time APINote
Feastget_historical_features(entity_df, features)TTL relative to each entity row; optional filter_by_created_timestamp
Tectonget_features_for_events style historical retrievalManaged as-of joins
Spark / DatabricksAs-of joins, window functionsYou write the logic
PostgreSQLLEFT JOIN LATERAL ... ORDER BY event_ts DESC LIMIT 1Needs an index on (entity, event_ts)
Snowflake / BigQueryASOF JOIN (Snowflake), window + filterEngine-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.

text
     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 values

Real 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 typeComputeStore pathFreshness
BatchSpark, dbt, BigQuery SQLOffline, then materialize to onlineHours to a day
StreamingFlink, Kafka Streams, Spark Structured StreamingPush to online and offline (Feast push source)Seconds
On-demandRequest-time Python or Go transformNot stored, or loggedRequest time
BackfillBatch job over historyOffline 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.

text
     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:

ProductStyleNote
Great Expectations (GX Core)Declarative expectation suites in PythonRuns in Airflow/Dagster steps
TFDVSchema inference + anomaly, drift and skew detectionPart of TFX
EvidentlyData quality and drift test suitesAlso monitoring dashboards
dbt testsSQL tests on warehouse modelsnot_null, accepted_values, custom
Pandera / DeequDataFrame 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.

text
     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 rebuild

Real 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:

ProductVersionsStage/aliasLineage
MLflow Model RegistryYesAliases (@champion), tagsRun, logged model, dataset
Vertex AI Model RegistryYesAliases, version defaultVertex pipelines metadata
SageMaker Model RegistryModel packagesApproval statusPipeline lineage
HopsworksYesTagsTied to feature groups
Weights & BiasesArtifactsAliasesRun 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.

text
     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 offline

Real 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:

ModeCommon stackMain cost
Batch scoringSpark, BigQuery ML, Airflow + model libraryCompute per run; stale between runs
Online inferenceTriton, KServe, TF Serving, BentoML behind a gatewayAlways-on capacity, GPUs
Streaming inferenceKafka + Flink or a consumer service calling a model serverConsumer lag, exactly-once concerns
Edge inferenceTensorFlow Lite / LiteRT, Core ML, ONNX Runtime, ExecuTorchModel 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).

Shadowchampion 100%copy to challengerusers see: champion onlylearns: latency, errors,score diff (no outcome)Canary95% / 5%, then 25, 50, 100users see: 5% challengerlearns: health under realtraffic; auto rollbackA/B test50 / 50 by hash(user_id)users see: either, stickylearns: business metricwith significanceBanditsplit adapts to rewardusers see: mostly bestlearns: while exploiting;weaker causal evidenceexposure of users to the new model and speed of learning both grow left to right
text
     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 rollback

Real 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:

ProductShadowCanaryA/B / bandit
KServeVia Knative/Istio mirroringcanaryTrafficPercent on InferenceServiceExternal
Seldon Core 2Experiments with mirrorTraffic splittingExperiments
Istio / Envoymirror routeWeighted routesHeader-based routing
AWS SageMaker endpointsShadow variantsProduction variants with weightsVariant weights
Application codeGateway sampling (this page's Go and Laravel code)Feature flagExperiment 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.

Clientbudget 100 msInference gateway1 Cachemodel ver + entity2 Feature fetchHMGET, ~2 ms3 Batchermax 32 or 5 msFallbackon timeout / shedShadow sample10%, asyncOnline storeRedis / DynamoDBChampion modelTriton / KServe on GPUdynamic batching, warmChallenger (shadow)result logged, never returnedPrediction log (Kafka)features + score + model version
text
     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 ready

Real 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:

ServerStrengthProtocolsNote
NVIDIA Triton Inference ServerMany frameworks (TensorRT, ONNX, PyTorch, TF, Python), dynamic batching, ensemblesHTTP/gRPC, Open Inference ProtocolGPU-first; Model Analyzer for tuning
KServeKubernetes InferenceService CRD, autoscaling, canary, scale to zeroOpen Inference Protocol, OpenAI-compatible for LLMsRuns Triton, vLLM, MLServer and others as runtimes
TensorFlow Serving"flexible, high-performance serving system" for TF SavedModelsgRPC, RESTVersion policies, batching
TorchServePyTorch handlersREST, gRPCRepository marked "Limited Maintenance": "no longer actively maintained"
Seldon Core 2"Kubernetes-native MLOps framework", pipelines, experimentsOpen Inference Protocol (MLServer)Inference graphs, Kafka-based pipelines
BentoML"Python library for building online serving systems"HTTP, gRPCAdaptive batching, packaging to containers
vLLMLLM serving: PagedAttention, continuous batching, prefix cachingOpenAI-compatible HTTPSee 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".

text
     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 1

Real 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:

LayerKnobProduct
Server-side batchingdynamic_batching { max_queue_delay_microseconds, preferred_batch_size }, max_batch_sizeTriton
Queue policymax_queue_size, default_timeout_microseconds, priority_levelsTriton
Instancesinstance_group [{ count: 2, kind: KIND_GPU }]Triton
LLM batchingContinuous batching, chunked prefillvLLM
Client-side batchingBatcher with max size + max delayThis page's Go Batcher
QuantisationTensorRT INT8/FP8, AWQ/GPTQ, ONNX Runtime quantizationTriton, vLLM, ONNX Runtime
Utilisation metricsDCGM 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).

text
     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 hit

Real 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:

ConcernMechanismProduct
Prediction cacheKey = model version + entity or input hash; TTLRedis, in-process LRU, CDN for public scores
Warm-upSynthetic requests before readyTriton ModelWarmup, readiness probes
Cold startPre-pulled images, model on local disk, min replicasKubernetes, KServe minReplicas
AutoscalingHPA on custom/external metricsKubernetes HPA, KEDA, Knative KPA
Scale to zeroActivator buffers first requestKServe 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.

text
     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 + transfer

Real 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:

StoreBatched readNote
RedisHMGET per hash, pipelining, MGETHash per entity keeps one key per row
DynamoDBBatchGetItem (up to 100 items)Single-digit ms typical; check your region
Cassandra / ScyllaDBIN queries per partition, async parallel readsPartition by entity key
Feast feature serverget_online_features with many entity rowsOne 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.

text
     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 tenant

Real 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:

ConcernProduct / mechanismNote
ServingvLLM, NVIDIA TensorRT-LLM / Triton, Hugging Face TGI, SGLangvLLM: OpenAI-compatible server
MemoryPagedAttention, quantisation (AWQ, GPTQ, FP8)Bigger batches per GPU
Prompt cachingvLLM Automatic Prefix Caching; hosted APIs' prompt cachingOrder prompts: static prefix first
Response cacheExact-match or semantic cache in RedisRisky for personalised answers
Token budgetsGateway counters per tenantSame algorithms as Rate Limiting
GuardrailsInput/output validators, policy modelsRun in the gateway, not in the prompt
EvaluationGolden sets, LLM-as-judge, MLflow LLM evaluationRegression 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).

text
     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 streams

Real 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:

StepChoiceNote
ChunkingFixed tokens with overlap, structure-awareChunk size trades context vs precision
EmbeddingsHosted embedding APIs or open modelsRe-embed everything when the model changes
Storepgvector, Qdrant, Milvus, Weaviate, Pinecone, ElasticsearchSee Vector databases
RetrievalVector + keyword (hybrid), metadata filtersACL as a filter, never in the prompt
Re-rankingCross-encoderSmall 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.

text
     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 rows

Real 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:

ProductIndex typesFilteringScale model
PostgreSQL + pgvectorHNSW, IVFFlat; vector up to 2,000 dims indexed, halfvec 4,000SQL WHERE, iterative index scans (0.8.0+)Postgres replicas; shard with Citus
QdrantHNSW with filterable (payload-aware) edgesPayload indexes; planner picks full scan under full_scan_thresholdShards + replicas
MilvusFLAT, IVF_FLAT, IVF_SQ8, IVF_PQ, HNSW, SCANN, DISKANN, GPU indexesScalar indexes and expressionsDistributed, separated storage/compute
WeaviateHNSW, flat, dynamic (flat that switches to HNSW past a threshold)Inverted index filtersShards + replication
PineconeManaged (serverless)Metadata filtersFully managed
Elasticsearch / OpenSearchHNSW dense_vector, knn with k and num_candidatesFilters + BM25 in one engineShards + 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.

IVF / IVF-PQqscan nprobe = 2 of nlist listsPQ codes: 8-64 bytes / vectorHNSWlayer 2layer 1layer 0 (all)greedy descent, beam = efRAM-resident graph, m linksDiskANN (Vamana)graph + full vectors on SSDPQ-compressed vectors in RAM1B points, 64 GB RAM(Subramanya et al. 2019)few SSD reads per queryMilvus DISKANN, Azurelarger nprobe / ef_search: recall goes up, latency and cost go upfast, lower recallslow, recall near 1.0 (= exact kNN)
text
     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 us

Real 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:

IndexMemoryBuildQuery speed / recallUpdates
Flat (exact)Vectors onlyNoneSlow, recall 1.0Trivial
HNSWVectors + graph (m links per node)Slow, memory-heavyFast, high recallIncremental inserts; deletes leave tombstones
IVF-FlatVectors + centroidsFast (k-means), build after data loadsGood; nprobe trades recallLists drift as data changes; rebuild periodically
IVF-PQCompressed codesTrain codebooksFast, lower recall; re-rank with full vectorsRetrain on distribution change
DiskANNPQ in RAM, graph + vectors on SSDHeavyFast for billion scaleEngine-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.

text
     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:

ProductFiltered ANNHybrid
pgvectorhnsw.iterative_scan = strict_order / relaxed_order, hnsw.max_scan_tuples (20,000 default)Combine with Postgres full-text search; RRF or cross-encoder
QdrantPayload indexes + filterable HNSW (build payload indexes first)Sparse + dense vectors, fusion
Elasticsearchknn with filter; num_candidatesBM25 + kNN in one query, RRF
WeaviatePre-filter with inverted indexhybrid query with alpha weighting
MilvusBoolean expressions on scalar fieldsMulti-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.

text
     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 -> retrain

Real 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:

SignalMetricProduct
Data driftPSI, KS test, Wasserstein, Jensen-Shannon per featureEvidently ("Test tabular data quality and data drift"), WhyLabs, TFDV
Prediction drift / biasMean score vs observed rate, per sliceEvidently, custom Prometheus metrics
Performance (when labels arrive)AUC, precision@k, calibrationBatch jobs joining the prediction log
Feature freshnessnow − last write per feature viewPrometheus gauge from the online store
Serving healthp50/p99 latency, error rate, queue time, GPU memoryPrometheus, Triton metrics, DCGM
Feedback loopShare of exploration traffic, holdout comparisonExperiment 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.

text
     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   privacy

Real 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:

ConcernToolNote
ExplainabilitySHAP, LIME, model-native importancesKServe supports explainers alongside predictors
Fairness metricsFairlearn, AIF360, Evidently slicesSlice metrics in the evaluation gate
PII detectionPresidio, DLP APIs, regex + validatorsAt ingestion and in LLM guardrails
Data minimisationHashing, aggregation, retention limitsRetention on prediction logs too
Access controlRow-level security, column maskingSee 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).

text
     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 burn

Real 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:

ProductModelNote
Apache AirflowPython DAGs of tasksMature scheduler; huge operator ecosystem
Kubeflow PipelinesContainerised components on KubernetesArtefacts and metadata built in
DagsterSoftware-defined assetsLineage and freshness policies on assets
Argo WorkflowsKubernetes-native DAGsUsed under Kubeflow
MLflow / DVCExperiment tracking, data versioningReproducibility ids
GitHub Actions / GitLab CICI for pipeline code and imagesTrigger 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.

text
     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 day

Real 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:

LeverTypical effectRisk
Dynamic / continuous batchingHigher throughput per GPUAdded queue latency
QuantisationLess memory, faster kernelsAccuracy loss; must re-evaluate
Prediction and prompt cachingFewer model callsStaleness; cache key mistakes
Smaller / distilled modelsLower cost per requestQuality on hard cases
Autoscaling, scale to zeroPay for useCold starts
Batch instead of onlineCheap compute, spotStaleness

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):

StepBudgetNote
Network client to gateway10 msSame region
Prediction cache lookup1 msIn-process or Redis
Feature fetch (user + 500 items, pipelined)5 msOne round trip per store
Batcher wait5 msMaxDelay; Triton max_queue_delay_microseconds
Model compute on GPU20 msBatch 32
Post-processing, business rules5 msFilters, dedupe
Logging (async)0 ms on pathBuffered producer
Headroom for p9954 msTail latency, retries (Tail latency)

Triton model configuration ​

text
# 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 ​

text
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 time

pgvector knobs ​

KnobDefaultEffect
HNSW m16Max connections per layer; memory and recall
HNSW ef_construction64Build candidate list; recall vs build time
hnsw.ef_search40Query candidate list; recall vs latency
ivfflat listsnone (you set it)rows / 1000 up to 1M rows, sqrt(rows) above (README guidance)
ivfflat.probes1Lists scanned; sqrt(lists) as a start
hnsw.iterative_scanoffstrict_order or relaxed_order to keep scanning under filters
hnsw.max_scan_tuples20,000Upper bound on iterative scanning

Feast and vLLM knobs ​

KnobProductMeaning
ttl on a FeatureViewFeastMax age of a value relative to each entity row in historical retrieval
feast materialize start end / materialize-incrementalFeastCopy offline to online for a time range
Push sourceFeastWrite streaming features directly to online (and offline)
filter_by_created_timestamp=TrueFeastExclude values created after the entity timestamp
--max-num-seqsvLLMSequences in a running batch
--gpu-memory-utilizationvLLMShare of GPU memory for weights + KV cache
--enable-prefix-cachingvLLMAutomatic prefix caching (check your version's default)
--max-model-lenvLLMContext length cap; bounds KV cache per sequence

Error messages you will actually see ​

MessageWhereMeaning / fix
context deadline exceededGo client to model serverDeadline hit; return fallback, do not retry past the budget
gateway: batch queue fullThis page's Go BatcherShed load; scale out; lower delay
Illuminate\Http\Client\ConnectionExceptionLaravel HTTP clientConnect/read timeout; fallback score
UNAVAILABLE / RESOURCE_EXHAUSTEDgRPC to TritonServer overloaded or queue full (timeout_action: REJECT)
CUDA out of memoryPyTorch/vLLMBatch or context too large; lower --max-num-seqs or --gpu-memory-utilization
expected 384 dimensions, not 1536pgvectorQuery embedding from a different model than the column
ERROR: column cannot have more than 2000 dimensions for hnsw indexpgvectorUse 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:

go
// 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:

go
// 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:

go
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:

go
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:

go
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:

go
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:

go
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:

go
// 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
}
go
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:

go
// 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
}
go
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)
	}
}
go
// 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 featureUse hereNote
context.ContextRequest deadline through feature fetch and model callBatches get their own context; shadow gets its own
http.Client{Timeout: ...}Model server callshttp.DefaultClient has no timeout
Channels + select with defaultBounded batch queue that sheds loadNever block a request on a full queue
time.NewTimerBatch max delayStop timers to avoid leaks
sync.WaitGroupWait for shadow calls on shutdownGateway.Wait
github.com/redis/go-redis/v9HMGet for online featuresOne round trip per entity
google.golang.org/grpcgRPC to Triton/KServe with generated v2 stubsgrpc.NewClient; pass the request ctx for deadlines
container/heapTop-k selection in the vector indexO(n log k)
math/rand/v2Shadow sampling; seeded PCG for reproducible test dataSeed everything you want to reproduce
net/http/httptestFake model serverProtocol 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureUseNote
Http::timeout() / connectTimeout()Model callsDefaults are 30 s and 10 s; far too long for inference
Http::retry([20], when: ...)One retry on connection errors onlyNever retry a slow model past the budget
Http::pool()Parallel calls (several models, ensembles)Concurrent requests
Http::fake()Test the client without a model serverAssert payload shape
Redis::pipeline()Materialize features in bulkOne round trip for many commands
Redis::hmget()Read one entity's featuresResult shape differs between phpredis and Predis; normalise
Queued job with QueueableShadow scoring off the request pathOwn queue, $tries = 1
Laravel Pennant Feature::active()Kill switch for shadow or canaryFlags per user or global
Schema::ensureVectorExtensionExists(), $table->vector()pgvector schema->index() creates a cosine vector index
whereVectorSimilarTo, selectVectorDistance, orderByVectorDistanceVector queriesPostgreSQL + pgvector, MariaDB 11.7+
selectRaw / orderByRaw with bindingspgvector operators and knobsBind the vector; never interpolate user input

Solving the classic problems ​

Offline metrics great, production poor (skew) ​

SolutionHowAdvantageCost / limitation
Log served featuresPrediction log with the exact vectorTrain on what serving sawStorage; needs a join to labels
One definitionFeature store views used by both pathsRemoves re-implementationPlatform to run
Skew monitorDaily comparison logged vs recomputedCatches regressions earlyNeeds both values

Leakage in training data ​

SolutionHowAdvantageCost / limitation
As-of joinsFeast get_historical_features, LATERAL joinCorrect by constructionNeeds history with event times
Created-timestamp filterExclude late-written valuesStops backfill leakageNeeds reliable created_ts
Time-based splitsTrain on past, validate on later periodRealistic evaluationLess data for training

GPUs expensive and underused ​

SolutionHowAdvantageCost / limitation
Dynamic batchingTriton dynamic_batching, client batcherThroughput per GPU upAdds up to the delay to latency
Multiple instancesinstance_group count: 2Overlap compute and I/OGPU memory
QuantisationINT8/FP8/AWQSmaller, fasterRe-evaluate quality
Right-size the fleetAutoscale on queue timePay for loadCold starts

Cold starts and stampedes after deploys ​

SolutionHowAdvantageCost / limitation
Warm-upTriton model_warmup, readiness after warm-upNo slow first requestsSlower model updates
Min replicasKServe minReplicasAlways-ready capacityIdle cost
Pre-pulled images, local weightsDaemonSet pre-pull, node cacheMinutes to secondsDisk, ops

Filtered vector search returns too few results ​

SolutionHowAdvantageCost / limitation
Iterative scanspgvector hnsw.iterative_scanFills kMore work per query
Filter-aware indexQdrant payload index + filterable HNSWEfficientIndex build order matters
Exact search on subsetB-tree filter + exact distancePerfect recallOnly when the subset is small
Partition by filterIndex per tenant/categorySmall indexesMany indexes to manage

Silent degradation ​

SolutionHowAdvantageCost / limitation
Drift monitoringEvidently/WhyLabs per featureEarly warningThreshold tuning
Prediction bias per sliceMean prediction vs observed rateCheap and effective (Sculley)Needs labels eventually
Freshness SLOAlert on last write ageCatches dead pipelinesOne more alert

A bad model reaches users ​

SolutionHowAdvantageCost / limitation
Shadow firstGateway sampling, Istio mirrorZero user impactNo outcome signal
Canary with auto rollbackKServe canaryTrafficPercent, Argo RolloutsLimited blast radiusNeeds good health metrics
Alias rollbackMove @champion backMinutesOld model must stay compatible with features

LLM bill and latency grow ​

SolutionHowAdvantageCost / limitation
Prefix cachingStatic prompt first; vLLM APCLower prefill costNeeds stable prefixes
Token budgetsGateway counters per tenantBounded spendUsers hit limits
Smaller model routingClassify, route easy cases to a small modelBig savingsRouter quality
StreamingSSEBetter perceived latencyLong-lived connections

SQL: point-in-time joins, prediction log, pgvector ​

sql
-- 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';
sql
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.

QuantityEstimateReasoning
Peak home-page requests3,000/s2M DAU × 5 visits ÷ 86,400 s × ~25 peak factor
Candidates per request500Two-tower retrieval top-500
Item feature reads per second1.5M3,000 × 500 (pipelined, cached hot items)
Item embeddings5M × 128 × 4 B ≈ 2.6 GBFits in RAM of one HNSW node; replicate for QPS
Ranking GPU throughput needed1.5M rows/s3,000 × 500 rows; batch per request
Prediction log3,000/s × 2 KB ≈ 6 MB/sKafka; ~0.5 TB/day before compression

3. High-level design.

text
     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 ranker

4. Decisions.

DecisionChoiceReasonAlternative
Two-stage retrieval + rankingANN top-500 then GPU rankerRanking 5M items per request is impossibleBatch-precomputed lists only (stale)
Vector storeQdrant or Milvus cluster (or pgvector at this size)5M vectors, filters on stock and categoryElasticsearch kNN if search already runs there
Online storeRedis cluster, entity key = user_id / item_idSub-ms reads, pipelinesDynamoDB for managed ops
Session featuresFlink, 1-minute windows"Within a minute" requirementRequest-time from recent events in Redis
Ranker servingTriton, dynamic batching, 2 instances per GPUThroughput per GPUKServe with Triton runtime for K8s operations
RolloutShadow → canary → A/B on CTR and revenue per sessionHealth and value separatelyBandit for short-lived promos only
FallbackBatch popularity per category in RedisPage always rendersEmpty module
Feedback loop control5% exploration traffic, logged propensitiesModel not trained only on its own choicesNone (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 ​

SituationRecommendationExtra techniqueReason
Score per entity, changes dailyBatch scoringWrite to Redis; precompute fallbacksCheapest and simplest
Input only known at request timeOnline inferenceFeature store + batchingBatch cannot know the input
Every event must be scored, no user waitingStreaming inferenceKafka consumer + model serverThroughput, no sync coupling
Privacy or offline use, tiny latencyEdge inferenceQuantised model, staged app rolloutNo network
LLM generationOnline with streamingvLLM, prefix cache, token budgetsToken-by-token output

Which serving technology ​

SituationRecommendationReason
GPU models, many frameworksNVIDIA TritonDynamic batching, instance groups, ensembles
Kubernetes platform for many teamsKServe (with Triton/vLLM runtimes)CRD, autoscaling, canary, scale to zero
TensorFlow SavedModels onlyTensorFlow ServingMature, simple
Python team, quick productionisationBentoMLPackaging and adaptive batching
Inference graphs, Kafka pipelinesSeldon Core 2Pipelines and experiments
LLMsvLLMPagedAttention, continuous batching, OpenAI API
New PyTorch projectNot TorchServe (limited maintenance); Triton or KServeMaintenance status

Which vector store ​

SituationRecommendationReason
Under ~10M vectors, data already in Postgrespgvector (HNSW)One database, SQL filters, transactions
Heavy filtering, self-hostedQdrantPayload indexes, filterable HNSW
Hundreds of millions to billionsMilvus (IVF-PQ, DISKANN, GPU)Distributed, disk-based indexes
Search engine already in place, hybrid neededElasticsearch / OpenSearch kNNBM25 + kNN in one query
No ops teamPinecone or a managed Qdrant/Milvus/WeaviateManaged scaling
Built-in hybrid and modulesWeaviateHybrid query, dynamic index

Which feature store ​

SituationRecommendationReason
One or two models, small teamWarehouse tables + Redis, written by your pipelineAvoid a platform you do not need yet
Several teams, open source, own infraFeastDefinitions, PIT joins, many stores
Streaming features at scale, managedTectonManaged stream/batch/real-time features
Integrated platform with registryHopsworks or the cloud vendor's storeFewer 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:

text
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 ​

LoadDesignWhat changes
1x (100 req/s)Model on CPU in the app or one KServe pod; pgvector; batch features in Postgres; nightly retrain by cronSimplicity 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 + canaryBatching 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 storesGPU 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.

text
$ 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/gateway

2. 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):

text
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µs

Reading 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.

text
-- 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 ms

5. 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 ​

BeliefReality
The model is most of the systemSculley et al.: at most ~5% ML code in a mature system; the rest is glue, data and infrastructure
Good offline metrics guarantee production qualitySkew, leakage and drift break that link; log served features and monitor
A feature store is just RedisRedis may be the online half; history, definitions and PIT joins are the point
Joining on user id is fine for training dataIt leaks the future; use as-of joins
Canary proves the model is betterIt proves health; A/B with a business metric proves value
Shadow traffic is freeIt doubles inference cost for the sampled share and must never affect latency
GPU utilisation 100% means efficiencyBatch size and throughput at target p99 measure efficiency
Vector search is exactANN trades recall for speed; measure recall@k
Adding a WHERE clause to vector search is enoughPost-filtering can return fewer than k; use iterative or filter-aware search
Drift monitoring replaces accuracy monitoringDrift is a proxy; compute real performance when labels arrive
RAG removes hallucinationsOnly when retrieval finds the right context; measure retrieval recall
Removing a sensitive column removes biasProxies remain; measure outcomes per group
Retraining more often always helpsWithout validation and gates it ships bad data faster; feedback loops get stronger

Cheat sheet ​

TopicRemember
LifecycleValidate → features → train (PIT) → evaluate → register → serve → monitor → retrain
MLOps levels0 manual, 1 pipeline + CT, 2 CI/CD of pipelines
SkewLog served features (Rules of ML #29); one definition for both paths
Feature storeOffline history + online latest per entity key, materialization, TTL
Point-in-timeAs-of join, TTL relative to each row, created-timestamp filter for backfills
RegistryVersion + lineage + alias; serve by alias; log version per prediction
Deployment modesBatch if slow-changing; online if input arrives with the request
RolloutsShadow (behaviour) → canary (health) → A/B (value); bandits for short-lived arms
ServingStandard protocol (Open Inference Protocol); Triton/KServe/vLLM; avoid TorchServe for new work
BatchingDelay from the budget; bounded queue; shed load
CachingKey includes model version; skip stale features; warm-up before ready
LLMPrefix caching (static prefix first), token budgets, streaming, guardrails, eval gates
Vector DBpgvector to ~10M with SQL filters; dedicated engines beyond; one embedding model per index
ANN knobspgvector hnsw.ef_search 40, ivfflat.probes 1; tune to recall target
MonitoringFreshness, latency, drift, prediction bias, delayed-label performance, feedback holdout

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ML systemThe model plus data, features, training, serving and monitoring infrastructure around it
MLOpsPractice of automating and monitoring the whole ML lifecycle (Google: unify ML development and operation)
LifecycleData → features → training → evaluation → registry → serving → monitoring → retraining
Continuous training (CT)Automatic retraining and redeployment triggered by schedule, new data or drift
Hidden technical debtSystem-level ML maintenance cost (Sculley et al. 2015)
CACE"Changing Anything Changes Everything": entanglement of features and settings
Undeclared consumerA system silently using a model's outputs
FeatureAn input value to a model, derived from raw data
Feature storeSystem that defines features once and serves them for training (offline) and serving (online)
Offline storeHistorical, time-stamped feature values for training and materialization
Online storeLatest feature value per entity key for low-latency serving
Entity keyPrimary key that features belong to (user_id, item_id, driver_id)
MaterializationCopying feature values from the offline source to the online store
TTLMaximum age of a feature value that still counts (online expiry, offline join window)
Point-in-time correctnessEach training row sees feature values as of its own timestamp
As-of joinJoin that picks the newest row at or before a timestamp
Data leakageTraining data containing information not available at prediction time
Training-serving skewDifference between training and serving behaviour from data or pipeline differences
Feature freshnessAge of the newest feature value at serving time
Batch featuresFeatures computed on a schedule over historical data
Streaming featuresFeatures computed continuously from event streams
On-demand featureFeature computed at request time from request data
BackfillRecomputing historical feature values for a new or fixed definition
Data validationDeclared checks on schema, ranges and distributions of data
Great ExpectationsPython data validation library with expectation suites
TFDVTensorFlow Data Validation: statistics, schema, anomaly, drift and skew detection
Model registryCatalogue of model versions with metadata, aliases and lineage
MLflowOpen-source tracking, registry and evaluation platform
Model aliasMutable named pointer to a model version (@champion)
LineageGraph from data and code to model version to deployment
ReproducibilityAbility to re-run training and get an equivalent model
Batch scoringPrecomputing predictions for many entities on a schedule
Online inferenceSynchronous prediction per request within a latency budget
Streaming inferencePredictions computed from events flowing through a stream
Edge inferenceRunning the model on the user's device
Shadow deploymentMirroring traffic to a new model whose answers are only logged
CanaryGradual rollout to a small, increasing share of traffic with rollback
A/B testRandomised controlled comparison of variants on a metric
Multi-armed banditAdaptive allocation of traffic toward better-performing arms
Blue/greenTwo full environments; traffic flips from one to the other
Champion/challengerStanding comparison of the live model with candidate models
Model servingHosting models behind an inference API
Open Inference ProtocolKServe v2 REST/gRPC inference API (/v2/models/.../infer)
NVIDIA TritonMulti-framework inference server with dynamic batching
KServeKubernetes model-serving platform (InferenceService)
TensorFlow ServingServing system for TensorFlow models
TorchServePyTorch model server, now in limited maintenance
Seldon Core 2Kubernetes-native MLOps serving framework
BentoMLPython library for building model-serving services
vLLMLLM inference and serving engine with PagedAttention
Dynamic batchingServer or client combining requests into batches within a delay
Continuous batchingLLM batching that adds/removes sequences at each generation step
GPU utilisationShare of time GPU kernels run; not the same as useful throughput
QuantisationLower-precision weights/activations (INT8, FP8, INT4) to save memory and compute
Prediction cacheCache of scores keyed by model version and input or entity
Warm-upSynthetic requests before a model is marked ready
Cold startSlow first requests after a scale-up or model load
AutoscalingAdjusting replicas from metrics (HPA, KEDA, Knative)
Feature fetchingReading online features for the entities in a request
LLMLarge language model
PagedAttentionKV-cache memory management in blocks, like virtual memory paging
KV cacheStored attention keys/values of processed tokens
Prompt cachingReusing computation for a repeated prompt prefix
Token budgetLimit on input/output tokens per request or tenant
Streaming responseReturning tokens as generated (SSE)
GuardrailsInput/output checks around an LLM
EvaluationOffline and online measurement of model quality as a release gate
RAGRetrieval-augmented generation: retrieve context, then generate
EmbeddingDense vector representation of an object
Vector databaseStore with ANN indexes, metadata filters, sharding for vectors
kNNk-nearest neighbours; exact when every vector is compared
ANNApproximate nearest neighbour search with an index
HNSWHierarchical Navigable Small World graph index
IVFInverted file index: k-means lists, scan nprobe lists
Product quantisationCompressing vectors into codes from sub-vector codebooks (PQ)
DiskANNSSD-resident graph ANN index for billion-scale data
RecallShare of true nearest neighbours returned (recall@k)
Metadata filteringRestricting vector search by attributes
Hybrid searchCombining keyword (BM25) and vector results (RRF, re-ranker)
RRFReciprocal rank fusion: sum of 1/(k + rank) across result lists
pgvectorPostgreSQL extension for vectors, HNSW and IVFFlat
QdrantVector database with payload indexes and filterable HNSW
MilvusDistributed vector database with many index types
WeaviateVector database with HNSW, flat and dynamic indexes and hybrid search
PineconeManaged vector database
Data driftChange in the input distribution
Concept driftChange in the input-to-label relationship
Delayed labelsGround truth arriving long after the prediction
Feedback loopPredictions influencing future training data
Prediction biasPredicted label distribution differing from observed (Sculley)
EvidentlyOpen-source data quality, drift and model monitoring framework
WhyLabsData and model monitoring platform
ExplainabilityAttributing predictions to inputs
SHAPShapley-value based explanation method
BiasSystematically different outcomes or errors across groups
PIIPersonally identifiable information
AirflowDAG-based workflow scheduler
KubeflowML platform on Kubernetes; Kubeflow Pipelines for ML DAGs
DagsterAsset-oriented data orchestrator
GPU costCost of accelerators, managed as cost per 1k predictions or per 1M tokens
Recommendation systemSystem that retrieves and ranks items for a user
Two-tower modelSeparate user and item encoders whose embeddings are compared for retrieval

References ​

Built by Morteza Negahi