Online vs. Batch Inference: ML Deployment Architecture
Training a machine learning model is only half the engineering challenge. To deliver real-world value, a trained model must process unseen production data and generate predictions—a process known as Inference (Model Serving).
When deploying machine learning models into production, system architects face a fundamental architectural decision: should predictions be generated on demand in real time (Online Inference) or precomputed on a schedule across large datasets (Batch Inference)?
Choosing the wrong serving architecture can increase cloud infrastructure costs, violate latency service-level agreements (SLAs), overload prediction services, or leave users with outdated recommendations.
Modern ML systems commonly use three inference patterns:
- Batch Inference: Generate predictions for large datasets on a scheduled basis.
- Online Inference: Generate predictions immediately when an application sends a request.
- Streaming Inference: Continuously process incoming events and generate or update predictions as data arrives.
Understanding these architectures, their infrastructure requirements, cost trade-offs, and real-world applications is essential for designing scalable machine learning systems.
1. Batch Inference (Offline Serving)
Batch inference processes large volumes of accumulated data together, usually on a recurring schedule such as hourly, nightly, or weekly.
Instead of generating a prediction every time an application requests one, the system calculates predictions in advance and stores them in a database, data warehouse, or cache.
When an application needs a prediction, it retrieves the previously calculated result.
1.1 Batch Inference Architecture
Consider an e-commerce platform with 10 million customers.
The platform wants to generate product recommendations for every customer.
Running a complex recommendation model whenever each customer opens the application may require significant infrastructure.
Instead, the system can calculate recommendations overnight and store the results.
Data Warehouse / Data Lake
(Millions of Records)
|
v
Scheduled Trigger
(Airflow / Cron)
|
v
Batch Processing
(Spark / Python)
|
v
Batch ML Model
(CPU / GPU)
|
v
Prediction Results
|
+-----+-----+
| |
v v
Database Redis Cache
| |
+-----+-----+
|
v
Downstream Application
/ BI Dashboard / API
How Batch Inference Works
Step 1: Collect Historical Data
The system collects accumulated records from databases, event streams, data warehouses, or data lakes.
Example:
| Customer ID | Age | Previous Purchases | Total Spending |
|---|---|---|---|
| C101 | 25 | 8 | ₹25,000 |
| C102 | 32 | 12 | ₹48,000 |
| C103 | 28 | 5 | ₹12,000 |
| C104 | 40 | 20 | ₹95,000 |
Step 2: Trigger the Batch Job
A scheduler starts the prediction process at a predefined time.
Common scheduling technologies include:
- Apache Airflow
- Apache Oozie
- Cron Jobs
- Cloud Composer
- AWS Step Functions
For example, a recommendation system may execute its batch prediction job every night at 2:00 AM.
Step 3: Load the Model
The system loads the previously trained and validated model.
The model may be stored in:
- MLflow Model Registry
- Cloud object storage
- A model artifact repository
- A version-controlled deployment package
Step 4: Generate Predictions
The model processes records in batches.
For example:
import pandas as pd
import joblib
# Load historical customer data
data = pd.read_csv("customers.csv")
# Load trained ML model
model = joblib.load("churn_model.pkl")
# Select model features
features = data[
["age", "monthly_spending", "support_calls"]
]
# Generate predictions for all customers
predictions = model.predict(features)
# Generate churn probabilities
probabilities = model.predict_proba(features)[:, 1]
# Store prediction results
data["churn_prediction"] = predictions
data["churn_probability"] = probabilities
data.to_csv("customer_predictions.csv", index=False)
print(data.head())
This example demonstrates the basic workflow. In production, preprocessing must use the same transformations and feature definitions as training, preferably through a saved pipeline or shared feature-processing implementation.
Step 5: Store Predictions
Predictions are saved in a database, warehouse, or low-latency cache.
Example:
| Customer ID | Churn Prediction | Churn Probability |
|---|---|---|
| C101 | No | 0.12 |
| C102 | Yes | 0.89 |
| C103 | No | 0.08 |
| C104 | Yes | 0.76 |
Step 6: Retrieve Predictions
When a customer opens the application, the application retrieves the previously calculated prediction.
It does not need to execute the ML model again for that request.
1.2 Advantages of Batch Inference
1. High Throughput
Batch processing can evaluate millions of records efficiently by using vectorized operations, parallel execution, and distributed computing.
2. Lower Serving Costs
The model does not need to remain available for every individual prediction request.
Computational resources can be allocated to scheduled jobs and released after processing.
3. Efficient Resource Utilization
Batch jobs can use available CPU or GPU capacity during off-peak hours.
4. Simpler Online Infrastructure
Applications retrieve stored predictions rather than invoking an ML service for every request.
5. Suitable for Large-Scale Analytics
Batch predictions can be combined with data warehouse queries, BI dashboards, and reporting pipelines.
1.3 Limitations of Batch Inference
1. Prediction Staleness
Predictions are only as fresh as the latest completed batch.
If recommendations are generated at 2:00 AM, they may not reflect a user's activity at 10:00 AM.
2. Scheduled Processing Delays
A prediction may not become available until the next scheduled execution.
3. Large Data Processing Requirements
Processing millions of records can require distributed computing infrastructure and significant memory.
4. Failed Batch Jobs
A failed job may leave downstream applications with incomplete or outdated predictions unless the system handles failures correctly.
5. Storage Requirements
Precomputed predictions must be stored, updated, expired, and managed.
1.4 Real-World Applications of Batch Inference
| Application | Batch Prediction |
|---|---|
| Customer Churn | Generate daily churn probabilities |
| Recommendation | Prepare personalized product lists |
| Credit Risk | Calculate periodic customer risk scores |
| Demand Forecasting | Predict product demand for upcoming weeks |
| Marketing | Generate customer campaign segments |
| Predictive Maintenance | Calculate equipment failure risk periodically |
| Business Analytics | Populate dashboards with predicted outcomes |
Example: Customer Churn Prediction
A telecom company has 5 million customers.
Every night, a batch job predicts which customers are likely to leave during the next 30 days.
The marketing team retrieves high-risk customer records and creates retention campaigns.
This is a good batch inference use case because the business does not need to recalculate every customer's churn probability every second.
2. Online Inference (Real-Time Serving)
Online inference generates predictions immediately when a user, application, or external system sends a request.
Unlike batch inference, predictions are not necessarily precomputed and stored for future use.
The model receives the current input, processes its features, and returns a prediction.
Online inference is commonly used when decisions depend on the latest available information.
2.1 Online Inference Architecture
Consider a banking application processing a payment.
The bank must evaluate the transaction before approving or declining it.
Waiting for the next scheduled batch would be unacceptable.
The system therefore uses an online prediction service.
User Request
|
v
API Gateway
|
v
Request Validation
|
v
Feature Retrieval
|
v
ML Model Server
|
v
Real-Time Prediction
|
v
Decision / Response
|
v
Application
How Online Inference Works
Step 1: Receive a Request
An application sends input data to the prediction API.
Example:
{
"customer_id": "C101",
"transaction_amount": 75000,
"device": "new",
"location": "Bengaluru"
}
Step 2: Validate the Input
The API checks:
- Required fields
- Data types
- Missing values
- Valid input ranges
- Authentication and authorization
Invalid requests should be rejected or handled through defined fallback behavior.
Step 3: Retrieve Features
The system may retrieve historical customer information from an online feature store.
For example:
- Number of recent transactions
- Average transaction amount
- Previous fraud reports
- Recent device activity
A low-latency database such as Redis may support these lookups.
Step 4: Run Model Inference
The feature vector is passed to the deployed model.
The model generates a prediction.
For example:
\[ P(Fraud\mid X)=0.92 \]
This means the model estimates a 92% fraud probability, assuming its probabilities are appropriately calibrated.
Step 5: Return the Prediction
The application receives the prediction and applies its decision policy.
Example response:
{
"customer_id": "C101",
"fraud_probability": 0.92,
"risk_level": "high",
"recommended_action": "additional_verification"
}
The decision policy may approve, decline, or request additional authentication depending on business rules and risk thresholds.
2.2 Building a Simple Online Inference API with FastAPI
A machine learning model can be exposed through a REST API using FastAPI.
First, install the required packages:
pip install fastapi uvicorn scikit-learn pandas joblib
Assume a trained model has already been saved as model.pkl.
Create main.py:
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
app = FastAPI()
# Load the trained model
model = joblib.load("model.pkl")
# Define request structure
class PredictionInput(BaseModel):
age: float
income: float
spending_score: float
@app.get("/")
def home():
return {"message": "ML Prediction API is running"}
@app.post("/predict")
def predict(data: PredictionInput):
# Prepare model input
features = [[
data.age,
data.income,
data.spending_score
]]
# Generate prediction
prediction = model.predict(features)[0]
return {
"prediction": int(prediction)
}
Run the API:
uvicorn main:app --reload
The prediction endpoint is:
POST http://127.0.0.1:8000/predict
Example request:
{
"age": 25,
"income": 50000,
"spending_score": 80
}
Example response:
{
"prediction": 1
}
This is a simplified demonstration. A production implementation should include the complete preprocessing pipeline, model versioning, request authentication, structured logging, monitoring, timeouts, and robust error handling.
2.3 Advantages of Online Inference
1. Low Prediction Latency
Predictions are generated when requested, making online inference suitable for immediate decisions.
2. Fresh Inputs
The model can use the latest available transaction, user activity, or request context.
3. Interactive Applications
Online inference supports applications where users expect immediate responses.
4. Context-Aware Predictions
The system can use request-specific information such as device type, current location, session activity, and recent behavior.
5. Immediate Decision-Making
It enables real-time fraud checks, dynamic pricing, personalized ranking, and interactive AI applications.
2.4 Limitations of Online Inference
1. Infrastructure Costs
The model-serving infrastructure must be available whenever requests arrive.
GPU-based models can become expensive when traffic is high or utilization is low.
2. Strict Latency Requirements
Feature retrieval, network calls, model execution, and response serialization all contribute to total latency.
3. Scalability Challenges
The service must handle traffic spikes, concurrent requests, and changing request volumes.
4. Operational Complexity
Online services require monitoring, load balancing, autoscaling, version management, and failure handling.
5. Dependency on Other Services
If the feature store or model-serving infrastructure becomes unavailable, prediction requests may fail or become delayed.
2.5 Real-World Applications of Online Inference
| Application | Online Prediction |
|---|---|
| Banking | Fraud risk during payment |
| E-commerce | Personalized product ranking |
| Search Engines | Rank results for a submitted query |
| Ride Sharing | Estimate prices and ETAs |
| Insurance | Instant preliminary risk assessment |
| Cybersecurity | Evaluate suspicious activity |
| Conversational AI | Generate responses to user prompts |
Example: Real-Time Fraud Detection
A customer attempts a ₹75,000 payment.
The banking system retrieves relevant customer and transaction features, evaluates the payment using a fraud detection model, and applies a risk policy.
The result is returned before the payment workflow proceeds.
This is an online inference use case because the decision depends on the current transaction.
3. Streaming Inference (Continuous Real-Time Processing)
Streaming inference processes incoming events continuously rather than waiting for a scheduled batch or handling only isolated API requests.
It is useful when an application needs to monitor changing behavior and update predictions or features as events arrive.
Examples include:
- Live transaction monitoring
- Industrial sensor analysis
- Network intrusion detection
- Real-time clickstream analysis
- Live operational forecasting
Streaming inference is related to online inference, but the request-processing pattern is different.
Online inference generally receives an individual request and returns a response. Streaming inference continuously consumes event records from an event stream and processes them as part of an ongoing pipeline.
3.1 Streaming Inference Architecture
Incoming Events
|
v
Event Producer
|
v
Message Broker
Kafka
|
v
Stream Processor
(Flink / Spark)
|
v
Feature Processing
|
v
ML Model Inference
|
v
Prediction Events
|
+------+------+
| |
v v
Database Alert System
| |
v v
Dashboard Action Service
How Streaming Inference Works
Step 1: Generate Events
Applications, devices, or sensors continuously produce events.
Example:
{
"device_id": "D101",
"temperature": 95,
"timestamp": "2026-11-24T10:00:00"
}
Step 2: Send Events to a Message Broker
A platform such as Apache Kafka receives and distributes events.
Step 3: Process the Stream
A streaming engine processes incoming records and calculates features.
For example:
- Average temperature in the last 5 minutes
- Number of failures in the last hour
- Transaction count in the last 10 minutes
Step 4: Generate Predictions
The ML model processes the newly calculated features.
Step 5: Trigger an Action
The system may send an alert, update a database, or initiate another automated workflow.
3.2 Advantages of Streaming Inference
- Continuous event processing
- Rapid detection of changing conditions
- Near-real-time feature updates
- Suitable for event-driven architectures
- Supports large-scale monitoring systems
3.3 Limitations of Streaming Inference
- More complex infrastructure
- Stateful processing requirements
- Event ordering and late-arriving data challenges
- Duplicate-event handling
- Monitoring and recovery complexity
- Potentially higher operational costs
Streaming systems need careful handling of event time, processing time, checkpoints, retries, and delivery guarantees.
4. Online vs. Batch vs. Streaming Inference
The three architectures differ primarily in how predictions are generated and delivered.
| Dimension | Batch Inference | Online Inference | Streaming Inference |
|---|---|---|---|
| Processing | Scheduled groups | Individual requests | Continuous events |
| Trigger | Timer or scheduled job | API request | Incoming event |
| Latency | Minutes to hours, depending on schedule | Usually milliseconds to seconds | Usually milliseconds to seconds |
| Throughput | Very high | Depends on serving capacity | High continuous throughput |
| Data Freshness | Depends on batch frequency | Latest available request-time data | Continuously updated |
| Infrastructure | Batch compute cluster | Model-serving service | Broker and stream processor |
| Cost Pattern | Scheduled compute | Always-ready or autoscaled services | Continuous infrastructure |
| Best For | Periodic predictions | Immediate decisions | Continuous monitoring |
Latency ranges are illustrative. Real-world systems may operate outside these ranges depending on the model, workload, hardware, and service-level objectives.
4.1 Which Inference Architecture Should You Choose?
| Requirement | Recommended Architecture |
|---|---|
| Predict churn for millions of customers every night | Batch |
| Detect fraud during a payment | Online |
| Update product recommendations periodically | Batch |
| Rank products when a user opens a page | Online |
| Monitor factory sensor data continuously | Streaming |
| Generate weekly sales forecasts | Batch |
| Detect suspicious network traffic as events arrive | Streaming |
| Predict a customer's risk during an application request | Online |
The correct architecture depends on the business requirement rather than simply choosing the newest or most sophisticated technology.
5. Hybrid Inference: Combining Batch and Online Serving
Many production ML systems combine batch and online inference.
This is called a hybrid inference architecture.
The objective is to reduce expensive real-time computation while still responding to user requests using current information.
Consider a video recommendation platform.
It may precompute a list of recommended videos for each user overnight. When a user opens the application, the system retrieves that list and adjusts it using recent activity.
5.1 Hybrid Architecture
Historical User Data
|
v
Batch Pipeline
|
v
Recommendation Model
|
v
Precomputed Results
|
v
Redis Cache
|
|
User Opens Application
|
v
Online API
|
v
Recent User Activity
|
v
Contextual Re-Ranking
|
v
Final Recommendations
The batch system performs expensive work in advance.
The online system makes lightweight adjustments based on the current request.
5.2 Example: E-Commerce Recommendations
Suppose a user frequently purchases electronics.
The platform generates a list of 100 recommended products overnight.
When the user opens the application:
- The system retrieves the precomputed recommendations.
- It checks current product availability.
- It removes products the user has recently purchased.
- It considers the user's latest browsing activity.
- It re-ranks the remaining products.
- It displays the top 10 products.
This architecture provides a useful balance between prediction freshness, response latency, and computational cost.
5.3 Advantages of Hybrid Inference
- Lower online computation requirements
- Faster response times
- Better personalization
- Reduced infrastructure pressure
- Flexible prediction refresh schedules
5.4 Challenges of Hybrid Inference
- Synchronizing batch and online features
- Managing stale cache entries
- Handling missing predictions
- Maintaining consistent model versions
- Preventing duplicate or conflicting updates
A hybrid architecture should define cache expiration, prediction timestamps, model versions, and fallback behavior.
6. Latency, Throughput, and Cost Optimization
Inference architecture is not only about model predictions. It is also about infrastructure performance.
Three important engineering concepts are latency, throughput, and cost.
6.1 Latency
Latency measures how long it takes to complete a prediction request.
For online inference:
\[ Total\ Latency = T_{network}+ T_{features}+ T_{preprocessing}+ T_{inference}+ T_{response} \]
For example:
| Component | Time |
|---|---|
| Network and API | 5 ms |
| Feature Retrieval | 8 ms |
| Preprocessing | 2 ms |
| Model Inference | 10 ms |
| Response Processing | 5 ms |
| Total | 30 ms |
These values are illustrative.
The model itself takes only 10 ms, but the complete request takes 30 ms.
This demonstrates why optimizing only model inference time may not improve the overall user experience significantly.
6.2 Throughput
Throughput measures how many records or requests a system processes during a given period.
\[ Throughput = \frac{Number\ of\ processed\ records} {Time} \]
For example:
If a batch job processes 600,000 records in 10 minutes:
\[ Throughput= \frac{600,000}{600} =1,000\ records/second \]
A batch system may optimize throughput, while an online system may prioritize individual request latency.
6.3 Cost Optimization
Different inference architectures have different infrastructure costs.
Batch Inference Cost Optimization
- Schedule jobs during suitable off-peak periods.
- Use distributed processing only when needed.
- Choose CPU or GPU according to actual model requirements.
- Process records in efficient batches.
- Avoid unnecessary full-dataset recomputation.
- Use incremental scoring when possible.
Online Inference Cost Optimization
- Use autoscaling.
- Cache reusable predictions or features.
- Optimize model size.
- Apply quantization when accuracy requirements permit.
- Use CPU inference for models that do not benefit from GPUs.
- Monitor utilization and tail latency.
- Avoid unnecessary network calls.
Streaming Inference Cost Optimization
- Partition streams appropriately.
- Use efficient state management.
- Avoid unnecessary event processing.
- Tune parallelism based on workload.
- Monitor broker storage and processing lag.
There is no universal rule that batch inference is always cheaper. A frequently refreshed batch pipeline may cost more than a lightweight online service, while a continuously running online GPU service may be more expensive than scheduled batch processing.
The workload and infrastructure utilization determine the actual cost.
7. Production Challenges and Best Practices
A production inference architecture must handle more than successful predictions.
7.1 Model Versioning
Every deployed model should have a version identifier.
For example:
churn_model_v1
churn_model_v2
churn_model_v3
Versioning helps teams:
- Compare model performance
- Reproduce predictions
- Roll back failed releases
- Track model changes
- Maintain deployment history
Tools such as MLflow can help manage model versions and artifacts.
7.2 Data and Feature Consistency
The preprocessing logic used during training must match the preprocessing logic used during inference.
For example, if a model was trained with standardized numerical features, production inputs must use the same fitted scaler.
Avoid independently implementing training and serving transformations without tests.
7.3 Monitoring
Monitor both model quality and infrastructure performance.
| Area | Important Metrics |
|---|---|
| Model Quality | Precision, Recall, F1, AUC, NDCG |
| Latency | Average, p95, p99 |
| Throughput | Requests or records per second |
| Infrastructure | CPU, GPU, RAM, network usage |
| Data Quality | Missing values, invalid inputs, schema changes |
| Model Drift | Feature and prediction distribution changes |
| Reliability | Error rate, timeouts, availability |
7.4 Failure Handling
A reliable system should define what happens when:
- The model service becomes unavailable.
- The feature store cannot be reached.
- A batch job fails halfway through.
- The prediction database is unavailable.
- Events arrive late or more than once.
- A new model release produces unexpected results.
For batch jobs, a useful strategy is to write predictions to a temporary location, validate them, and then publish them atomically or through a controlled version switch.
For online systems, use timeouts, controlled retries, circuit breakers, and safe fallback policies.
For streaming systems, use checkpointing, replayable event logs, and appropriate duplicate-event handling.
7.5 Retraining and Prediction Refresh
Model retraining and prediction refresh are different processes.
- Retraining: Update the model using new training data.
- Prediction refresh: Run an existing model against new or updated records.
A batch prediction job may run every hour even if the model is retrained only once a month.
Similarly, an online model may remain deployed for weeks while processing fresh requests continuously.
A production architecture should define separate schedules and policies for both activities.
8. Common Interview Questions: Online vs. Batch Inference
Q1. What is inference in machine learning?
Inference is the process of using a trained machine learning model to generate predictions for new, unseen input data.
Q2. What is batch inference?
Batch inference processes many records together on a scheduled basis and stores the generated predictions for later use.
Q3. What is online inference?
Online inference generates a prediction when an application sends an individual or small-batch request to a deployed model.
Q4. What is the difference between online and batch inference?
Batch inference prioritizes high-throughput processing of accumulated records, whereas online inference prioritizes fast responses to incoming requests.
Q5. What is streaming inference?
Streaming inference continuously processes incoming events and generates or updates predictions without waiting for a scheduled batch.
Q6. Which inference architecture is best for fraud detection?
Online inference is commonly used to evaluate transactions before a decision is made. Streaming inference may also monitor transaction patterns and update behavioral features continuously.
Q7. Why is batch inference often cost-efficient?
It can process large volumes of records together, use resources only during scheduled execution, and avoid maintaining an always-ready prediction service for every request.
However, actual cost depends on workload and infrastructure utilization.
Q8. Can batch and online inference be used together?
Yes. Hybrid architectures commonly use batch processing for expensive precomputation and online inference for request-specific adjustments.
Q9. What is model serving?
Model serving is the infrastructure and process through which applications access a trained model to generate predictions.
Q10. What is the difference between model training and inference?
Training learns model parameters from historical data. Inference uses the learned parameters to generate predictions from new inputs.
Conclusion
Online, batch, and streaming inference are three important architectures for deploying machine learning models in production.
Batch inference is suitable for large-scale periodic predictions, reporting, customer segmentation, and precomputed recommendations.
Online inference is essential when applications need immediate predictions for transactions, searches, recommendations, and interactive experiences.
Streaming inference is useful for continuously processing event data and reacting to changing conditions.
Many real-world systems combine these approaches through hybrid architectures to balance cost, latency, freshness, and scalability.
The most important lesson is that the best inference architecture is not necessarily the fastest or most advanced one. It is the architecture that satisfies the application's prediction freshness, response-time, throughput, reliability, and cost requirements.
Understanding these deployment patterns is an important step toward building scalable, production-ready machine learning systems.