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
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
Real Project Structure
Here is how a production ML system is organized. Each directory maps to a specific responsibility in the architecture:
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:
- Popularity-based recommendations (baseline)
- Collaborative filtering
- Two-tower deep learning model
- 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
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.
| Quantity | Symbol | Worked value | Unit |
|---|---|---|---|
| Peak request rate | lambda | 10,000 | requests per second |
| p99 latency budget | T_p99 | 100 | milliseconds |
| Requests in flight | L = lambda x W | 1,000 | concurrent |
| Batch per replica | b | 32 | requests |
| Fleet size | N = ceil(L / b) | 32 | GPU replicas |
| Cost per prediction | C_pred | 1.8e-6 | USD |
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
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
| Component | Technology | Why |
|---|---|---|
| Candidate Generation | Two-tower model + FAISS ANN | Fast retrieval from 10M items |
| Re-ranking | LightGBM | Interpretable, fast, handles business rules |
| Feature Store | Redis (online) + BigQuery (offline) | Low-latency serving + historical training |
| Training | Spark + PyTorch distributed | Handle 100M user interactions |
| Serving | Triton Inference Server | GPU 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:
| Severity | Detection | Action |
|---|---|---|
| Warning | PSI > 0.1 | Investigate, prepare rollback |
| Critical | PSI > 0.25 or accuracy drop >5% | Auto-rollback to previous version |
| Emergency | System failure | Circuit 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:
-
Model Optimization
- Quantization: FP16 -> INT8 (2x throughput, <1% quality loss)
- Pruning: Remove 30% of attention heads
- Distillation: Train smaller student model
-
Serving Optimization
- Continuous batching (vLLM)
- KV-cache for autoregressive generation
- Speculative decoding for faster inference
-
Infrastructure
- GPU autoscaling with Kubernetes HPA
- Request queuing with backpressure
- Edge caching for repeated prompts
-
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:
| Aspect | Online Features | Batch Features |
|---|---|---|
| Latency | <10ms (Redis) | Minutes-hours (Snowflake) |
| Freshness | Real-time updates | Daily/hourly snapshots |
| Cost | Higher (always-on infra) | Lower (compute on schedule) |
| Use Cases | Fraud detection, real-time recs | Training 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:
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:
| Aspect | A/B Testing | Canary Deployment |
|---|---|---|
| Purpose | Measure model impact | Reduce deployment risk |
| Traffic Split | 50/50 or configurable | 1% -> 5% -> 25% -> 100% |
| Duration | Weeks (statistical significance) | Hours-days (gradual rollout) |
| Metric | Business KPIs (CTR, revenue) | System metrics (latency, errors) |
| Rollback | Manual based on analysis | Automatic 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:
Raw Data -> Feature Engineering Pipeline -> Feature Registry -> Online Store (Redis)
v v
Offline Store Serving API
(Snowflake) (<10ms latency)
Key Practices:
- Feature catalog: Centralized registry with descriptions, owners, and schemas
- Feature groups: Logical grouping (user features, item features, context features)
- Point-in-time joins: Ensure training/serving consistency
- Feature monitoring: Track drift per feature, not just model-level
- 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
- Module 2: ML Pipeline Architecture - Build robust, automated training and inference pipelines
- Module 3: Feature Store Design - Design and implement production feature stores
- Module 4: Model Serving Architecture - Deploy models at scale with low latency
Continue to ML Pipeline Architecture ->