Learning pathsPricingChecking sign-in…
← ML curriculum

MLSD-001 · WORKED SYSTEM DESIGN

Video recommendations

Design a home-page video recommendation system from a usable eligible-popularity baseline to compatible retrieval/ranking, trustworthy exposure labels and safe operation. The workload and examples are synthetic.

Author self-review; independent technical review pending. Deterministic synthetic vector/rank/contract fixtures; no trained model, ANN benchmark or production service.

Practice this design before reading →

Prerequisites and scoped previews

Frame the decision and non-ML baseline

Define user action, prediction unit, target horizon, product outcome and guardrails.

Labels, delayed outcomes and human annotation

Define label windows, maturity, censoring, annotation policy and disagreement.

Leakage, splits and evaluation contamination

Prevent future information, entity overlap, preprocessing leakage and test-set reuse.

Sampling, imbalance and observation bias

Explain selection/exposure bias, negatives, weighting and what sampling changes.

Embeddings and representation contracts

Define embedding training objective, normalization, dimension and model/index compatibility.

Candidate retrieval and ANN indexes

Separate eligible-corpus recall from latency/memory and filtering effects.

Ranking, reranking and multi-stage systems

Bound candidate sets, score/rerank and apply policy without confusing retrieval with ranking.

Retrieval and ranking evaluation

Define recall/precision at K, MRR, DCG/NDCG, relevance labels and query/user weighting.

Online experiments and causal limits

Specify randomization unit, exposure, guardrails, SRM, delayed outcomes and interference.

Scoped prerequisite preview. The complete chapter is planned; this preview does not count as authored coverage.

Training-serving consistency

Version feature/transform/model contracts and compare training versus serving behavior.

Registry, validation, rollout and rollback

Promote compatible artifact bundles through checks, shadow/canary and rollback gates.

Scoped prerequisite preview. The complete chapter is planned; this preview does not count as authored coverage.

Cold start, exposure and recommender feedback

Handle new users/items and interactions shaped by previous decisions.

Scoped prerequisite preview. The complete chapter is planned; this preview does not count as authored coverage.

What, when, why and how

Decision, objective and policy

what
The decision returns up to K ordered, eligible videos for one viewer/placement at a known time. Product satisfaction, learning loss, ranking metric and slate guardrails are separate contracts.
when
Use this before data/model choice and when a product changes the placement, allowed content or user action.
why
Clicks and raw watch duration can reward clickbait or long videos without improving satisfaction. Safety, privacy and creator constraints cannot be recovered from an unconstrained relevance score alone.
how
Clarify the placement, eligible audience, response deadline and outcome. Start with followed/popular recent eligible items; measure qualified-watch and satisfaction proxies with duration/creator/safety guardrails. Version the policy and state what evidence would reject a model upgrade.

Exposure and delayed outcome labels

what
A response decision, a rendered impression and later interaction are distinct records. A label refers to one attributable eligible exposure under a policy/window.
when
Use this when building ranking examples, measuring position effects and diagnosing feedback loops.
why
An unshown item has no observed user response. No event yet can mean an immature window or telemetry outage rather than disinterest. Replaying future watch events as features leaks the outcome.
how
Join interactions to an impression ID and deduplicate producer event identity. For this exercise, qualified watch requires at least min(30 seconds, half the video duration) within 24 hours of exposure. Add one hour ingestion allowance; require completeness or label unknown. Keep raw watch and satisfaction/report evidence separate.

Retrieval followed by bounded ranking

what
Retrieval combines cheap candidate sources; a ranker scores a bounded unique subset; a slate policy enforces final constraints.
when
Use this when the catalog is too large for a rich user-item model to score every item synchronously.
why
A strong ranker cannot recover a video omitted by retrieval. Global ANN top K followed by eligibility filtering can underfill. A model with better offline score can still exceed serving or review budgets.
how
Retrieve from followed/recent/popular and compatible vector sources, deduplicate and recheck eligibility, cap expensive scoring, then apply creator/safety rules. Trace stage exclusions and evaluate candidate recall independently of final NDCG and product outcomes.

Embeddings, loss and model choice

what
An item encoder supports offline vectors, a user/context encoder supports request-time retrieval, and a ranker may use richer pair features. All have explicit input/output and objective contracts.
when
Use a dual-encoder hypothesis when precomputed candidate vectors improve retrieval coverage within the serving budget.
why
Same vector dimension does not establish a shared space. A random unexposed negative can be a genuinely desirable video. More model complexity does not automatically improve available evidence or quality.
how
Define user/item vectors in R^d and dot similarity, loss/normalization and negative sampling. Compare the complete popularity baseline, a simple learned ranker and optional richer retrieval/sequence extensions. Validate source contributions and ablations on mature time-split data; reject incompatible or non-finite vectors.

Immutable lineage and compatible rollout

what
A serving bundle binds query/item representation contract, index snapshot, ranker, transforms and policy to one immutable release identity.
when
Use it for promotion, canary observation, incident rollback, backfills and explaining a past recommendation.
why
Rolling back ranker weights alone can leave a mismatched index or transform. A green process health check does not establish data or product quality.
how
Pin dataset/split/run identities, validate candidate and serving contracts, prewarm a compatible bundle, shadow for compatibility/cost and expose a bounded canary under guardrails. Roll back the whole reference; recheck live eligibility independently of snapshot age.

Cold start, exploration and feedback

what
New users/items lack behavioral evidence; repeated recommendations influence which future labels exist. Exploration is a policy change with user impact and statistical assumptions.
when
Use these when high average quality masks catalog narrowing, new-creator exclusion or rapidly changing interests.
why
Popularity feedback can crowd out new content. Logging an unshown candidate score does not reveal its user outcome. Inductive encoders still fail when metadata is absent or out of distribution.
how
Use eligible metadata/content and cohort popularity fallback, track new-user/item slices, and separate observation from intervention. If controlled exploration is justified, define support/assignment/exposure and guardrails; evaluate its costs and uncertainty rather than claiming propensity weighting removes every bias.

Deadline, caching and failure policy

what
A request deadline bounds feature reads, retrieval and ranker work; fallback is an explicit policy. Cached candidates and current eligibility have different freshness needs.
when
Use these to contain overload and dependency failures while preserving the product’s hard invariants.
why
Unlimited queueing worsens tail latency. Cached personalized output can leak context or serve revoked content. Retrying after the client deadline wastes resources and can duplicate telemetry.
how
Use per-stage work caps and remaining-deadline checks; cache only under user/placement/bundle/policy keys or use nonpersonalized eligible candidates. Recheck eligibility at display, return a shorter slate if needed and tag degraded decisions without fabricating model scores.

Understanding the product and clarifying the problem

We design a signed-in home-page surface that returns up to ten videos. Search results, autoplay chaining, ad auctions, creator upload/transcoding and moderation-model training are separate systems. We consume their authorized catalog/policy outputs and explain their failure boundaries. Anonymous users receive an eligible nonpersonalized baseline.

The following are assumed interviewer answers, not an employer’s interview script or current production requirements.

Clarifying questionAssumed answerDesign consequence
What is the placement and requested slate size?Home page, at most ten items.Optimize a slate; define per-request identity and positions.
What is the response target?Synthetic p99 target 200 ms at 2,000 peak requests/s.Bound stage deadlines, candidates and queueing.
What catalog is eligible?Published, permitted language/region/age policy; no revoked videos.Eligibility authority is separate from learned relevance.
Which data exists?Permitted exposures, watch events and sparse satisfaction/report outcomes.Labels have provenance, delay and selection limits.
How much user history may be used?Consented pre-request history, maximum 30-day lookback.Feature availability and deletion must propagate.
Can the system return fewer than ten?Yes, when eligibility or safety constraints prevent a full slate.Do not weaken invariants to fill slots.

Change two answers and revise the architecture

If history use is disabled, remove personalized history features and user-vector lookup. Serve permitted context/region popularity and explicitly report the changed population; do not silently reuse cached personalized results. An item/content model can still be considered under permitted inputs.

If the deadline drops from 200 to 50 ms, the proposed budget no longer fits. Consider precomputed eligible candidate pools and a small local scorer, reduce source fan-out and candidate work, and measure quality loss and revocation freshness. Do not claim the same sequence ranker will simply run four times faster.

Hard invariants: no ineligible output; unique video IDs per slate; bounded work; every served learned decision names a compatible bundle; an interaction is not treated as an unexposed negative; historical features were available at decision time. Logical schemas below specify identity, but cross-record timing and compatibility need application/transaction validation.

Separate product outcome, proxy, model loss and guardrail

The product outcome is useful, satisfying discovery over repeated sessions. We do not observe that perfectly. This exercise uses qualified-watch rate as an early proxy, with sparse explicit satisfaction/report evidence and longer-horizon return behavior as separate signals. Longer watch is not unconditionally better: duration, accidental play and regret matter.

A retrieval contrastive loss optimizes paired representation separation; a ranker may optimize binary log loss for an observed qualified-watch label. Neither is the entire product objective. Offline Recall@K and NDCG measure declared judgments; online treatment evidence asks whether actual exposure improves outcomes under guardrails.

LayerDefinition / denominatorFailure to watch for
ProductUseful discovery and satisfaction in eligible viewer sessionsCannot equate raw time with satisfaction.
Early proxyMature qualified-watch labels / eligible rendered impressionsPosition, missing telemetry and selected exposure bias.
Offline retrievalRetrieved relevant eligible IDs / judged relevant eligible IDsMissing items and filter mismatch.
Offline rankingExponential-gain NDCG under fixed eligible judgmentsUnknown labels or changed gain/ideal convention.
Systemp99 ≤ 200 ms at stated synthetic peak; stage capsToy fixtures do not establish this SLO.
GuardrailsRevoked/safety output, creator concentration, error/fallback, costAggregate engagement can hide a harmful slice.

Build a complete non-ML service first

Use followed creators where permitted, then recent popular items in the viewer’s eligible region/language. Deduplicate, exclude already-consumed items under an explicit product rule, apply current eligibility and a creator cap, and return at most K. Store the rule/policy release identity with the decision.

This baseline already has useful output and a defined degraded mode. A simple learned ranker over the same candidates is the first controlled upgrade. Compare candidate-source coverage and operating costs before adding learned retrieval. A complete simple service is preferable to a neural diagram with no trustworthy labels or fallback.

Do not treat a “popular” count as timeless: use a declared rolling window of available, deduplicated events and document bot/filter effects. A popularity aggregate computed tomorrow is not valid for replaying yesterday’s request unless it reconstructs yesterday’s available state.

Prioritize signal groups and reject leakage

Initial groups are item content/metadata, pre-request user history and active request context. Include missing/default and freshness behavior, not a list of every conceivable feature. Sensitive or inferred attributes are not required by this teaching design.

Reject the current exposure’s eventual watch duration, like, report or corrected moderation decision as pre-exposure inputs. A prior signal can be valid only if its availability precedes this request and its permitted purpose remains valid.

Signal group / hypothesisRepresentation / freshnessCost and verification
Item topic/language/duration: preference and feasibilityVersioned categorical/numeric features; optional content vectorCache with catalog/bundle identity; test changed metadata and new items.
Prior history: taste and recent interestsBounded sequence or aggregates from consented 30-day historyBounded read/default; late-event and revoked-consent tests.
Request context: placement and active sessionAvailable placement/device/session fields; unknown categorySmall request payload; missing and unsupported values tested.
Rejected signal: current watch outcomeFuture outcome belongs to label constructionDeliberately leaked historical join must fail eligibility.

Create exposure labels and temporal splits

A Decision may return ten candidates, but only rendered/visible items generate Impressions under the product’s declared visibility rule. An Interaction references that impression. A retry uses a stable producer event ID so repeated delivery does not double-count watch or likes. Duration aggregation must avoid counting replayed progress deltas twice.

Synthetic example: I1 is rendered October 1 10:00 UTC for a 60-second video; a 40-second qualified watch is observed 10:05 and available 10:06. The 24-hour observation horizon plus one-hour ingestion allowance closes October 2 11:00. Before that boundary, label maturity is pending. After it, the outcome is positive if the telemetry source is complete. I2 with no interaction is not negative while pending or during an outage.

Use min(30 seconds, duration/2) as the exercise’s qualified-watch threshold. This is a synthetic target definition, not an industry standard; validate alternatives by duration and satisfaction slices. Define negative only for a mature eligible impression with complete observation and no qualifying outcome. Unshown videos remain unobserved.

Train on earlier mature impressions, tune on later validation and reserve a final future test period. Freeze source/duplicate and user-cohort rules matching the deployment question. Purge/embargo overlap where a training label window extends into the evaluation boundary; preprocess only on training. Existing-user future quality and unseen-user quality need separately declared assessments.

Snapshot examples pin exact feature and label revisions plus their known-at cutoff. A later appeal, deletion or corrected watch event creates a new revision/snapshot under a stated retention policy; it must not silently rewrite a published benchmark. Event time alone cannot justify a feature that arrived after the decision.

Choose a model with explicit shapes, losses and negatives

Baseline B0 has no learned model. Candidate B1 uses a simple linear/logistic or tree ranker with item, history and context features for the bounded retrieved set. For binary y, log loss is -[y log(p)+(1-y) log(1-p)], evaluated with an explicit numerically stable implementation if trained. Toy rank scores below are hand-authored and do not train B1.

Candidate B2 adds a dual-encoder retrieval hypothesis: user/context vector q in R^d, item vector v in R^d, similarity q·v under a declared normalization. Candidate vectors can be precomputed; a richer pair ranker consumes cross-features for the smaller candidate set. Contrastive or margin loss uses explicit positive/negative sampling; in-batch duplicates and alternate positives need handling.

For similarity hinge, positive 3, negative 1 and margin 1 gives zero; swapping them gives 3. For cosine, normalize nonzero vectors and use an equivalent query/index contract. Same dimension with a different representation identity is invalid. A sequence ranker is an optional design-only extension requiring learning curves, resource measurements and evidence beyond these fixtures.

Clicks, skips and watch labels depend on previous exposure and position. Random corpus negatives are modeling samples, not confirmed dislike. Define sample probabilities and any weighting assumptions; audit hard-negative quality and contamination. Do not claim a negative sampler or propensity weight alone eliminates feedback bias.

Required experiment plan: compare B0/B1 on the same eligible mature data, then ablate history/context and candidate sources. Add B2 only if it recovers useful missing candidates under resource and guardrail limits. Tune on validation; a fair final assessment uses a frozen held-out contract and reports slices/uncertainty.

Make training and promotion reproducible

The offline path consumes deduplicated available events, label-policy revisions and a permitted catalog snapshot. DatasetSnapshot records eligibility, time cutoffs, split rules, transform identity and label maturity/completeness. Each example pins feature/label revisions. TrainingRun pins code/config/environment, seed where meaningful, dataset and objective.

A completed run does not imply an approved model. Validate finite/shape outputs, stage coverage, metric oracles, new-user/item slices and compatibility before publishing ModelVersion and IndexSnapshot. A build retry uses run/artifact identity to avoid publishing two conflicting snapshots; invalid partial artifacts remain unpublished.

Only a release bundle with declared query/item representation, index, ranker, transform and policy versions can receive traffic. Maintain old compatible artifacts within the retention/access policy. The reference fixtures exercise these contracts without orchestrating a training job, checkpoint recovery or a distributed registry. A seed is not a guarantee of bitwise training determinism.

Trace training and serving paths separately

Offline: permitted events → validated snapshot/examples → simple training/validation → immutable models and index → compatible release bundle. Serving: request/consent/context → eligible candidate sources and query encoding → bounded ranking → final live policy → decision response and actual exposure telemetry. The two paths meet through explicit artifact and feature contracts.

For the synthetic workload, retrieve at most 200 unique candidates and send at most 100 to the expensive ranker. Batch feature reads within the stage budget. A relevant item lost at cheap selection is a measured stage loss; it cannot be recovered by a later model. Final live policy can remove an item that was valid in the index snapshot.

Use request/decision identity for retries and a deterministic per-response tie rule. A repeated transport attempt must not create duplicate exposure facts; the client uses a stable actual-render event ID. Decision logging acknowledgement is distinct from user exposure and later durable analytics ingestion.

Specify the request, result and event contracts

Logical interface: recommend(request_id, viewer_id_or_anonymous, placement, region, consent_context, requested_k, deadline). The server enforces K limits, authorized context and its own deadline; a client cannot grant access merely by setting region or consent flags.

Response: decision_id, ordered video IDs with positions, bundle_id, policy_version, fallback_reason and optional cursor scoped to the query/bundle/eligibility policy. Do not expose internal sensitive features or unvalidated reason text. A stale cursor or revoked consent must revalidate rather than replay an unsafe cached slate.

Exposure event: producer_event_id, decision_id, video_id, position, rendered_at, received/available timestamps and visibility-rule version. Interaction: stable event identity, impression_id, type, event/available times and bounded duration measurement. Reject impossible joins, wrong viewer/decision references and incompatible schema versions; quarantine with an owned error counter.

Logical acknowledgement semantics: a successful recommend response means selection completed, not that every item was viewed. A telemetry acknowledgement means accepted under the ingestion durability contract; analytics consumers deduplicate retries. These are proposed contracts, not deployed APIs.

BoundaryNormal caseFailure behavior
RequestValid context and K within limitReject invalid/unauthorized input; do not broaden permissions.
Feature fetchAvailable permitted snapshot/defaultsBound timeout; use explicit missing/default indicators.
Candidate/rankerCompatible versions; bounded unique workReject mixed bundle; eligible baseline on timeout.
Final responseCurrent eligibility and creator cap holdReturn fewer when no safe fill exists.
TelemetryStable producer identity and valid attributionDeduplicate identical retry; quarantine conflicting payload.

Work retrieval, ranking and slate evaluation by hand

Use q=(1,0), candidate vectors X=(1,0), A=(.9,0), B=(.8,0), C=(.7,0), D=(.6,0), E=(.5,0). X is ineligible. Exact eligible top-3 by dot is A/B/C. A simulated approximate A/C/D overlaps that oracle in 2/3 IDs. With independent binary relevant eligible set A/B/E, its relevance Recall@3 is 1/3. This fixture simulates a search miss; no ANN algorithm was executed.

For a separate graded-ranking query, eligible relevance grades A=3, B=2, C=1, D=0 and returned order B/A/D give DCG=3+7/log2(3)≈7.416508. Ideal A/B/C gives IDCG≈9.392789, so NDCG@3≈.789596. Binary recall and precision are both 2/3. Keep this relevance set distinct from the previous retrieval fixture.

For the slate-policy trace, rank scores A=.9 and B=.8 share creator C1; C=.7 is C2; D=.6 is C3; E=.5 is ineligible. Top-3 with one-per-creator cap is A/C/D. B’s exclusion is a policy decision, not a model failure. Evaluate the displayed slate under a declared constrained or unconstrained ideal; do not change the ideal silently to make policy look perfect.

Duplicates A/A/B count A/B once. Under precision denominator K=3 the shortfall remains visible. A query with all relevance grades zero has undefined NDCG; a mean reports defined and undefined counts. Stable item-ID score ties, zero/invalid vectors, K bounds and revoked items are exercised in the reference suite.

Separate offline evidence, shadow checks and causal lift

Offline evaluation measures historical ranking under selected, imperfect labels. Use user/cohort/region/new-item slices, source coverage, duration strata, exposure policy and completeness counts. Include uncertainty appropriate to the sampling process and correlated observations; these tiny fixtures do not estimate confidence intervals.

Shadow deployment computes candidate output without displaying it and can measure compatibility, latency and request/policy failure. It cannot observe the user’s response to unshown alternatives. A controlled exposure experiment needs a stable assignment unit (for example viewer), actual exposure logs, predefined outcome/guardrail windows and mature analysis.

Define sample-ratio-mismatch checks, interference/novelty risks, repeated-peeking/multiple-comparison discipline and a minimum detectable effect/variance/traffic assumption before estimating duration. No universal number of days or users is asserted. Long-horizon return behavior cannot be inferred from one immediate click metric.

If exploration is used, declare which eligible items have nonzero exposure probability, what propensities are logged and where support is absent. User/candidate logging alone is not counterfactual outcome data. Controlled audit labels and independent judgments can complement behavior logs without claiming perfect debiasing.

Estimate capacity, latency and cost with units

Synthetic assumptions: 10 million active catalog videos, dimension d=128, float32 vectors, 2,000 peak requests/s, at most 200 retrieved and 100 expensive-rank candidates, up to ten outputs. Raw candidate vector storage is 10,000,000*128*4=5,120,000,000 bytes, approximately 4.77 GiB, excluding index, metadata, replicas, user vectors and rebuild overlap.

If old/new vector snapshots coexist during migration, raw candidate vectors alone use 10.24 GB decimal; index overhead and regional replicas add more. At peak, the configured caps imply up to 400,000 retrieved candidate IDs/s and 200,000 expensive pair scores/s. These are work bounds, not measured service capacity or hardware sizing.

An authored deadline budget of 15 ms request/context, 35 ms feature access, 40 ms retrieval, 65 ms scoring, 15 ms policy/logging and 30 ms reserve totals 200 ms. This is an allocation, not a proof that component p99 values add to end-to-end p99; benchmark correlated tail behavior and overload under representative traffic.

Cost worksheet: requests per window times bounded candidate work; raw vectors plus index/metadata/replicas/rebuild storage; training resource-hours; feature read and telemetry bytes. Price is a dated input to fill, not a live cloud estimate. Compare a simple ranker and precomputed baseline at equal eligible quality and constraints before reserving GPUs.

QuantitySynthetic calculationPractical limit
Raw item vectors10M * 128 * 4 = 5.12 GB decimalNo index/metadata/replicas included.
Expensive pair work2,000 req/s * 100 = 200,000 pairs/sNot an observed throughput benchmark.
Response items2,000 req/s * 10 = 20,000 IDs/s maximumActual impressions may be fewer.
Latency allocation15+35+40+65+15+30 = 200 msMeasure end-to-end tails; bound queues.

Trace normal, boundary and failure requests

Normal: permitted viewer U1 requests K=3 under bundle B1. Retrieval produces unique eligible A/B/C/D, scores are finite, the creator cap selects A/C/D and a decision is returned. Only actually rendered items create deduplicated impressions. Mature interactions later produce versioned labels.

Boundary: a new viewer with no history uses a declared missing-history representation or eligible baseline; a new item uses compatible content metadata or waits for indexing/fallback. If fewer than K eligible creators exist, return fewer. A no-positive evaluation query is undefined, not a serving failure.

Failure: query representation E2 arrives with index E1. Compatibility validation rejects the pair before scoring. Use B1 or the eligible rule baseline, tag the fallback and alert the release owner. Never serve mixed vectors because their dimensions happen to match. A revocation arriving after retrieval removes the item during final policy; remaining safe items can underfill.

Failure: the feature service is slow and ranker queue is saturated. Enforce remaining deadline and work caps, stop optional sources and use bounded eligible fallback. Cancel/abandon expired scoring work. Track degraded rate and quality; fallback is not evidence that the learned model succeeded.

Recovery: quarantine a bad bundle, restore the last compatible reference, verify sample decisions and event lineage, then compare live system signals immediately and mature quality later. Do not erase failed decisions or silently retrain into production.

Release, monitor and retrain under explicit gates

Stage a release through schema/vector/compatibility and metric-oracle validation, representative offline/slice review, shadow compatibility/cost checks, then bounded controlled exposure under predefined guardrails. Owner approval and rollback criteria are domain decisions; this educational reference does not auto-promote a trained model.

Monitor system tails/errors/queue saturation, data freshness/defaults/conflicts, candidate coverage/shortfalls, score/slate/creator distribution, policy violations, cost per request and delayed mature outcome quality. Immediate distribution shifts are diagnostic signals, not automatic proof of quality loss.

Retraining requires a documented cause/hypothesis, valid new data/labels, an immutable run and the same promotion gates. A telemetry outage, label-policy change or incompatible index may need data repair or rollback rather than a larger model. Scheduled retraining is a proposal, not an automation created by this course.

SignalOwner / immediate actionWhat remains unknown
Mixed representation or invalid vectorRelease/serving owner: reject and restore compatible bundleNew bundle’s product quality cannot be inferred.
Eligibility violationCatalog/policy owner: contain and audit affected decisionsLate label evidence may still be incomplete.
High default/feature lagFeature owner: bounded fallback, check producer/materializationIs quality affected in each mature cohort?
Candidate shortfall/new-item exclusionRetrieval owner: inspect filters/coverage and source fallbackDoes recovered coverage improve outcomes?
Delayed outcome regressionProduct/model/data owners: validate maturity, policy and assignmentDo not attribute causality without appropriate evidence.

Own privacy, deletion and multi-team evolution

Use only permitted history and synthetic/appropriately licensed examples. Do not log raw sensitive viewer histories or free-form reports in routine traces. Apply purpose, access and retention controls to raw events, feature snapshots, indexes, datasets and model artifacts.

Revoking history consent invalidates personalized lookup/cache entries under an explicit SLA and prevents new examples from using that history. Catalog removal propagates to candidate sources and indexes; authoritative final checks contain stale snapshots. Deleting online rows alone does not prove removal of all derived influence or model unlearning.

Product owns objectives and exposure policy; catalog/policy owns eligibility; data owns event/label semantics; retrieval/ranking own quality/contracts; platform/SRE own serving budgets and rollback. Use reviewed version changes, support windows and accountable incident handoffs rather than letting one score encode every team’s policy.

Staff deep dives: negotiate satisfaction versus creator exposure, migrate representation/index bundles across regions, and correct feedback-biased benchmarks without hiding a score drop. Each needs a rollout, owner, measurement period and explicit trade-off. Research-paper patterns are dated inputs, not claims about a named employer’s current system.

Data model, schema and relationships

Proposed logical schema for the synthetic recommendation product. IDs are globally unique; a multi-tenant adaptation must add tenant-qualified identity and authorization. FK relationships protect identity, not temporal eligibility or representation compatibility.

Implementation boundary: Logical contracts and deterministic synthetic references only; no SQL migrations, data ingestion service, ANN cluster or trained model is deployed.

These are proposed logical schemas with field contracts, not executable database migrations. PK identifies a row, FK references an existing parent, UK is a uniqueness rule. A composite PK identifies the combination. Nullable references are marked with ?. A foreign key protects identity; cross-row limits, timing and state transitions also require the transaction rules below.

Viewer: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Viewer relationshipsuser 0..1 to embedding 0..*: user id. embedding.user_id → user.user_id. user 0..1 to decision 0..*: user id. decision.user_id → user.user_id. user 0..1 to feature_snapshot 0..*: user id. feature_snapshot.user_id → user.user_id.user id0..1 parent · 0..* childrenEmbeddingembedding_id [PK]model_id [FK]user_id [FK]user id0..1 parent · 0..* childrenDecisiondecision_id [PK]user_id [FK]bundle_id [FK]user id0..1 parent · 0..* childrenFeatureSnapshotfeature_snapshot_id [PK]user_id [FK]decision_cutoffVieweruser_id [PK]consent_versionhistory_allowed
Video: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Video relationshipsvideo 0..1 to embedding 0..*: video id. embedding.video_id → video.video_id. video 1 to index_membership 0..*: video id. index_membership.video_id → video.video_id. video 1 to impression 0..*: video id. impression.video_id → video.video_id.video id0..1 parent · 0..* childrenEmbeddingembedding_id [PK]model_id [FK]user_id [FK]video id1 parent · 0..* childrenIndexMembershipindex_id + video_id [PK]embedding_id [FK]video id1 parent · 0..* childrenImpressionimpression_id [PK]decision_id [FK]video_id [FK]Videovideo_id [PK]creator_idduration_seconds
Video: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Video relationshipsvideo 1 to decision_item 0..*: video id. decision_item.video_id → video.video_id.video id1 parent · 0..* childrenDecisionItemdecision_id + position [PK]video_id [FK]score_sourceVideovideo_id [PK]creator_idduration_seconds
DatasetSnapshot: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

DatasetSnapshot relationshipsdataset_snapshot 1 to training_run 0..*: dataset id. training_run.dataset_id → dataset_snapshot.dataset_id. dataset_snapshot 1 to dataset_example 0..*: dataset id. dataset_example.dataset_id → dataset_snapshot.dataset_id.dataset id1 parent · 0..* childrenTrainingRunrun_id [PK]dataset_id [FK]code_config_envdataset id1 parent · 0..* childrenDatasetExampleexample_id [PK]dataset_id [FK]decision_id [FK]DatasetSnapshotdataset_id [PK]known_at_cutoffsplit_manifest
TrainingRun: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

TrainingRun relationshipstraining_run 1 to model_version 0..*: run id. model_version.run_id → training_run.run_id.run id1 parent · 0..* childrenModelVersionmodel_id [PK]run_id [FK]roleTrainingRunrun_id [PK]dataset_id [FK]code_config_env
ModelVersion: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

ModelVersion relationshipsmodel_version 1 to embedding 0..*: model id. embedding.model_id → model_version.model_id. model_version 1 to index_snapshot 0..*: item encoder id. index_snapshot.item_encoder_id → model_version.model_id. model_version 1 to release_bundle 0..*: query model id. release_bundle.query_model_id → model_version.model_id.model id1 parent · 0..* childrenEmbeddingembedding_id [PK]model_id [FK]user_id [FK]item encoder id1 parent · 0..* childrenIndexSnapshotindex_id [PK]item_encoder_id [FK]catalog_cutoffquery model id1 parent · 0..* childrenReleaseBundlebundle_id [PK]query_model_id [FK]rank_model_id [FK]ModelVersionmodel_id [PK]run_id [FK]role
ModelVersion: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

ModelVersion relationshipsmodel_version 1 to release_bundle 0..*: rank model id. release_bundle.rank_model_id → model_version.model_id.rank model id1 parent · 0..* childrenReleaseBundlebundle_id [PK]query_model_id [FK]rank_model_id [FK]ModelVersionmodel_id [PK]run_id [FK]role
Embedding: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Embedding relationshipsembedding 1 to index_membership 0..*: embedding id. index_membership.embedding_id → embedding.embedding_id.embedding id1 parent · 0..* childrenIndexMembershipindex_id + video_id [PK]embedding_id [FK]Embeddingembedding_id [PK]model_id [FK]user_id [FK]
IndexSnapshot: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

IndexSnapshot relationshipsindex_snapshot 1 to index_membership 0..*: index id. index_membership.index_id → index_snapshot.index_id. index_snapshot 1 to release_bundle 0..*: index id. release_bundle.index_id → index_snapshot.index_id.index id1 parent · 0..* childrenIndexMembershipindex_id + video_id [PK]embedding_id [FK]index id1 parent · 0..* childrenReleaseBundlebundle_id [PK]query_model_id [FK]rank_model_id [FK]IndexSnapshotindex_id [PK]item_encoder_id [FK]catalog_cutoff
ReleaseBundle: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

ReleaseBundle relationshipsrelease_bundle 0..1 to decision 0..*: bundle id. decision.bundle_id → release_bundle.bundle_id.bundle id0..1 parent · 0..* childrenDecisiondecision_id [PK]user_id [FK]bundle_id [FK]ReleaseBundlebundle_id [PK]query_model_id [FK]rank_model_id [FK]
Decision: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Decision relationshipsdecision 1 to impression 0..*: decision id. impression.decision_id → decision.decision_id. decision 1 to decision_item 0..*: decision id. decision_item.decision_id → decision.decision_id. decision 1 to dataset_example 0..*: decision id. dataset_example.decision_id → decision.decision_id.decision id1 parent · 0..* childrenImpressionimpression_id [PK]decision_id [FK]video_id [FK]decision id1 parent · 0..* childrenDecisionItemdecision_id + position [PK]video_id [FK]score_sourcedecision id1 parent · 0..* childrenDatasetExampleexample_id [PK]dataset_id [FK]decision_id [FK]Decisiondecision_id [PK]user_id [FK]bundle_id [FK]
Impression: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

Impression relationshipsimpression 1 to interaction 0..*: impression id. interaction.impression_id → impression.impression_id. impression 1 to label 0..*: impression id. label.impression_id → impression.impression_id.impression id1 parent · 0..* childrenInteractionevent_id [PK]impression_id [FK]type_durationimpression id1 parent · 0..* childrenLabelRevisionlabel_id [PK]impression_id [FK]policy_revisionImpressionimpression_id [PK]decision_id [FK]video_id [FK]
LabelRevision: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

LabelRevision relationshipslabel 1 to dataset_example 0..*: label id. dataset_example.label_id → label.label_id.label id1 parent · 0..* childrenDatasetExampleexample_id [PK]dataset_id [FK]decision_id [FK]LabelRevisionlabel_id [PK]impression_id [FK]policy_revision
FeatureSnapshot: relationship map

Connectors name the relationship; multiplicities state parents per child and children per parent. 0..1 means optional, 1 required, 0..* any number. Self-links show two roles of the same entity.

FeatureSnapshot relationshipsfeature_snapshot 0..1 to decision 0..*: feature snapshot id. decision.feature_snapshot_id → feature_snapshot.feature_snapshot_id. feature_snapshot 1 to dataset_example 0..*: feature snapshot id. dataset_example.feature_snapshot_id → feature_snapshot.feature_snapshot_id.feature snapshot id0..1 parent · 0..* childrenDecisiondecision_id [PK]user_id [FK]bundle_id [FK]feature snapshot id1 parent · 0..* childrenDatasetExampleexample_id [PK]dataset_id [FK]decision_id [FK]FeatureSnapshotfeature_snapshot_id [PK]user_id [FK]decision_cutoff

Entity definitions and field contracts

Viewer

Permitted viewer identity and consent boundary.

FieldType / keyMeaning and reference
user_idopaque ID · PKGlobal viewer identity; no raw personal history in this row.
consent_versionstring · VALUEVersion of permitted history purpose.
history_allowedboolean · VALUEAuthoritative history permission, not trusted from client.
region_policystring · VALUEApplicable eligibility/region policy context.
deleted_attimestamp? · VALUERevocation/deletion marker and retained-minimum policy.

Code mapping: Request authorization and feature-permission contract.

  • Do not personalize after effective history revocation; cache invalidation has an owner.

Video

Candidate identity and current catalog eligibility.

FieldType / keyMeaning and reference
video_idopaque ID · PKStable candidate identity.
creator_idopaque ID · VALUECreator grouping for this exercise; external creator authority.
duration_secondspositive number · VALUEInput for the synthetic qualified-watch threshold.
catalog_versionstring · VALUEMetadata/eligibility revision identity.
eligibility_stateenum · VALUEPublished/revoked/region-age restrictions under policy.
available_attimestamp · VALUEWhen this catalog revision can be used.

Code mapping: Candidate filter and creator-cap policy.

  • Final eligibility check is authoritative even if an old index contains the video.

DatasetSnapshot

Immutable example/split manifest, not a mutable latest-data query.

FieldType / keyMeaning and reference
dataset_idstring · PKContent-addressed or otherwise immutable snapshot identity.
known_at_cutofftimestamp · VALUEFeature and label availability cutoff.
split_manifestartifact ref · VALUETemporal/entity/duplicate boundaries and purged rows.
label_policystring · VALUETarget/window/completeness and revision semantics.
example_manifestartifact ref · VALUEExact prediction, feature and label revisions per example.

Code mapping: Offline dataset fixture and design-only training input.

  • A correction creates a new snapshot; retained snapshots follow access/deletion policy.

TrainingRun

Reproducible provenance and promotion evidence.

FieldType / keyMeaning and reference
run_idstring · PKUnique attempt/run identity.
dataset_idstring · FKExact training snapshot. · dataset_snapshot.dataset_id
code_config_envartifact refs · VALUECode, objective, transforms, environment and seed where meaningful.
quality_reportartifact ref · VALUEHeld-out/slice and shape/contract evidence.
stateenum · VALUECreated/running/failed/validated; completion alone does not promote.

Code mapping: Design-only orchestration and run lineage.

  • Retry and publication identity prevents conflicting artifact writes.

ModelVersion

Immutable encoder/ranker artifact with compatibility metadata.

FieldType / keyMeaning and reference
model_idstring · PKImmutable model identity.
run_idstring · FKProducing validated run. · training_run.run_id
roleenum · VALUEQuery encoder, item encoder or ranker.
representation_contractstring? · VALUEShared space identity for compatible query/item pair.
dimension_metric_normalizationstruct · VALUEShape, score direction and normalization contract.
artifact_hashstring · VALUEIntegrity of permitted weights/config/transforms.

Code mapping: Bundle validator; real training remains design-only.

  • A learned release requires validated model roles and compatible metadata.

Embedding

Versioned user/item vector; one subject kind per row.

FieldType / keyMeaning and reference
embedding_idstring · PKImmutable vector revision.
model_idstring · FKProducing encoder. · model_version.model_id
user_idopaque ID? · FKUser-vector subject when applicable. · user.user_id
video_idopaque ID? · FKItem-vector subject when applicable. · video.video_id
vectorfinite float array · VALUEDeclared dimension; zero-vector policy depends on metric.
available_attimestamp · VALUEHistorical feature/index availability.

Code mapping: Deterministic vector fixture; bounded user-history versioning.

  • Exactly one of user_id/video_id is set.
  • Subject, model role and representation metadata are validated together.

IndexSnapshot

Immutable candidate index metadata and publication cutoff.

FieldType / keyMeaning and reference
index_idstring · PKSnapshot identity.
item_encoder_idstring · FKCompatible item model. · model_version.model_id
catalog_cutofftimestamp · VALUECandidate metadata snapshot cutoff.
representation_contractstring · VALUEQuery/item space, dimension, metric, normalization.
stateenum · VALUEBuilding/validated/published/retired with coverage report.

Code mapping: Exact oracle fixture; ANN index build is design-only.

  • An incomplete or mixed representation snapshot cannot be published.

IndexMembership

Explicit many-to-many video/index relationship and exact vector revision.

FieldType / keyMeaning and reference
index_idstring · PK,FKOwning immutable snapshot. · index_snapshot.index_id
video_idopaque ID · PK,FKIncluded candidate. · video.video_id
embedding_idstring · FKExact compatible item vector. · embedding.embedding_id

Code mapping: Catalog coverage and migration validation.

  • Unique(index_id, video_id).
  • Referenced embedding subject/model must match video and index encoder.

ReleaseBundle

Atomically selected compatible serving artifact set.

FieldType / keyMeaning and reference
bundle_idstring · PKImmutable release identity.
query_model_idstring · FKUser/context encoder. · model_version.model_id
rank_model_idstring · FKRanker artifact. · model_version.model_id
index_idstring · FKMatching candidate snapshot. · index_snapshot.index_id
transform_policy_versionsstruct · VALUEFeature/default/normalization and slate policy versions.
stateenum · VALUEValidated/canary/active/retired under owned release gates.

Code mapping: Validated release/reference state; no real registry deployed.

  • Query model and index representation must match; model roles checked.
  • Rollback selects a complete compatible bundle, not weights alone.

Decision

One recommendation response selection under a bundle and policy.

FieldType / keyMeaning and reference
decision_idstring · PKOpaque idempotent request/response selection identity.
user_idopaque ID? · FKNull for anonymous eligible baseline. · user.user_id
bundle_idstring? · FKLearned bundle; null for explicit rule fallback. · release_bundle.bundle_id
decision_timetimestamp · VALUEHistorical input availability boundary.
policy_fallbackstruct · VALUESlate policy, request constraints and degraded reason.
feature_snapshot_idstring? · FKRecorded inputs when permitted; null on explicit unrecorded rule path. · feature_snapshot.feature_snapshot_id

Code mapping: recommend response and deterministic slate trace.

  • All-allow empty policy is not a valid way to fill a slate.
  • Learned decisions require a bundle; rule fallback requires explicit identity/reason.
  • DecisionItem rows provide at most K unique eligible videos with unique positions; none imply actual rendering.

Impression

Actual rendered item and position, separate from response.

FieldType / keyMeaning and reference
impression_idstring · PKStable actual-render event identity.
decision_idstring · FKOwning response. · decision.decision_id
video_idopaque ID · FKActually displayed candidate. · video.video_id
positionpositive integer · VALUEPosition under the response policy.
rendered_available_attimestamps · VALUEEvent and materialized availability times.
visibility_rulestring · VALUEVersioned product definition of eligible exposure.

Code mapping: Exposure ingestion and attribution fixture.

  • Validate membership/position in the decision; stable retries deduplicate.

Interaction

Attributable watch/feedback fact with retry identity.

FieldType / keyMeaning and reference
event_idstring · PKStable producer event identity; conflicting payload quarantined.
impression_idstring · FKAttributed actual exposure. · impression.impression_id
type_durationstruct · VALUEWatch/like/report and bounded duration semantics.
event_timetimestamp · VALUEWhen the interaction occurred.
available_attimestamp · VALUEWhen the validated event could be consumed.

Code mapping: Deduplicated label construction input.

  • Repeated watch-progress deltas must not inflate duration.
  • No matching impression means unattributed evidence, not an automatic training label.

LabelRevision

One immutable target revision for an exposure.

FieldType / keyMeaning and reference
label_idstring · PKExact revision identity.
impression_idstring · FKLabeled exposure. · impression.impression_id
policy_revisionstring · VALUETarget threshold/horizon and adjudication semantics.
value_statusstruct · VALUEPositive/negative/pending/unknown, not missing=zero.
window_completenessstruct · VALUEHorizon, allowance and source-completeness evidence.
available_attimestamp · VALUERevision availability for an as-of dataset.

Code mapping: Maturity and qualified-watch fixture; audited dataset lineage.

  • Unique exposure/policy/revision identity.
  • Pin one eligible revision per target/example in the immutable dataset manifest.

FeatureSnapshot

Exact permitted feature input lineage at a decision boundary.

FieldType / keyMeaning and reference
feature_snapshot_idstring · PKImmutable input snapshot identity.
user_idopaque ID? · FKNull for nonpersonalized context. · user.user_id
decision_cutofftimestamp · VALUEEvery included historical feature was available by this boundary.
transform_versionstring · VALUETransform/default/normalization identity.
feature_revision_manifestartifact ref · VALUEPinned raw/aggregate/vector revision IDs and missing/default flags.

Code mapping: Serving input replay and immutable dataset example contract.

  • Availability and permission are validated against the decision cutoff.
  • Retained snapshot fields follow purpose/redaction/deletion policy.

DecisionItem

Relational membership of a response slate, including items never rendered.

FieldType / keyMeaning and reference
decision_idstring · PK,FKOwning recommendation selection. · decision.decision_id
positionpositive integer · PKUnique slot within the decision.
video_idopaque ID · FKSelected candidate. · video.video_id
score_sourcestruct · VALUEPermitted score/provenance or explicit rule fallback; not a probability claim.

Code mapping: Response slate membership and impression-position validation.

  • Unique(decision_id, video_id); at most K rows per decision.
  • Final eligibility and creator cap require cross-row policy validation.

DatasetExample

Explicit lineage from one frozen training example to its inputs and target.

FieldType / keyMeaning and reference
example_idstring · PKImmutable example identity within a published snapshot.
dataset_idstring · FKOwning dataset snapshot. · dataset_snapshot.dataset_id
decision_idstring · FKHistorical request boundary. · decision.decision_id
label_idstring · FKOne selected eligible label revision. · label.label_id
feature_snapshot_idstring · FKExact permitted input snapshot. · feature_snapshot.feature_snapshot_id
splitenum · VALUETrain/validation/test under the frozen split manifest.

Code mapping: Mature label, temporal split and feature/target leakage boundary.

  • Label impression must belong to the referenced decision; enforce this cross-record invariant.
  • Feature snapshot availability must precede decision and agree with its input lineage.
  • Unique(dataset_id, label_id) under the declared one-example-per-target/revision policy.

Relationship cardinalities and their reasons

Parent → childMultiplicityFK / why
dataset_snapshot → training_run

dataset id

1 parent per child; 0..* children per parenttraining_run.dataset_id → dataset_snapshot.dataset_id

Each child references exactly one dataset_snapshot; a parent may have many children. Exact training snapshot.

training_run → model_version

run id

1 parent per child; 0..* children per parentmodel_version.run_id → training_run.run_id

Each child references exactly one training_run; a parent may have many children. Producing validated run.

model_version → embedding

model id

1 parent per child; 0..* children per parentembedding.model_id → model_version.model_id

Each child references exactly one model_version; a parent may have many children. Producing encoder.

user → embedding

user id

0..1 parent per child; 0..* children per parentembedding.user_id → user.user_id

Each child references zero or one user; a parent may have many children. User-vector subject when applicable.

video → embedding

video id

0..1 parent per child; 0..* children per parentembedding.video_id → video.video_id

Each child references zero or one video; a parent may have many children. Item-vector subject when applicable.

model_version → index_snapshot

item encoder id

1 parent per child; 0..* children per parentindex_snapshot.item_encoder_id → model_version.model_id

Each child references exactly one model_version; a parent may have many children. Compatible item model.

index_snapshot → index_membership

index id

1 parent per child; 0..* children per parentindex_membership.index_id → index_snapshot.index_id

Each child references exactly one index_snapshot; a parent may have many children. Owning immutable snapshot.

video → index_membership

video id

1 parent per child; 0..* children per parentindex_membership.video_id → video.video_id

Each child references exactly one video; a parent may have many children. Included candidate.

embedding → index_membership

embedding id

1 parent per child; 0..* children per parentindex_membership.embedding_id → embedding.embedding_id

Each child references exactly one embedding; a parent may have many children. Exact compatible item vector.

model_version → release_bundle

query model id

1 parent per child; 0..* children per parentrelease_bundle.query_model_id → model_version.model_id

Each child references exactly one model_version; a parent may have many children. User/context encoder.

model_version → release_bundle

rank model id

1 parent per child; 0..* children per parentrelease_bundle.rank_model_id → model_version.model_id

Each child references exactly one model_version; a parent may have many children. Ranker artifact.

index_snapshot → release_bundle

index id

1 parent per child; 0..* children per parentrelease_bundle.index_id → index_snapshot.index_id

Each child references exactly one index_snapshot; a parent may have many children. Matching candidate snapshot.

user → decision

user id

0..1 parent per child; 0..* children per parentdecision.user_id → user.user_id

Each child references zero or one user; a parent may have many children. Null for anonymous eligible baseline.

release_bundle → decision

bundle id

0..1 parent per child; 0..* children per parentdecision.bundle_id → release_bundle.bundle_id

Each child references zero or one release_bundle; a parent may have many children. Learned bundle; null for explicit rule fallback.

feature_snapshot → decision

feature snapshot id

0..1 parent per child; 0..* children per parentdecision.feature_snapshot_id → feature_snapshot.feature_snapshot_id

Each child references zero or one feature_snapshot; a parent may have many children. Recorded inputs when permitted; null on explicit unrecorded rule path.

decision → impression

decision id

1 parent per child; 0..* children per parentimpression.decision_id → decision.decision_id

Each child references exactly one decision; a parent may have many children. Owning response.

video → impression

video id

1 parent per child; 0..* children per parentimpression.video_id → video.video_id

Each child references exactly one video; a parent may have many children. Actually displayed candidate.

impression → interaction

impression id

1 parent per child; 0..* children per parentinteraction.impression_id → impression.impression_id

Each child references exactly one impression; a parent may have many children. Attributed actual exposure.

impression → label

impression id

1 parent per child; 0..* children per parentlabel.impression_id → impression.impression_id

Each child references exactly one impression; a parent may have many children. Labeled exposure.

user → feature_snapshot

user id

0..1 parent per child; 0..* children per parentfeature_snapshot.user_id → user.user_id

Each child references zero or one user; a parent may have many children. Null for nonpersonalized context.

decision → decision_item

decision id

1 parent per child; 0..* children per parentdecision_item.decision_id → decision.decision_id

Each child references exactly one decision; a parent may have many children. Owning recommendation selection.

video → decision_item

video id

1 parent per child; 0..* children per parentdecision_item.video_id → video.video_id

Each child references exactly one video; a parent may have many children. Selected candidate.

dataset_snapshot → dataset_example

dataset id

1 parent per child; 0..* children per parentdataset_example.dataset_id → dataset_snapshot.dataset_id

Each child references exactly one dataset_snapshot; a parent may have many children. Owning dataset snapshot.

decision → dataset_example

decision id

1 parent per child; 0..* children per parentdataset_example.decision_id → decision.decision_id

Each child references exactly one decision; a parent may have many children. Historical request boundary.

label → dataset_example

label id

1 parent per child; 0..* children per parentdataset_example.label_id → label.label_id

Each child references exactly one label; a parent may have many children. One selected eligible label revision.

feature_snapshot → dataset_example

feature snapshot id

1 parent per child; 0..* children per parentdataset_example.feature_snapshot_id → feature_snapshot.feature_snapshot_id

Each child references exactly one feature_snapshot; a parent may have many children. Exact permitted input snapshot.

Transaction boundaries

  1. Accept an identical event retry once using stable producer identity; quarantine a conflicting payload under the same ID.
  2. Validate snapshot/artifact completeness before publishing an immutable bundle reference. Promotion/rollback switches one compatible reference atomically.
  3. Validate decision item uniqueness, bounds and live eligibility before response; exposure ingestion separately validates membership/position and idempotency.
  4. Dataset publication pins exact feature/label revisions and split manifest; correction/deletion creates an auditable revision/rebuild process.

Indexes and uniqueness

  1. PK/unique event_id and impression_id protect delivery retry identity.
  2. Unique(index_id, video_id) plus embedding_id validates one indexed vector revision per candidate.
  3. Query interaction by impression_id and event_time/available_at for attribution and maturity.
  4. Query label revisions by impression_id, policy_revision, available_at; choose the declared eligible revision.
  5. Query catalog availability/state by region/language/policy; validate actual selectivity and index costs before deployment.

Schema traps and failure cases

  1. A foreign key alone cannot prove that a watch event occurred within the label window or arrived before the dataset cutoff.
  2. A same-dimension model FK does not establish a shared representation space; validate bundle metadata and roles.
  3. A valid index membership can still reference a now-revoked video; recheck authoritative eligibility.
  4. Deleting a viewer row does not by itself remove derived vectors, historical datasets or all trained influence. Follow the declared retention/rebuild process.

Trace the records through one operation

  1. Create validated model/index artifacts and bundle B1 after the design-only run gates.
  2. Decision D1 references viewer, FeatureSnapshot F1 and B1; DecisionItem rows select A/C/D at unique positions before any actual rendering.
  3. Impression I1 references D1/A only when rendered at a known position/time.
  4. Interaction W1 references I1 and is deduplicated by producer identity.
  5. After maturity/completeness, label L1 references I1; DatasetExample X1 in snapshot S2 joins D1/F1/L1 with an explicit split and cross-record invariants.
  6. An E2/E1 mismatch is rejected; a fallback decision names its rule or restored compatible bundle, retaining lineage.

Execute the small recommendation trace

Local deterministic calculations over synthetic data. The approximate result is simulated; no ANN engine, neural training, network request or GPU is used.

Step 1 of 4

Retrieve from the eligible corpus

X is ineligible. Exact top-3: A, B, C. Simulated ANN output: A, C, D. Search overlap: 0.666667. Relevance recall for A/B/E: 0.333333.

Diagrams and relationships

1. Exposure, availability and label maturity

The current outcome never becomes a pre-request feature. A complete feed and horizon are required for a mature negative.

Scroll horizontally on smaller screens, or enlarge the diagram.

1. Exposure, availability and label maturityThe current outcome never becomes a pre-request feature. A complete feed and horizon are required for a mature negative. Request: 10:00, available history to Rendered impression I1: 10:00: serve eligible slate. Rendered impression I1: 10:00 to Watch observed 10:05; ready 10:06: attributed watch event. Watch observed 10:05; ready 10:06 to 24h + 1h maturity boundary: pin eligible revision.serve eligible slateattributed watch eventpin eligible revisionRequest: 10:00, available historyRendered impression I1: 10:00Watch observed 10:05; ready 10:0624h + 1h maturity boundary
1. Exposure, availability and label maturityThe current outcome never becomes a pre-request feature. A complete feed and horizon are required for a mature negative. Request: 10:00, available history to Rendered impression I1: 10:00: serve eligible slate. Rendered impression I1: 10:00 to Watch observed 10:05; ready 10:06: attributed watch event. Watch observed 10:05; ready 10:06 to 24h + 1h maturity boundary: pin eligible revision.serve eligible slateattributed watch eventpin eligible revisionRequest: 10:00, available historyRendered impression I1: 10:00Watch observed 10:05; ready 10:0624h + 1h maturity boundary
2. Decision and artifact lineage

Detailed entity field/FK/cardinality maps follow below. Serving references a compatible bundle, while exposure produces later evidence.

Scroll horizontally on smaller screens, or enlarge the diagram.

2. Decision and artifact lineageDetailed entity field/FK/cardinality maps follow below. Serving references a compatible bundle, while exposure produces later evidence. ReleaseBundle: compatible IDs to Decision: viewer + bundle: one release per decision. Decision: viewer + bundle to Impression: item + position: zero or more renders. Impression: item + position to LabelRevision: policy + window: zero or more revisions.one release per decisionzero or more renderszero or more revisionsReleaseBundle: compatible IDsDecision: viewer + bundleImpression: item + positionLabelRevision: policy + window
2. Decision and artifact lineageDetailed entity field/FK/cardinality maps follow below. Serving references a compatible bundle, while exposure produces later evidence. ReleaseBundle: compatible IDs to Decision: viewer + bundle: one release per decision. Decision: viewer + bundle to Impression: item + position: zero or more renders. Impression: item + position to LabelRevision: policy + window: zero or more revisions.one release per decisionzero or more renderszero or more revisionsReleaseBundle: compatible IDsDecision: viewer + bundleImpression: item + positionLabelRevision: policy + window
3. Offline training and promotion path

Training is a design-only extension. Deterministic fixtures validate contracts and arithmetic without a trained model.

Scroll horizontally on smaller screens, or enlarge the diagram.

3. Offline training and promotion pathTraining is a design-only extension. Deterministic fixtures validate contracts and arithmetic without a trained model. Permitted events + label policy to DatasetSnapshot + split: availability + maturity. DatasetSnapshot + split to Train + validate candidate: immutable examples. Train + validate candidate to Models + matching index: quality/shape gates. Models + matching index to Gated release bundle: compatible versions.availability + maturityimmutable examplesquality/shape gatescompatible versionsPermitted events + label policyDatasetSnapshot + splitTrain + validate candidateModels + matching indexGated release bundle
3. Offline training and promotion pathTraining is a design-only extension. Deterministic fixtures validate contracts and arithmetic without a trained model. Permitted events + label policy to DatasetSnapshot + split: availability + maturity. DatasetSnapshot + split to Train + validate candidate: immutable examples. Train + validate candidate to Models + matching index: quality/shape gates. Models + matching index to Gated release bundle: compatible versions.availability + maturityimmutable examplesquality/shape gatescompatible versionsPermitted events + label policyDatasetSnapshot + splitTrain + validate candidateModels + matching indexGated release bundle
4. Online serving and feedback path

Bound work at each stage and revalidate current eligibility before output; response and actual exposure are distinct.

Scroll horizontally on smaller screens, or enlarge the diagram.

4. Online serving and feedback pathBound work at each stage and revalidate current eligibility before output; response and actual exposure are distinct. Request + consent/context to Eligible candidates + query: deadline + source caps. Eligible candidates + query to Bounded feature scoring: unique candidate IDs. Bounded feature scoring to Slate policy + current eligibility: scores + bundle. Slate policy + current eligibility to Decision + rendered exposures: at most K safe items.deadline + source capsunique candidate IDsscores + bundleat most K safe itemsRequest + consent/contextEligible candidates + queryBounded feature scoringSlate policy + current eligibilityDecision + rendered exposures
4. Online serving and feedback pathBound work at each stage and revalidate current eligibility before output; response and actual exposure are distinct. Request + consent/context to Eligible candidates + query: deadline + source caps. Eligible candidates + query to Bounded feature scoring: unique candidate IDs. Bounded feature scoring to Slate policy + current eligibility: scores + bundle. Slate policy + current eligibility to Decision + rendered exposures: at most K safe items.deadline + source capsunique candidate IDsscores + bundleat most K safe itemsRequest + consent/contextEligible candidates + queryBounded feature scoringSlate policy + current eligibilityDecision + rendered exposures
5. Mixed-bundle rejection and recovery

E2 query vectors cannot silently use an E1 index. Restore a complete permitted bundle; quality evidence may be delayed.

Scroll horizontally on smaller screens, or enlarge the diagram.

5. Mixed-bundle rejection and recoveryE2 query vectors cannot silently use an E1 index. Restore a complete permitted bundle; quality evidence may be delayed. Query E2 with index E1 to Compatibility gate rejects: representation mismatch. Compatibility gate rejects to B1 or eligible rule fallback: preserve eligibility. B1 or eligible rule fallback to Alert + restore bundle reference: verify live + delayed signals.representation mismatchpreserve eligibilityverify live + delayed signalsQuery E2 with index E1Compatibility gate rejectsB1 or eligible rule fallbackAlert + restore bundle reference
5. Mixed-bundle rejection and recoveryE2 query vectors cannot silently use an E1 index. Restore a complete permitted bundle; quality evidence may be delayed. Query E2 with index E1 to Compatibility gate rejects: representation mismatch. Compatibility gate rejects to B1 or eligible rule fallback: preserve eligibility. B1 or eligible rule fallback to Alert + restore bundle reference: verify live + delayed signals.representation mismatchpreserve eligibilityverify live + delayed signalsQuery E2 with index E1Compatibility gate rejectsB1 or eligible rule fallbackAlert + restore bundle reference

Engineer, Senior and Staff follow-ups

These are teaching lenses. Each answer changes the scope of reasoning; they are not official employer leveling criteria.

Engineer: Why is a returned video without a watch event not immediately negative?

It may not have been rendered, its 24-hour window may still be open, or telemetry may be incomplete. Require an attributed impression, maturity plus allowance and source completeness; unexposed items remain unobserved.

Engineer: Compute the two retrieval metrics for A/C/D.

Exact eligible vector top-3 is A/B/C, giving overlap 2/3. Independent relevant eligible A/B/E gives relevance recall 1/3. They compare to different references and cannot be labeled interchangeably.

Senior: How do you handle a same-dimension encoder migration?

Require matching representation identity, metric, normalization and transforms, build/validate the new index and atomically switch the compatible bundle. Retain the prior bundle and live eligibility checks. Dimensions alone are insufficient.

Senior: Which request path survives a scoring outage?

Stop optional expired work and use the eligible simple order under the same creator/policy rules and remaining deadline. Tag the degraded decision and measure fallback rate/quality separately; do not turn errors into fabricated low-risk scores.

Staff: How do you reconcile long-term satisfaction and creator exposure?

Make objectives and hard constraints explicit with accountable product/policy owners. Evaluate utility, creator concentration and harms by cohort over appropriate windows, version policy changes and use controlled exposure where justified. Do not hide the compromise in an unexplained loss weight.

Staff: How do you repair an exposure-biased benchmark across teams?

Version the old benchmark and its limitations, collect appropriate audit/controlled exposure evidence, revise labels/splits/coverage under review and compare under a common contract. Expect a possible score drop from removing leakage or selection artifacts; migrate gates with transparent evidence rather than retaining an invalid number.

Practice and self-review

Your practice draft

Design the home-page recommender under the stated 200 ms/2,000 req/s workload. Explain a complete baseline, label maturity and schema relationships, retrieval/ranking evaluation, compatible release and rollback. Then handle no-history consent, selective eligibility, a ranker outage and a same-dimension encoder change.

Saved locally on this device. The worked answer does not score your draft. Existing lesson notes and completion are separate.

Progressive hints

Hint 1

Start with unit, product objective, hard eligibility and a complete rule baseline; do not start with ANN brand names.

Hint 2

Draw decision → actual impression → interaction → label revision, then separate candidate recall from final rank quality.

Hint 3

Trace the full bundle and final live policy through the mismatch/outage; compute raw vector bytes and bounded pair work before claiming capacity.

Reveal worked answer guidance

A coherent design uses an eligible followed/popular baseline, logs actual impressions separately from responses, builds only mature complete-source labels and uses available historical features. It introduces retrieval/ranking only with distinct metrics and a compatible artifact contract. The fixture computes overlap 2/3, relevance recall 1/3 and separate graded NDCG about .789596. It bounds scoring, rechecks eligibility, returns fewer items when necessary, rejects mixed bundles and retains a complete rollback. It estimates 5.12 GB raw item vectors and 200,000 expensive pairs/s at the declared caps without claiming observed capacity. Product lift and feedback correction require evidence beyond the toy fixture.

Evidence to check in your answer

  • Framing: decision/action/placement, assumptions and two changed-answer branches are concrete.
  • Data: availability, consent, actual exposure, attribution, maturity/completeness, split and immutable lineage hold.
  • Modeling: complete baseline, shape/objective/negative assumptions and a reason to keep the simpler design.
  • Evaluation: distinct vector-overlap/relevance/ranking metrics with duplicate, tie and undefined-query semantics.
  • Integration: explicit PK/FK/cardinality, compatible bundle, bounded work, eligibility and fallback.
  • Operation: gated rollout/rollback, owners, delayed evidence, deletion limits and feasible cost assumptions.

For each item, record Missing, Prompted, Independent or Adaptive evidence. Adaptive means you can revise the reasoning under a changed constraint. Reading completion and readiness are separate.

Sources and verification scope

Original synthetic examples and reference calculations. Sources support narrowly scoped background; they do not establish production performance or independent chapter review.

Rules of Machine Learning ↗ · Baseline/infrastructure and training-serving consistency principles; dated examples are not current architecture claims.

Feast point-in-time joins ↗ · Historical feature retrieval reference; actual availability/revision contracts still need explicit modeling.

Deep Neural Networks for YouTube Recommendations ↗ · 2016 publication page/abstract inspected for candidate-generation versus ranking separation only. Full PDF could not be retrieved. No current YouTube architecture or full-paper review claim.

Faiss metric types and distances ↗ · Metric/normalization definitions only; the fixture executes exact scalar math and no Faiss/ANN benchmark.

Google recommendation systems overview ↗ · General recommendation framing; original candidate/slate examples and workload assumptions.

scikit-learn NDCG API and references ↗ · Metric comparison context; this fixture explicitly chooses exponential gain and deterministic ID ties rather than claiming library-default equivalence.

Primary background links checked during authoring on 2026-10-19. Arithmetic, temporal eligibility, maturity and split reference functions are checked by the bounded local fixture suite. SQL is explanatory, not a migrated production query. No GPU, external dataset, model API or training job is required.