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

Batch Prediction Systems

AI System DesignBatch InferenceđŸŸĸ Free Lesson

Batch Prediction Systems

Large-Scale ML Scoring at Petabyte Scale

What You'll Learn

  • 1Derive a batch job's runtime from row count, worker count, and per-worker rate
  • 2Compare batch and real-time cost per prediction before choosing an architecture
  • 3Size checkpoint intervals from measured spot instance interruption rates
  • 4Plan result storage volume and retention for a month of predictions

Why This Matters

Batch prediction systems are essential for:

  • High-Throughput Scoring: Process millions or billions of predictions
  • Cost Efficiency: Leverage spot instances and reserved capacity
  • Complex Models: Use models too expensive for real-time serving
  • Scheduled Workflows: Align with business cycles

â„šī¸

Batch prediction powers critical business functions: daily recommendations, weekly reports, marketing campaigns, and risk assessments.

Batch Inference Pipeline Architecture

Batch Prediction System ArchitectureData Sources- Data Warehouse- Data Lake- Event Logs- External APIsJob Scheduler- Apache Airflow- Cron Jobs- Event Triggers- Dependency ManagementData Preparation- Feature Computation- Data Validation- Schema Enforcement- Data PartitioningModel Loading- Model Registry- Version Selection- Model Caching- A/B Test ModelsBatch Scoring- Spark / Dask- Distributed Computing- GPU Clusters- Fault Tolerance- Progress TrackingResult Storage- Data Warehouse- Feature Store- Cache Layer- Notification ServiceMonitoring- Job Status Tracking- Performance Metrics- Cost Tracking- AlertingCost Optimization- Spot Instances- Auto-scaling- Resource Right-sizing- Scheduling Optimization

Spark Batch Scoring Implementation

Spark batch scoring uses distributed computing to process large volumes of data. A SparkBatchScorer class loads data from parquet files, computes features using Spark DataFrames, and applies a pandas UDF (User Defined Function) for batch prediction. The UDF loads the model, prepares features, and generates predictions in parallel across Spark partitions. Results are saved as partitioned parquet files for efficient downstream consumption.

Airflow DAG for Batch Predictions

An Airflow DAG orchestrates the complete batch prediction workflow:

  1. Check Data: S3 sensor verifies input data availability
  2. Compute Features: Spark job computes features from raw data
  3. Batch Scoring: Spark job applies the model to generate predictions
  4. Store Results: Python operator loads predictions to the data warehouse
  5. Notify: Send completion notification

Tasks are connected sequentially with dependencies, and the DAG runs daily at 2 AM with automatic retries and timeout handling.

Cost Optimization Strategies

Cost optimization for batch predictions involves:

  • Spot Instance Selection: Choose cost-effective instance types based on memory and vCPU requirements, sorted by cost per vCPU-hour
  • EMR Cluster Configuration: Create clusters with spot instances, dynamic allocation, and shuffle service enabled
  • Job Scheduling: Prioritize critical jobs during on-demand windows, schedule flexible jobs during off-peak hours using spot instances, and archive jobs on weekends

Result Storage Patterns

Prediction results can be stored in multiple ways:

  • Data Warehouse: Append predictions with metadata (timestamp, model version, batch ID) and create indexes for fast queries
  • Feature Store: Transform predictions to feature format and store in the online feature store for downstream models
  • Cache Layer: Store hot predictions in Redis with configurable TTL for fast access

Monitoring Batch Jobs

Batch job monitoring tracks operational metrics using Prometheus:

  • Job Counters: Track total jobs and failures by status
  • Duration Histograms: Measure job execution time
  • Record Counters: Track total records processed
  • Active Job Gauges: Monitor currently running jobs
  • SLA Checking: Verify jobs complete within expected time limits

Sizing a Batch Job

Runtime comes from three measured numbers: rows to score, workers available, and rows per second per worker.

Scoring billion rows on workers that each sustain rows per second takes seconds, or about 83 minutes. If the business window is 60 minutes, you have three honest options: add 40 percent more workers, cut features so each worker processes more rows per second, or split the job into incremental partitions that only rescore what changed. Padding the deadline is a fourth option, and the one teams regret.

Cost is where batch wins. At USD 0.50 per spot worker-hour, the same job spends 100 workers x 1.4 hours x 0.50 = USD 70, so cost per prediction is:

That is USD 0.07 per million predictions, roughly two orders of magnitude below a real-time GPU fleet. This gap is the entire business case for batch scoring: anything whose result is consumed later should ride this path.

Spot capacity trades money for interruption risk. With mean time between interruptions minutes and a job running minutes, the probability of at least one preemption is:

An 84 percent chance of being interrupted is not a reason to avoid spot; it is a reason to checkpoint aggressively. Save state every 5 minutes and a preemption costs at most 5 minutes of redone work plus a few minutes to acquire a replacement node, instead of restarting an 83-minute job from partition zero. Without checkpoints, the expected wasted work per run approaches half the job.

Results accumulate just as predictably. With 100 bytes written per prediction:

So a daily billion-row batch produces about 3 TB of predictions per month. Partition results by model version and date, keep 90 days hot for analysis, and aggregate the long tail into daily summary tables, or you will pay warehouse scan costs forever to answer questions that only need the last quarter.

Interview Q&A

â„šī¸

Q: How do you handle failures in batch prediction pipelines?

Answer:

  1. Idempotent Jobs: Ensure jobs can be safely retried
  2. Checkpointing: Save intermediate results
  3. Circuit Breakers: Stop failing jobs quickly
  4. Alerting: Notify on failures
  5. Fallback Strategies: Use previous successful predictions

A batch job with recovery loads checkpoints to determine the starting partition, processes each partition sequentially, saves checkpoints after each partition, and sends alerts on failure for manual intervention.

â„šī¸

Q: How do you optimize batch prediction for cost?

Answer:

StrategyImplementationCost Savings
Spot InstancesUse preemptible VMs60-70%
Auto-scalingScale based on workload30-50%
Resource Right-sizingMatch instance to workload20-40%
SchedulingRun during off-peak hours10-20%
CompressionReduce data transfer10-30%

â„šī¸

Q: How do you ensure data quality in batch predictions?

Answer:

  1. Input Validation: Check data schema and quality
  2. Feature Validation: Ensure features meet expectations
  3. Output Validation: Verify prediction distributions
  4. Monitoring: Track data drift and anomalies

Common Mistakes

Running a batch job without checkpoints on spot capacity

Fix: Checkpoint every few minutes: at an 84 percent preemption chance over 83 minutes, restarts are routine, not exceptional.

Writing predictions without idempotent keys

Fix: Key outputs by batch ID, model version, and entity so a retry overwrites instead of duplicating rows.

Keeping every raw prediction forever

Fix: Aggregate to daily summaries after 90 days, since only the recent window is ever scanned in detail.

Best Practices

  • Right-size workers from the measured rows-per-second rate rather than copying last month's cluster config
  • Separate the scoring job from the load job so a bad load can be retried without rescoring a billion rows
  • Track cost per million predictions alongside runtime, so the batch versus real-time decision stays quantitative

Key Takeaways

  • Runtime is N over P times r: 1 billion rows at 100 workers and 2,000 rows/s each takes 5,000 seconds, about 83 minutes
  • At USD 0.50 per spot worker-hour the same job costs USD 70, which is USD 0.07 per million predictions
  • Spot interruption risk over 83 minutes with a 45 minute mean is 1 - e^(-83/45) = 84 percent, so checkpoint every 5 minutes
  • A billion predictions a day at 100 bytes each is 3 TB per month, so partition by version and date and aggregate the tail

Frequently Asked Questions

Why not just run this workload in real time?

Because the consumer is not waiting. Real-time serving buys latency with an always-on fleet, and that fleet costs roughly 100 times more per prediction than spot capacity used for an hour. If the output is read tomorrow morning, batch scoring on spot is the correct architecture; reserve real-time for predictions that change the outcome of the request in flight.

How do you recover when a job dies at hour two?

Checkpoint after every partition and make writes idempotent, then resume from the last completed partition rather than partition zero. On spot capacity, also request replacement capacity automatically and keep the partition size small enough that a restart is minutes, not hours. The alert that matters is deadline risk: page when the projected finish time passes the window, not when a single task fails.

Where should prediction results land?

Three places with different lifetimes: a partitioned table keyed by model version and date for analysis and audit, the online feature store when downstream models need the score as an input, and a small cache with a TTL when the same score is read repeatedly within minutes. Writing once to a table and projecting from there keeps the three copies consistent.

Interview Questions

Q1: A nightly scoring job must finish by 6 AM. How do you size it?

Measure rows per second per worker first: 1 billion rows at 2,000/s on 100 workers is 5,000 seconds or 83 minutes. Add the load and validation stages, keep total utilization near 70 percent of the window, and verify that one full retry of the slowest stage still lands before 6 AM.

Q2: How do you decide between spot and on-demand capacity?

Compare interruption probability against the checkpoint cost. Over an 83-minute job with a 45-minute mean time between interruptions, preemption probability is 84 percent, so with 5-minute checkpoints you lose at most 5 minutes per event. Use spot for everything checkpointable and on-demand only for the driver or a latency-critical stage.

Q3: How much data do these results generate and how do you control it?

1 billion rows a day at 100 bytes each is 3 TB a month before compression. Partition by model version and date, keep 90 days hot, aggregate the rest into daily summaries, and attach retention policies so an accidental SELECT star cannot scan a year of history.

Quiz

Next Steps

  • Module 7: Recommendation System Design - Apply batch predictions to recommendations
  • Module 8: Search Ranking System - Learn to score and rank items
  • Practice: Design a batch prediction system for a marketing campaign

Continue to Recommendation System Design ->

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