Markdown Editor

ML System Design Document Template

Problem framing, metrics, data, features, baselines, training, offline and A/B evaluation, serving, monitoring, rollout

IA & DonnéesCompletsystemdesignmath

Mode d'emploi: Use before building a production machine learning feature. Fill problem framing, success metrics and data sources first, and always compare against a simple baseline. The main pitfall is optimising a model metric that does not move the business metric.

Aperçu

ML System Design: [System or feature name]

Complete design document for a production machine learning system: problem framing, success metrics, data and labelling, features, model choice, training, offline and online evaluation, serving, budgets, monitoring, retraining, fairness and safety, failure modes and rollout. Replace every [bracketed] value and every row marked Example. Worked examples use a product recommendation feature for an online shop.

Document control

FieldValue
Document ID[MLSD-SYSTEM-001]
System / feature[Name]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Author(s)[@author]
Reviewers[@ml-reviewer], [@platform-reviewer], [@product-owner]
Classification[Internal / Confidential]
Last updatedYYYY-MM-DD
Related[PRD], [Model card], [Datasheet], [AI risk assessment], [Data pipeline spec]

Approvals

RoleNameDecisionDate
ML lead[@name][Approved / Changes requested]YYYY-MM-DD
Product owner[@name][Decision]YYYY-MM-DD
Platform / SRE[@name][Decision]YYYY-MM-DD
Responsible AI / privacy[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft
0.2YYYY-MM-DD[@name]Example: Replaced real-time features with hourly batch after latency review
1.0YYYY-MM-DD[@name]Example: Approved for build

Contents

1. Problem framing and success metrics

1.1 Problem statement

[Who has the problem and what it costs today. Example: "Shoppers on product pages see 'related items' chosen by a static category rule; fewer than 2% click them, and catalogue items outside the top 500 are almost never discovered."]

1.2 Why machine learning

[Why rules or heuristics are not enough, and what non-ML alternative was considered. Example: "A co-purchase rule covers only 30% of products; personalised ranking is needed for the long tail."]

1.3 ML task formulation

AspectDecision
Task typeExample: Ranking: order 200 candidate products for a (user, page) pair
Prediction targetExample: Probability the user adds the item to cart within the session
Unit of predictionExample: (session, anchor product, candidate product)
Prediction timeExample: Online, at page render
Action taken on outputExample: Show top 8 candidates in the carousel

1.4 Success metrics

LevelMetricCurrentTargetGuardrail
BusinessExample: Add-to-cart rate from carousel1.8%3.0%Overall conversion must not drop
BusinessExample: Revenue per session[value]+1.5%Return rate must not rise more than 0.2 pt
Model (offline)Example: NDCG@80.21 (rule)at least 0.30Calibration error at most 0.05
Model (offline)Example: Recall@50 of candidate generationn/aat least 0.85
SystemExample: p99 inference latencyn/aat most 60 msPage render p99 unchanged

For classification-style components, use the usual definitions:

Precision=TPTP+FP,Recall=TPTP+FN,F1=2⋅Precision⋅RecallPrecision+Recall\text{Precision} = \frac{TP}{TP + FP}, \qquad \text{Recall} = \frac{TP}{TP + FN}, \qquad F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

For ranking, normalised discounted cumulative gain at cut-off kk:

DCG@k=∑i=1k2reli−1log⁡2(i+1),NDCG@k=DCG@kIDCG@k\text{DCG@}k = \sum_{i=1}^{k} \frac{2^{rel_i} - 1}{\log_2(i + 1)}, \qquad \text{NDCG@}k = \frac{\text{DCG@}k}{\text{IDCG@}k}

2. Data sources and labelling

2.1 Data sources

IDSourceContentVolumeFreshnessOwnerContains personal data
SRC-01Example: Clickstream eventsViews, clicks, add-to-cart40 M events/dayStreaming, under 1 minWeb platformYes, pseudonymous user ID
SRC-02Example: Product catalogueTitle, category, price, stock1.2 M productsHourlyCatalogue teamNo
SRC-03Example: OrdersPurchases and returns300 k/dayDailyCommerce teamYes
[SRC-nn][Source][Content][Volume][Freshness][Owner][Yes / No]

2.2 Labels

[How labels are defined and produced, label delay, noise and class balance. Example: "Positive = add-to-cart within the same session after an impression; negatives sampled from impressions without action at 1:20. Labels available within 1 hour. Position bias corrected with inverse propensity weights from a 1% randomised slot."]

2.3 Leakage and bias risks

RiskExamplePrevention
Target leakageExample: Feature uses cart contents after the impressionPoint-in-time feature joins
Feedback loopExample: Model only learns from items it already shows5% exploration traffic
Selection biasExample: Logged-in users over-representedWeighting; separate evaluation for guests
[Risk][Example][Prevention]

3. Feature pipeline

Feature groupExamplesComputedStoreFreshnessOwner
User historyExample: Last 50 viewed categories, 30-day spend bandStreaming aggregatesOnline feature store5 minRecs team
ProductExample: Price band, category embedding, stock flagBatchOnline and offline storeHourlyRecs team
ContextExample: Device, time of day, page typeAt requestNoneReal timeWeb platform
CrossExample: Co-view count of anchor and candidateDaily batchOffline and online storeDailyRecs team
[Group][Examples][How][Store][Freshness][Owner]

Skew controls: [Example: one feature definition used for both offline and online computation; daily job compares feature distributions between training snapshots and logged serving features].

4. Model selection and baselines

OptionDescriptionNDCG@8 (validation)p99 latencyComplexityDecision
Baseline AExample: Static category rule (current)0.212 msLowFallback
Baseline BExample: Popularity within category, last 7 days0.242 msLowComparison
Candidate 1Example: Gradient-boosted ranker on features in 30.3118 msMediumChosen
Candidate 2Example: Two-tower neural retrieval plus transformer re-ranker0.3375 msHighRejected: latency, ops cost
[Option][Description][value][ms][L / M / H][Decision]

Rationale: [Why the chosen model, and what would make you revisit.]

5. Training pipeline

StepDetail
Data snapshotExample: 28-day window, point-in-time join, snapshot ID recorded
SplitsExample: Time-based: train days 1-24, validation 25-26, test 27-28
Hyperparameter searchExample: 40 trials Bayesian search on validation NDCG@8
ComputeExample: 1 CPU node, 64 vCPU, about 40 minutes per run
ArtefactsModel file, feature list, metrics, data snapshot ID, code commit
Registry[Model registry and naming convention]
ReproducibilityExample: Same snapshot and seed reproduce NDCG within 0.002

6. Offline evaluation

CheckMethodAcceptance criterion
Overall qualityNDCG@8 on test daysat least 0.30 and at least 0.05 above Baseline B
SlicesExample: New users, guests, mobile, long-tail productsNo slice more than 10% below its baseline
CalibrationExpected calibration errorat most 0.05
RobustnessExample: Products with missing price or imageNo errors; graceful score
UncertaintyBootstrap 95% CI over sessionsLower bound above target
[Check][Method][Criterion]

7. Online evaluation

ItemPlan
DesignExample: A/B test, 50/50 split, randomised by user ID
Primary metricExample: Add-to-cart rate from carousel
Guardrail metricsExample: Overall conversion, page latency p99, return rate, error rate
Minimum detectable effectExample: +0.3 pt absolute on 1.8% baseline
DurationExample: At least 14 days to cover two weekly cycles
Stop ruleExample: Stop early if any guardrail degrades significantly at the 99% level

Approximate sample size per arm for a two-proportion test with baseline rate pp, absolute effect δ\delta, significance α\alpha and power 1−β1 - \beta:

n≈2 (z1−α/2+z1−β)2  p(1−p)δ2=2 (1.96+0.84)2×0.018×0.9820.0032≈30 800n \approx \frac{2\,(z_{1-\alpha/2} + z_{1-\beta})^{2}\; p(1-p)}{\delta^{2}} = \frac{2\,(1.96 + 0.84)^{2} \times 0.018 \times 0.982}{0.003^{2}} \approx 30\,800

8. Serving architecture

The request path retrieves candidates, fetches features, scores with the model and falls back to the rule-based list on any timeout.

ComponentResponsibilityScalingTimeout
Recommendation APIOrchestrate, enforce budget, fall backStateless replicas80 ms overall
Candidate generatorReturn 200 candidatesCached per anchor product20 ms
Online feature storeServe user and product featuresManaged, partitioned10 ms
Ranker serviceScore candidatesCPU replicas, autoscaled on QPS25 ms
[Component][Responsibility][Scaling][ms]

9. Latency and cost budgets

Stepp99 budget
Candidate generation20 ms
Feature fetch10 ms
Scoring 200 candidates25 ms
Network and serialisation5 ms
Total60 ms (headroom 20 ms to the 80 ms timeout)

Serving cost per 1 000 requests, with instance cost cc per hour and sustained throughput qq requests per second per instance:

C1000=1000⋅c3600⋅q=1000×0.403600×150≈0.00074 currency unitsC_{1000} = \frac{1000 \cdot c}{3600 \cdot q} = \frac{1000 \times 0.40}{3600 \times 150} \approx 0.00074 \ \text{currency units}
ItemEstimate per month
Serving compute[value]
Feature store[value]
Training compute[value]
Logging and storage[value]
Total[value]

10. Monitoring

LayerSignalThresholdActionOwner
Systemp99 latency, error rate, fallback ratep99 above 60 ms, fallback above 2% for 10 minPage on-call[@platform]
Data qualityNull rate, out-of-range values per featureAny feature null rate above 5%Alert, block retraining[@data]
Data driftPopulation stability index per top-20 featurePSI above 0.2Investigate within 1 day[@ml]
Prediction driftScore distribution shiftKS statistic above 0.1Investigate[@ml]
Model qualityDaily NDCG@8 on logged outcomesDrop above 10% vs 28-day meanConsider rollback[@ml]
BusinessCarousel add-to-cart rateDrop above 15% day over dayReview with product[@product]

Population stability index for one feature with bins ii, expected share eie_i and actual share aia_i:

PSI=∑i(ai−ei)ln⁡aieiPSI = \sum_{i} (a_i - e_i) \ln \frac{a_i}{e_i}

11. Retraining

AspectPolicy
ScheduleExample: Weekly, Sunday 02:00 UTC
TriggersExample: PSI above 0.2 on 3 or more top features; quality drop above 10%
Validation gateExample: Offline criteria in 6 plus shadow scoring for 24 h
PromotionExample: Automatic if gate passes and change in NDCG within +/-5%; manual approval otherwise
RollbackExample: Previous registry version re-pinned in under 5 minutes

12. Fairness, safety and privacy

ConcernMeasureMitigation
Seller exposure fairnessExample: Share of impressions for small sellers vs catalogue shareExposure floor in re-ranking
Sensitive inferencesExample: Recommendations revealing health or pregnancy purchasesSensitive categories excluded from history features
Personal dataExample: Use of browsing historyConsent check; opt-out disables personalisation
Harmful contentExample: Age-restricted products to minorsPolicy filter after ranking
[Concern][Measure][Mitigation]

13. Failure modes

IDFailureImpactDetectionMitigation
FM-01Feature store unavailableNo personalisationFallback rate alertServe static rule list
FM-02Silent training-serving skewQuality drop without errorsFeature parity jobBlock promotion on parity failure
FM-03Popularity feedback loopLong tail never shownCatalogue coverage metricExploration traffic
FM-04Bad model promotedBusiness metric dropQuality and business alertsAutomatic rollback
[FM-nn][Failure][Impact][Signal][Mitigation]

14. Rollout plan

StageTrafficDurationExit criterion
Shadow0% shown, 100% scored3 daysLatency and parity within budget
Canary1%2 daysNo guardrail degradation
Experiment50%14 daysPrimary metric significant, guardrails healthy
General availability100%n/aApproval from product and ML lead

Rollback: [Feature flag name, who can flip it, expected time to effect].

15. Open questions and references

IDQuestionOwnerDue
OQ-01Example: Do guests get personalisation from session-only history?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

References: [PRD], [Model card], [Datasheets], [Experiment platform guide].

Standard and licence note

Based on common industry practice for machine learning system design documents. Original text written for this collection; example numbers are illustrative. Template licence: MIT.

Modèles associés