🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

AI System Design Fundamentals

AI System DesignFoundationsđŸŸĸ Free Lesson

AI System Design Fundamentals

Architecture, Trade-offs, and Production ML Systems

What You'll Learn

  • 1Map an ML problem onto the five production layers: data, features, model, serving, monitoring
  • 2Turn a latency SLA into a per-stage p99 budget that still fits after retries
  • 3Size a replica fleet with Little's law and compute cost per prediction
  • 4Choose batch, near-real-time, or real-time serving from freshness and cost constraints

Why This Matters

Every major tech company (Google, Netflix, Uber, Stripe, LinkedIn) runs AI systems serving millions of users. Understanding how to design these systems is the difference between a data scientist and an ML engineer.

â„šī¸

AI System Design interviews are standard at FAANG, unicorn startups, and any company with a data team. This module prepares you to architect complete ML solutions end-to-end.

What is AI System Design?

AI System Design is the practice of architecting end-to-end machine learning systems that solve real-world problems at scale. It goes beyond model building to encompass data pipelines, feature stores, serving infrastructure, monitoring, and feedback loops.

The ML System Lifecycle

BusinessProblemDataCollectionFeatureEngineeringModelTrainingEvaluation& ValidationDeployment& ServingMonitor& IterateFeedback Loop / Retraining

Key Components of an ML System

1. Data Layer

Responsibility: Ingest, validate, and store raw data from multiple sources.

Key Technologies: Apache Kafka (streaming), Apache Airflow (orchestration), Great Expectations (validation), Delta Lake / Apache Iceberg (storage)

Key Decisions:

  • Batch vs streaming ingestion
  • Data partitioning strategy (time-based, hash-based)
  • Schema evolution and versioning
  • Data quality gates before downstream consumption

2. Feature Layer

Responsibility: Compute, store, and serve features for training and inference with consistency.

Key Technologies: Feast, Tecton, Hopsworks, Redis (online store), Snowflake/BigQuery (offline store)

Key Decisions:

  • Online vs offline feature store
  • Feature freshness requirements (seconds vs hours)
  • Feature sharing across teams
  • Point-in-time correctness for training

3. Model Layer

Responsibility: Train, evaluate, version, and register models.

Key Technologies: MLflow, Kubeflow, Weights & Biases, SageMaker Model Registry

Key Decisions:

  • Training infrastructure (single GPU vs distributed)
  • Experiment tracking and reproducibility
  • Model versioning strategy
  • A/B testing vs canary deployment

4. Serving Layer

Responsibility: Deploy models and serve predictions at required latency and throughput.

Key Technologies: TensorFlow Serving, Triton Inference Server, BentoML, vLLM, KServe

Key Decisions:

  • Real-time vs batch vs near-real-time serving
  • Model optimization (quantization, distillation, pruning)
  • Autoscaling strategy
  • Multi-model serving vs dedicated endpoints

5. Monitoring Layer

Responsibility: Detect drift, performance degradation, and system failures.

Key Technologies: Evidently AI, WhyLabs, Prometheus + Grafana, custom dashboards

Key Decisions:

  • What to monitor (data drift, concept drift, latency, errors)
  • Alerting thresholds and escalation
  • Automated retraining triggers
  • Shadow deployment for comparison

End-to-End ML System Architecture

Production ML System ArchitectureDatabasesPostgreSQL, MongoDBEvent StreamsKafka, Kinesis, Pub/SubFiles & LogsS3, GCS, HDFSExternal APIsCRM, ERP, WebhooksData Ingestion LayerKafka Connect | Apache Airflow | Great Expectations | Schema RegistryFeature StoreOnline: Redis / DynamoDBOffline: Snowflake / BigQueryFeast | Tecton | HopsworksTraining PipelineGPU Cluster | DistributedMLflow | Kubeflow | W&BHyperparameter Tuning | Cross-ValidationModel RegistryVersioning & MetadataApproval & PromotionMLflow Registry | SageMakerModel ServingReal-time API | Batch InferenceTriton | TF Serving | vLLM | BentoMLAutoscaling | Model Optimization | CachingMonitoring & ObservabilityData Drift | Concept Drift | LatencyEvidently | WhyLabs | GrafanaAlerting | Dashboards | Automated RetrainingFeedback Loop -> Retraining TriggerApplicationsProduct RecommendationsSearch Ranking | Fraud DetectionPersonalization | Content ModerationData FlowIngestionFeaturesTrainingRegistryServingMonitoringApplicationsRetraining

Real Project Structure

Here is how a production ML system is organized. Each directory maps to a specific responsibility in the architecture:

Architecture Diagram
ml-recommendation-system/
|-- config/              # Environment-specific configuration
|-- data/                # Ingestion, validation, storage
|   |-- ingestion/       # Kafka consumers, batch loaders
|   |-- validation/      # Quality checks, drift detection
|   `-- storage/         # Data lake operations
|-- features/            # Feature computation and serving
|   |-- store/           # Online (Redis) and offline (Snowflake) stores
|   |-- engineering/     # Feature definitions per entity
|   `-- transforms/      # Normalization, embeddings
|-- models/              # Training, evaluation, versioning
|   |-- training/        # Training orchestration, HPO
|   |-- evaluation/      # Metrics, offline eval, A/B testing
|   `-- registry/        # Version management, promotion
|-- serving/             # Deployment and inference
|   |-- api/             # REST/gRPC prediction endpoints
|   |-- inference/       # Real-time and batch prediction
|   `-- infrastructure/  # Docker, Kubernetes, Terraform
|-- monitoring/          # Observability and alerting
|   |-- metrics/         # Latency, accuracy, throughput
|   |-- drift/           # Data and concept drift detection
|   `-- dashboards/      # Grafana dashboards
|-- pipelines/           # Orchestration (Airflow DAGs)
|-- tests/               # Unit, integration, E2E tests
`-- scripts/             # Train, deploy, rollback

Design Principles

Principle 1: Start Simple, Iterate

Always begin with the simplest model that can serve as a baseline. Complexity should be added only when metrics justify it.

Progression example:

  1. Popularity-based recommendations (baseline)
  2. Collaborative filtering
  3. Two-tower deep learning model
  4. Real-time personalization with context features

Principle 2: Design for Failure

Every component can fail. Build resilience into every layer.

Key patterns:

  • Circuit breaker: Stop calling a failing service, use fallback
  • Graceful degradation: Serve lower-quality results instead of failing
  • Timeout + retry: Prevent cascading failures
  • Health checks: Detect unhealthy components before they cause issues
  • Fallback models: Always have a simpler model ready

Principle 3: Measure Everything

You cannot improve what you cannot measure.

What to track:

  • Latency: P50, P95, P99 for every prediction request
  • Throughput: Requests per second, batch processing rates
  • Accuracy: Real-time accuracy when ground truth is available
  • Drift: Data drift score per feature, concept drift at model level
  • Cost: Compute cost per prediction, storage costs per feature

Key Trade-offs in ML Systems

Critical ML System Trade-offsLatency vs AccuracyFast: Simple ModelAccurate: Complex ->Real-time: <50msBatch: minutes OKLogistic Reg vs Deep NetDistillation, QuantizationFreshness vs CostCheap: BatchFresh: Streaming ->Daily retrain: $10/dayReal-time: $1000/dayOnline LearningFeature freshness SLAsScale vs ComplexitySimple: Single NodeScale: Distributed ->1K QPS: Single GPU1M QPS: Sharded clusterModel parallelismKubernetes orchestrationCost vs PerformanceCheap: CPU, SmallFast: GPU, big ->CPU inference: $0.001GPU inference: $0.01Spot instancesAuto-scaling policiesHow Top Companies Solve These Trade-offsNetflix:Two-stage ranking - fast candidate generation (ANN), then expensive re-ranking for top 10Uber:Michelangelo ML Platform - feature store + model registry + monitoring in one systemGoogle:TFX pipelines - automated training, validation, and deployment with TFX componentsStripe:Real-time fraud detection - ensemble of lightweight models with <50ms latency SLA

Sizing a System Before You Build It

Non-functional requirements turn into arithmetic as soon as you pin down two numbers: request rate and latency target. Suppose the recommendation endpoint must hold ms while serving queries per second at peak. The budget is spent before the model runs:

A realistic split is 5 ms for the gateway, 15 ms for a feature fetch out of Redis, 70 ms for the model, and 10 ms to serialize the response, which sums to exactly 100 ms. That leaves no room for a retry, so experienced teams give the model 60 ms and keep 10 ms of slack, because one retried request otherwise consumes the whole margin.

Throughput converts to hardware through Little's law. With arrival rate and per-request time , the number of requests in flight is:

At per second and s, the system keeps requests in flight at all times. If each GPU replica processes a batch of requests concurrently, the fleet size is:

Cost follows from fleet size. At USD 2.00 per GPU-hour the fleet spends 32 x 2.00 = USD 64.00 per hour, and since an hour holds predictions, cost per prediction is:

So one million predictions cost about USD 1.78 - that is the number you quote when someone asks whether a heavier model is affordable. Error budgets work the same way: an availability target of 99.9 percent over a 30-day month allows seconds of downtime, or 86 seconds per day. One long incident fits that budget; five small flapping ones do not.

QuantitySymbolWorked valueUnit
Peak request ratelambda10,000requests per second
p99 latency budgetT_p99100milliseconds
Requests in flightL = lambda x W1,000concurrent
Batch per replicab32requests
Fleet sizeN = ceil(L / b)32GPU replicas
Cost per predictionC_pred1.8e-6USD

Interview Questions & Answers

â„šī¸

Q1: Design a real-time recommendation system for 100M users. Walk through the full architecture.

Answer Framework:

Step 1 - Clarify Requirements

  • Latency: <100ms for real-time, <24h for batch
  • Throughput: 10K QPS peak
  • Scale: 100M users, 10M items
  • Metric: CTR improvement >15% over baseline

Step 2 - High-Level Architecture

Architecture Diagram
User Request -> API Gateway -> Candidate Generation (ANN) -> Re-ranking (GBDT) -> Response
                    v
              Feature Store (Redis) <- Feature Pipeline (Kafka + Spark)
                    v
              Model Training (GPU Cluster) -> Model Registry -> Deployment

Step 3 - Component Design

ComponentTechnologyWhy
Candidate GenerationTwo-tower model + FAISS ANNFast retrieval from 10M items
Re-rankingLightGBMInterpretable, fast, handles business rules
Feature StoreRedis (online) + BigQuery (offline)Low-latency serving + historical training
TrainingSpark + PyTorch distributedHandle 100M user interactions
ServingTriton Inference ServerGPU batching, multi-model support

Step 4 - Scale Considerations

  • Model sharding for 100M user embeddings
  • Feature caching with TTL based on freshness needs
  • A/B testing framework for safe rollout

â„šī¸

Q2: How do you detect and handle model degradation in production?

Answer:

Detection Layer:

  • Data drift: Monitor feature distributions using PSI (Population Stability Index) or KS test
  • Concept drift: Track model accuracy on recent labeled data vs training baseline
  • Performance drift: Monitor latency, error rates, throughput

Response Playbook:

SeverityDetectionAction
WarningPSI > 0.1Investigate, prepare rollback
CriticalPSI > 0.25 or accuracy drop >5%Auto-rollback to previous version
EmergencySystem failureCircuit breaker, serve fallback predictions

Prevention:

  • Automated retraining triggers when drift exceeds threshold
  • Champion/challenger model comparison
  • Shadow deployment before full rollout

â„šī¸

Q3: You need to serve a large language model at 1000 QPS with <200ms latency. How?

Answer:

Optimization Stack:

  1. Model Optimization

    • Quantization: FP16 -> INT8 (2x throughput, <1% quality loss)
    • Pruning: Remove 30% of attention heads
    • Distillation: Train smaller student model
  2. Serving Optimization

    • Continuous batching (vLLM)
    • KV-cache for autoregressive generation
    • Speculative decoding for faster inference
  3. Infrastructure

    • GPU autoscaling with Kubernetes HPA
    • Request queuing with backpressure
    • Edge caching for repeated prompts
  4. Architecture

    • Model parallelism across multiple GPUs
    • Load balancing across model replicas
    • Circuit breaker for overload protection

â„šī¸

Q4: Explain online vs batch feature serving. When would you use each?

Answer:

AspectOnline FeaturesBatch Features
Latency<10ms (Redis)Minutes-hours (Snowflake)
FreshnessReal-time updatesDaily/hourly snapshots
CostHigher (always-on infra)Lower (compute on schedule)
Use CasesFraud detection, real-time recsTraining data, analytics

Best Practice: Use both. Train on batch features (historical accuracy), serve on online features (real-time freshness). The feature store ensures consistency between training and serving.


â„šī¸

Q5: How would you design an ML system for fraud detection at a payment company?

Answer:

Key Requirements:

  • Latency: <50ms per transaction
  • Accuracy: >99% precision, >95% recall
  • Scale: 50K transactions/second
  • Class imbalance: 0.1% fraud rate

Architecture:

Architecture Diagram
Transaction -> Feature Computation (<10ms) -> Ensemble Model -> Decision Engine
                    v                              v
              Feature Store              Rule Engine (velocity checks)
                    v                              v
              Training Pipeline           Alert / Block / Allow

Model Design:

  • Stage 1: Rule-based filters (velocity, geolocation)
  • Stage 2: LightGBM for fast scoring (<5ms)
  • Stage 3: Deep learning ensemble for edge cases
  • Ensemble: Weighted voting across all stages

Key Trade-offs:

  • Precision vs recall: Block fraud (high precision) vs Flag for review (high recall)
  • Latency vs accuracy: Simple model for speed, complex model for accuracy
  • Freshness vs stability: Online learning for new fraud patterns vs stable batch model

â„šī¸

Q6: What is the difference between A/B testing and canary deployment for ML models?

Answer:

AspectA/B TestingCanary Deployment
PurposeMeasure model impactReduce deployment risk
Traffic Split50/50 or configurable1% -> 5% -> 25% -> 100%
DurationWeeks (statistical significance)Hours-days (gradual rollout)
MetricBusiness KPIs (CTR, revenue)System metrics (latency, errors)
RollbackManual based on analysisAutomatic based on thresholds

When to use which:

  • A/B test when comparing model architectures or features
  • Canary when deploying a new version of an existing model

â„šī¸

Q7: How do you handle feature engineering at scale with 500+ features?

Answer:

Feature Store Architecture:

Architecture Diagram
Raw Data -> Feature Engineering Pipeline -> Feature Registry -> Online Store (Redis)
                                            v                    v
                                      Offline Store         Serving API
                                     (Snowflake)            (<10ms latency)

Key Practices:

  1. Feature catalog: Centralized registry with descriptions, owners, and schemas
  2. Feature groups: Logical grouping (user features, item features, context features)
  3. Point-in-time joins: Ensure training/serving consistency
  4. Feature monitoring: Track drift per feature, not just model-level
  5. Feature versioning: Schema evolution without breaking downstream

Scale Challenges:

  • 500 features x 100M users = 50B feature values
  • Solution: Feature selection (keep top 50-100), embedding for high-cardinality features

Common Mistakes

Designing the model first and the data pipeline last

Fix: Specify data contracts, freshness, and point-in-time correctness before choosing an algorithm.

Quoting average latency instead of tail latency

Fix: Budget p99 explicitly, because the tail is what users feel and what paging alerts fire on.

Shipping without a fallback path

Fix: Add a circuit breaker and a cheap baseline model so an outage degrades quality instead of returning errors.

Best Practices

  • Write the latency budget as a table before picking components, one row per stage with its p99 share
  • Deploy a trivial baseline first so every later model is measured against a number rather than a feeling
  • Track cost per prediction next to accuracy so the trade-off is visible on one dashboard

Key Takeaways

  • A 100 ms p99 budget splits into 5 ms gateway, 15 ms features, 70 ms model, and 10 ms serialization
  • Little's law gives L = lambda x W: 10,000 QPS at 100 ms means 1,000 requests in flight, or 32 replicas at batch 32
  • Cost per prediction is P_hour over 3600 x lambda: USD 64 per hour at 10,000 QPS costs about USD 1.78 per million
  • A 99.9 percent error budget is 2,592 seconds per 30-day month, so one long incident beats five short flapping ones

Frequently Asked Questions

How do you decide between batch and real-time serving?

Read the freshness requirement first, then the cost. If a prediction can be hours old, batch scoring on spot instances costs a fraction of an always-on GPU fleet: a 10 million row nightly job on 16 spot workers finishing in 40 minutes is roughly one GPU-hour of spend. Real-time serving is only worth its cost when the prediction changes the outcome of the request in front of the user, as with fraud scoring, search ranking, or ad selection.

What is the difference between data drift and concept drift?

Data drift is a change in the input distribution, measured per feature with a population stability index or a Kolmogorov-Smirnov test, and it fires before labels exist. Concept drift is a change in the relationship between features and the target, so it only becomes visible once ground truth arrives and measured accuracy drops. Seasonal shopping shifts cause data drift with no accuracy loss, while a new competitor changes click behavior and causes concept drift with no data drift at all.

Why design the failure path before the happy path?

ML systems fail softly. A stale feature, a timeout, or a cold model usually returns a plausible but wrong number instead of a 500, so the failure mode is silent quality loss. Define the fallback first (previous model version, cached prediction, or popularity baseline), wire an alert that fires when the fallback is active, and only then build the happy path on top of it.

Interview Questions

Q1: Size the fleet for a 10,000 QPS endpoint with a 100 ms p99 budget.

Convert to concurrency with Little's law: L = 10,000 x 0.1 = 1,000 in-flight requests. At a batch of 32 per GPU replica, N = ceil(1000/32) = 32 replicas plus one spare for rolling deploys. At USD 2 per GPU-hour that is USD 64 per hour, about USD 1.78 per million predictions.

Q2: Accuracy is fine but p99 latency doubled after launch. How do you find the cause?

Split the budget by stage with per-request timing: gateway, feature fetch, model, serialization. Check whether the feature store lost its cache, whether batch size grew and added queue time, or whether a new path serializes over the network. Tail latency almost always comes from queueing rather than raw compute.

Q3: What do you monitor on day one of a new model?

Four signals cover most failures: input feature distributions and freshness, prediction score distributions, latency percentiles per stage, and the lagged business outcome such as CTR or approval rate. Alert on error budget consumption rather than raw metrics so every warning maps to an action.

Quiz


Next Steps


Continue to ML Pipeline Architecture ->

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement