Skip to main content
LearnMLAcademy
Advanced10 min read

End-to-End ML/AI System Design

Master end-to-end ML system design interviews with scalable architectures, with pipeline maps, deployment choices, and production reliability checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Design a fraud decision service around its deadline

System design turns business requirements into data paths, service boundaries, failure behaviour, and measurable contracts. The goal is not to draw the most boxes; it is to explain what must happen, when it must happen, what can fail, and how evidence returns to improve the system.

Our synthesis system scores card transactions for fraud in real time. It must respond quickly without treating every model score as a final truth. A decision policy combines prediction, threshold, deterministic business rules, and a manual-review path.

What You Will Be Able to Explain

  • Translate functional and non-functional requirements into architecture
  • Separate synchronous decisions from asynchronous learning
  • Design feature, model, duplicate-event, and timeout fallbacks
  • Prevent leakage with delayed fraud labels
  • Calculate capacity and plan release/rollback lineage

The contracts in an end-to-end ML architecture

These terms name different responsibilities. Read the meaning before following them through the diagrams and worked example.

Core vocabulary

Core vocabulary
TermMeaning in this lesson
Functional requirementWhat the system must do, such as return approve, review, or reject for each transaction.
Non-functional requirementHow well it must operate: latency, throughput, availability, security, cost, recovery, or auditability.
Decision policyReviewed logic that converts model evidence and business constraints into an action.
HeadroomCapacity above expected load for bursts, failures, maintenance, and estimation error.
Idempotency keyStable identity for one logical transaction so retries or duplicate delivery reuse the prior decision.
Canary releaseA candidate receives limited traffic while guardrails are compared with the current version.
RollbackRoute traffic back to a known-good immutable version when release criteria fail.

Start with the decision deadline, then attach the learning loop

The synchronous path validates the transaction, deduplicates its identity, reads fresh real-time features, obtains a model score, and applies threshold plus business rules. Only these operations belong on the customer-facing deadline because the approve/review/reject result cannot be returned without them.

Prediction logging is initiated on the live path but written durably without making slow analytics block the response. Monitoring, delayed fraud labels, training-dataset construction, candidate training, evaluation, registry approval, canary analysis, and broad release are asynchronous.

End-to-end real-time fraud detection system

How do the live decision path and learning feedback loop connect?

Transaction
Stream + validate
Live features
Model
Threshold + rules
Approve / review / reject
Prediction log
Delayed fraud label
Point-in-time dataset
Train candidate
Registry gates
Canary → production
How to read it: The synchronous path produces an approve, review, or reject decision. Logged predictions and delayed fraud labels later build leakage-safe training data for an evaluated candidate release.

Keep the customer decision path short; move learning work off it

Which operations must finish before the transaction response?

Synchronous · customer waits

validate
feature lookup
infer
decision

Asynchronous · durable background work

log
label join
train
evaluate + release
How to read it: Validation, approved feature lookup, inference, and decision policy are synchronous. Durable logging, labels, training, evaluation, and release workflows are asynchronous.

Design the failure path before it is needed

If the online feature store is unavailable, use only a reviewed fallback: a fresh-enough cache with recorded age, a model designed for a reduced feature set, deterministic high-risk rules, or manual review. If the model times out, do not blindly approve; cancel it and follow the degraded decision policy.

Stream duplicates are handled with a stable transaction/idempotency key and a stored prior outcome. Delayed labels join to the original transaction and prediction timestamp. Features for a historical row are cut off at that time; the later fraud report is the label, never an earlier feature.

A candidate release records code, training data, feature definitions, environment, artifact, metrics, threshold, rules, and runtime versions. Shadow or canary evidence decides promotion. Rollback changes traffic to the previous known-good bundle while preserving the incident trail.

Requirements become measurable design decisions

Requirements become measurable design decisions
RequirementDesign responseEvidence
Low decision latencyShort synchronous path; dependency deadlinesEnd-to-end and per-stage p95/p99
2,000 requests/sec peakReplicas, load balancing, headroom, backpressureLoad test and saturation curve
Fresh behavioural featuresEvent-time stream aggregation + online lookupFeature age and source checkpoint
No duplicate side effectTransaction idempotency key and prior receiptDuplicate/replay test
Delayed fraud truthVersioned prediction log + later label joinJoin coverage, delay distribution, label version
Safe model releaseEligibility gates, canary, known-good rollbackRelease and rollback traces
Auditable decisionRecord feature/model/policy versions and reasonReconstruct one transaction end to end

Worked Example: Calculate minimum theoretical serving capacity

Given: Peak traffic is 2,000 requests/second. One model instance safely handles 250 requests/second under the approved latency target. Assume perfect balancing and no failed or unavailable instance for the theoretical calculation.

  1. Required theoretical count = peak rate ÷ safe per-instance rate.
  2. 2,000 ÷ 250 = 8 instances.
  3. Check: 8 × 250 = 2,000 requests/second, exactly equal to the stated peak.
  4. Eight leaves no capacity for a burst above forecast, one failed instance, deployment replacement, maintenance, or estimation error. Losing one leaves 7 × 250 = 1,750 requests/second.
  5. Production therefore provisions more than the theoretical minimum or defines controlled load shedding. The amount of headroom is chosen from failure tolerance, burst data, scaling delay, SLO, and cost—not a universal percentage.

Result and interpretation: Eight is the minimum mathematical count under ideal assumptions, not a safe production plan. Capacity design includes redundancy, scaling time, overload policy, and validated latency at load.

The following figures turn the example into an operational decision. Follow every branch and note which state is recorded before work continues.

Named failures lead to named safe routes

How does the system avoid blindly approving when a dependency fails?

Feature store unavailableuse approved fresh-enough cache; otherwise review
Model times outcancel; deterministic rules; manual review
Duplicate eventsame idempotency key → return prior decision
Bad canary metricsroute traffic back to known-good model
All paths recordrequest, data, feature, model, rule, and outcome versions
How to read it: Feature-store failure, model timeout, and duplicate events have different responses. Versioned fallbacks, manual review, idempotency keys, and rollback preserve safety and traceability.

Ten system-design questions answered

Ten system-design questions answered
QuestionAnswer for this system
1 · What is synchronous?Validation, deduplication lookup, online features, inference, and decision policy.
2 · What is asynchronous?Analytics logs, labels, monitoring, training, evaluation, and release workflows.
3 · Feature store unavailable?Approved fresh cache or reduced-feature/rule path; otherwise review.
4 · Model times out?Cancel; apply deterministic safety rules or manual review—never blind approval.
5 · Stream duplicates?Reuse transaction idempotency key and stored outcome.
6 · Delayed labels joined?Join to transaction/prediction event time and immutable identifiers.
7 · Leakage prevented?Point-in-time feature cutoff; later fraud report is label only.
8 · Candidate released?Offline gates → registry approval → shadow/canary → gradual traffic.
9 · Rollback?Route to prior immutable model-feature-policy bundle.
10 · Versions recorded?Code, data, feature, environment, model, schema, threshold, rules, and runtime.

Translate capacity and fallback decisions into an implementation

The label above each block states what it is. Runnable Python can be executed as shown with the standard library; pseudocode and configuration communicate architecture and require adaptation to a real platform.

Make the fraud decision path explicit

The model produces evidence; trusted policy produces the action. Every branch writes a versioned reason and uses the transaction key idempotently.

Make the fraud decision path explicitCONCEPTUAL PSEUDOCODE
def decide(transaction):
    prior = decisions.get(transaction.idempotency_key)
    if prior:
        return prior
    validated = validate(transaction)
    features = feature_service.get(validated.card_id, deadline_ms=25)
    if not features:
        return persist_and_review(validated, "features_unavailable")
    score = model.predict(features, deadline_ms=35)
    if score is None:
        return apply_reviewed_fallback(validated)
    action = policy.apply(score, validated, threshold_version="t7")
    return persist_once(action, versions=current_versions())

Describe the release bundle

Rollback must restore compatible components, not only model bytes.

Describe the release bundleILLUSTRATIVE CONFIGURATION
release: fraud-v23
model_artifact: model-v23
feature_contract: fraud-features-v8
request_schema: transaction-v5
decision_policy: policy-v7
threshold: 0.82
runtime_image: sha256:runtime-19
rollback_bundle: fraud-v22
canary_guardrails: [p95_latency, error_rate, review_rate, confirmed_loss]

Make the fraud service's trade-offs explicit

  • Write functional and non-functional requirements, traffic assumptions, data availability, and error costs before choosing components.
  • Keep the synchronous path minimal and time-bounded; make durable learning work asynchronous.
  • Define a safe degraded result for every critical dependency and test it under realistic load.
  • Record compatible bundles of model, features, schema, policy, threshold, and runtime so release and rollback remain coherent.

Failure Analysis and Recovery

Observed failure → likely cause → controlled response

Observed failure → likely cause → controlled response
Observed failureLikely causeResponse
Fraudulent transaction approved during timeoutNo safe degradation policyRules/manual review; never default high-risk absence to approval
Duplicate transaction creates two actionsNo idempotency recordStable key, atomic prior-decision lookup/write
Offline test is unrealistically highDelayed label or future event leaked into featuresPoint-in-time dataset builder and temporal split
Rollback still errorsOld model paired with new incompatible featuresVersion and restore a complete compatible release bundle
Eight instances overload after one failureTheoretical minimum treated as capacity planProvision evidence-based headroom and load shedding

Connect to Earlier Lessons

Summary / Key Takeaways

  • System design begins with the user decision, functional requirements, non-functional requirements, and explicit assumptions.
  • Real-time validation, deduplication, feature lookup, inference, and decision policy form the synchronous fraud path.
  • Logging, delayed labels, monitoring, dataset creation, training, evaluation, and release belong to durable asynchronous workflows.
  • Feature or model failure must route to reviewed cache, reduced capability, deterministic rules, or manual review—not blind approval.
  • Point-in-time joins keep delayed fraud labels out of earlier features and preserve leakage-safe training data.
  • Eight instances are the theoretical minimum for 2,000 requests/second at 250 each, but production needs evidence-based failure and burst headroom.
  • Safe release and rollback require lineage for the compatible model, feature, schema, threshold, policy, data, code, environment, and runtime bundle.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "End-to-End ML/AI System Design"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5numerical/formula
Peak traffic is 2,000 requests/second and each instance safely handles 250. What is the theoretical minimum?
Question 2 of 5practical selection
Which operation must remain on the synchronous fraud-decision path?
Question 3 of 5application/scenario
The model service times out during a high-risk transaction. What is the safest designed response?
Question 4 of 5conceptual
A fraud label arrives two weeks after prediction. How should it enter retraining data?
Question 5 of 5debugging/diagnostic
A rollback restores model v22 but keeps v23's incompatible feature contract. Why does recovery fail?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Peak traffic is 2,000 requests/second and each instance safely handles 250. What is the theoretical minimum?▼

Correct Answer: 8

2,000 ÷ 250 = 8. This exact-capacity result has no headroom for burst, failure, maintenance, or estimation error.

2Which operation must remain on the synchronous fraud-decision path?▼

Correct Answer: Approved real-time feature lookup

The live decision needs validated current features before it can score and return approve/review/reject. Training and analysis can run asynchronously.

3The model service times out during a high-risk transaction. What is the safest designed response?▼

Correct Answer: Use approved deterministic rules or manual review

Missing model evidence must follow a reviewed degraded policy. High-risk absence should never become an unexamined approval.

4A fraud label arrives two weeks after prediction. How should it enter retraining data?▼

Correct Answer: Joined as the later outcome while features remain cut off at prediction time

The delayed report is the target label. Point-in-time features may include only facts known when the historical decision was made.

5A rollback restores model v22 but keeps v23's incompatible feature contract. Why does recovery fail?▼

Correct Answer: Rollback must restore a compatible model-feature-policy-runtime bundle

A model version depends on its input, decision, and runtime contracts. Coherent bundle versioning makes rollback operational rather than nominal.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next