Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 66

Real-time vs. Batch Inference Patterns

This lesson is built with resources from youtube.com, dat1.co and 1 more site.

Hello! Welcome back to our final module, Architecture for AI & Machine Learning.

In our last lesson, we designed an automated "factory" for producing ML models: the batch training pipeline. We saw how a model can be trained, evaluated, and versioned in a model registry, making it ready for production. But a model in a registry is just a stored asset; its real value comes when we use it to make predictions on new data.

Today, we'll explore how to put that model to work. This process is called inference or model serving. We will focus on the learning outcome: Compare architectural patterns for real-time vs. batch model inference. As an architect, understanding the trade-offs between these two fundamental patterns is crucial for designing systems that meet specific business needs for speed, scale, and cost.

1. What is Model Inference?

After a model is trained, inference is the stage where we feed it new, unseen data to get a prediction. In your work as an enterprise architect, you can think of this as the operational phase where the ML application goes live and starts delivering business value.

Instead of embedding model logic directly into an application—which would be brittle and hard to update—the modern approach is to deploy the model as a distinct, callable service.

Let's begin with a short video from Microsoft Azure that introduces the concept of deploying models and the two primary ways we can call them for inference.

Model deployment and inferencing with Azure Machine Learning | Machine Learning Essentials

This video, 'Model deployment and inferencing with Azure Machine Learning', clearly defines model deployment and introduces the two key inference modes: real-time and batch.

Please watch from the beginning to 03:36. Pay close attention to how the video defines real-time versus batch inferencing and the key driver for each: low latency for real-time and throughput/automation for batch.

As the video explained, the choice between real-time and batch inference is one of the first and most important decisions in designing an ML system. Let's break down the architecture of each.


2. Pattern 1: Batch Inference

Batch inference is an offline process where predictions are generated for a large set of observations at once. The process typically runs on a schedule (e.g., nightly, weekly).

Architectural Pattern:

  1. An orchestrator (like Apache Airflow, which we discussed in the last lesson) triggers a batch inference job on a schedule.
  2. The job loads the desired model version from the Model Registry.
  3. It reads a large "batch" of data from a data source, like a table in your data lakehouse.
  4. It efficiently computes predictions for every record in the dataset.
  5. The results (the predictions) are written back to a data store, such as a new table in the lakehouse or a relational database.

Downstream applications, like a BI dashboard or an email marketing system, then simply read these pre-computed predictions. They are not calling the model directly.

When to Use Batch Inference:
This pattern is ideal when predictions are not needed immediately.

  • Customer Segmentation: Grouping all customers into segments for a marketing team, run weekly.
  • Lead Scoring: Calculating a "propensity to buy" score for all new leads at the end of each day.
  • Inventory Forecasting: Predicting product demand for the next month for all stores in the chain.

The key is that the value of the prediction is not dependent on sub-second timing.


3. Pattern 2: Real-Time Inference (Online Inference)

Real-time inference (also called online inference) is an online process where predictions are generated on-demand for a single observation (or a very small group) with a response returned in milliseconds.

Architectural Pattern:
This pattern follows a service-oriented architecture.

  1. The ML model is packaged and deployed as a live, "always-on" web service (API) on a serving infrastructure like a Kubernetes cluster or a serverless platform (e.g., AWS Lambda, Azure Functions).
  2. A client application (e.g., a website's backend, a mobile app) sends an HTTP request to the model's API endpoint with the features for a single prediction.
  3. A load balancer routes the request to an available model server instance.
  4. The model server computes the prediction and returns it immediately in the API response.

The following diagram illustrates this "Transform, Predict, Result" (TPR) flow for a single real-time request.

Real-time Model Inference Architecture (TPR Pattern)
This diagram shows the typical flow for real-time inference. An application request is transformed into features, fed to a live model for prediction, and the result is post-processed before being returned to the application.

When to Use Real-Time Inference:
This pattern is essential when an immediate prediction is needed to drive a user experience or an automated decision.

  • Fraud Detection: Is this credit card transaction fraudulent? (Must be decided before approving the transaction).
  • Dynamic Pricing: What price should we offer this user for a ride-share trip right now?
  • Product Recommendations: As a user is viewing a product, what related items should we show them on the same page?
Test your understanding!

You are designing a system for a bank that wants to identify which of its mortgage customers are at high risk of defaulting. The goal is to have the bank's financial advisors reach out to these customers with support. Does this scenario call for batch or real-time inference? Why?

Show answer

This is a classic use case for batch inference. The predictions don't need to be instant. A daily or weekly batch job can score all mortgage customers and generate a list of high-risk individuals. The financial advisors can then use this list to plan their outreach. The latency of a batch process (hours) is perfectly acceptable for this business process.


4. Comparing the Patterns: An Architect's View

As an architect, your role is to weigh the trade-offs. The choice between batch and real-time inference involves balancing performance, cost, and complexity.

To deepen our understanding, let's read a concise article that lays out these trade-offs clearly.

Real-time, Batch, and Micro-Batching Inference Explained

The article 'Real-time, Batch, and Micro-Batching Inference Explained' provides a clear, structured comparison of these patterns, covering their pros, cons, and architectural implications.

Please read the entire article. It's short and to the point. Focus on the 'Use when', 'Pros', and 'Cons' for both Real-Time and Batch Inference. Also, take note of the hybrid 'Micro-Batching' approach it introduces.

Based on the resources we've reviewed, here is a summary of the architectural trade-offs:

Characteristic Batch Inference Real-Time Inference
Primary Goal High throughput Low latency
Latency High (minutes to hours) Very Low (milliseconds)
Data Freshness Stale (as of the last batch run) Live (based on real-time features)
Compute Cost Lower (ephemeral, pay-per-job) Higher (always-on, requires idle capacity)
Architecture Job-based, triggered by an orchestrator Service-based, exposed via an API
Operational Complexity Simpler (manage jobs, handle failures) Higher (manage deployments, scaling, uptime, monitoring)

5. A Practical Example: Building a Recommendation Engine

Let's apply these concepts to a recommendation engine, a common ML application. The following video discusses design choices that map directly to our batch vs. real-time patterns.

Design an ML Recommendation Engine | System Design

In our last lesson, we saw a clip from this video about training. Now let's watch a different section from 'Design an ML Recommendation Engine' that focuses on inference.

Watch the clip from 06:00 to 07:19. The video presents two options. Try to map each option to the inference patterns we've discussed: batch and real-time.

As you saw, the video proposes two architectures:

  1. The Inference API: This is a pure real-time pattern. It's fast but can have high latency and cost if the model is complex and called frequently.
  2. The Inference Server + Cache: This is a batch pattern. The inference server pre-generates recommendations and stores them in a fast cache. The user-facing API just reads from the cache, which is extremely fast. This is great for generating a user's main feed but isn't suitable for recommendations that depend on the user's very last action.

Many production systems use a mix of both. For instance, a homepage feed might be generated via a batch process, while the "users who viewed this also viewed..." feature on a product page might use a real-time API.


Conclusion

You now have a framework for thinking about and designing the final, value-delivery stage of the machine learning lifecycle. The choice is not about which pattern is "better," but which is right for the job.

Key Takeaways:

  • Batch Inference: Optimized for throughput. It processes large datasets on a schedule, making it cost-effective for analytics and internal processes where latency is not a concern.
  • Real-Time Inference: Optimized for latency. It serves predictions on-demand via an API, making it essential for user-facing applications and immediate automated decisions.
  • The Choice is a Trade-off: As an architect, you must balance the business need for data freshness and speed against the technical costs and operational complexity of the solution.

Preview of the next lesson:
Over the past few lessons, we've explored feature stores, training pipelines, and now inference patterns. These are all critical components of a larger practice called MLOps (Machine Learning Operations). In our next lesson, we will zoom out and formally define MLOps, looking at how its core components—like experiment tracking, model registries, and automated deployment—unite to create a robust, end-to-end machine learning lifecycle.