Sub topic 8
Cost and Resource Utilization
This chapter assumes you know basic ML vocabulary, can read Python, and understand what an HTTP API and a scheduled job are. It also assumes you have read the earlier chapters on batch prediction, real-time prediction, and latency versus throughput. Here we turn those ideas into a cost model.
Why cost differs between the two patterns
Serving cost is mostly the price of compute that is allocated, not the price of compute that is used. A cloud instance bills by the hour whether it is scoring one request per second or none. This single fact explains most of the cost gap between batch and real-time serving.
- A batch job rents compute for a bounded window, runs it hot, and releases it. Utilization during the window is high, and cost stops when the job ends.
- A real-time service must be running whenever a request might arrive. Capacity sits idle between requests and during quiet hours. You pay for the idle time.
Neither pattern is always cheaper. The comparison depends on how many predictions you make, how many of them anyone actually uses, and how spiky the traffic is.
The basic cost model
A rough model is enough for early design decisions.
Batch cost per run is approximately the instance price per hour, times the number of instances, times the job duration in hours. Add storage for inputs and outputs, and any data transfer.
Real-time cost per month is approximately the instance price per hour, times the number of instances kept running, times about 730 hours. Add the load balancer, logging, and any feature store lookups.
The unit that makes the two comparable is cost per prediction.
def batch_cost_per_prediction(
price_per_hour: float,
instances: int,
job_hours: float,
predictions: int,
) -> float:
return price_per_hour * instances * job_hours / predictions
def realtime_cost_per_prediction(
price_per_hour: float,
instances: int,
monthly_predictions: int,
hours_per_month: float = 730.0,
) -> float:
return price_per_hour * instances * hours_per_month / monthly_predictions
# 2 million customers scored nightly on one 0.40 USD/hour machine, 1.5 hours per run
nightly = batch_cost_per_prediction(0.40, 1, 1.5, 2_000_000)
# Same machine class, 2 instances for redundancy, 3 million live requests per month
live = realtime_cost_per_prediction(0.40, 2, 3_000_000)
print(f"batch: {nightly:.8f} USD per prediction")
print(f"real time: {live:.8f} USD per prediction")With these numbers the batch job costs about 0.0000003 USD per prediction, and the live service costs about 0.0002 USD, roughly three orders of magnitude more. The numbers are invented, but the shape is typical. The live service pays for two machines around the clock to serve a modest load. The batch job pays for 1.5 hours of one machine.
Utilization is the lever
Utilization is the share of allocated compute that does useful work. Batch jobs can approach full utilization because the work is queued up in advance and you can size the cluster to finish in the window you choose. Real-time services rarely do.
Three reasons real-time utilization stays low:
- Traffic is uneven. Daytime peaks may be many times the overnight load. Capacity must cover the peak, so average utilization is far below it.
- Headroom is required. Latency rises sharply as a server nears saturation. Teams often keep average CPU well below the limit so tail latency stays within the target.
- Redundancy is required. Running at least two instances protects against failure and allows rolling deploys. Each is billed in full.
Waste in batch: predictions nobody reads
Batch is not automatically cheap. Its main waste is scoring records whose predictions are never used. A nightly job that scores all 50 million users, when only 200 thousand open the app on a given day, spends most of its compute on unread output.
Ways to reduce this waste:
- Score a subset. Restrict the job to active customers, or to those who will be contacted by a campaign.
- Score incrementally. Re-score only records whose inputs changed since the last run.
- Lower the frequency. If a score barely changes day to day, weekly may be enough. Check this against the staleness requirements covered in the freshness chapter.
Real-time serving has the opposite property. It scores only what is requested, so it never wastes compute on unused predictions. At low or unpredictable volumes this can make it cheaper than batch, because you never score the long tail of records nobody asks about.
def breakeven_requests_per_day(
batch_records: int,
batch_cost_per_record: float,
realtime_fixed_cost_per_day: float,
realtime_cost_per_request: float,
) -> float:
"""Daily request volume at which live serving costs the same as nightly batch."""
batch_daily = batch_records * batch_cost_per_record
return (batch_daily - realtime_fixed_cost_per_day) / realtime_cost_per_request
# 50M records at 0.0000005 USD each, versus a live service with fixed cost 20 USD/day
# and a marginal cost of 0.00001 USD per request.
print(breakeven_requests_per_day(50_000_000, 0.0000005, 20.0, 0.00001))The result is 500,000 requests per day. Below that volume, live serving is cheaper in this example. Above it, batch wins. The function assumes the realtime fixed cost is below the batch daily cost. If it is not, the result is negative and live serving is never cheaper.
Costs beyond compute
Compute is the visible cost. Other items often decide the total.
| Cost item | Batch | Real time |
|---|---|---|
| Compute | Bursty, billed per run | Continuous, billed per hour allocated |
| Storage | Output tables for every run | Little, unless logging requests |
| Feature access | Bulk reads from the warehouse, cheap per row | Low-latency online store, costly per read and per GB |
| Engineering and on-call | Job retries and backfills | Latency targets, autoscaling, incident response |
| Failure cost | A late job delays reports | A down service breaks the product immediately |
The online feature store row deserves attention. A real-time service needs features available in milliseconds, which usually means a key-value store kept in memory or on fast disk. Such stores cost more per gigabyte than warehouse storage, and you must keep them populated and in sync with the offline data used in training. The skew chapter covers the correctness side of that requirement. The cost side is that you maintain two copies of the data.
Operational cost is real but hard to quantify. A real-time service needs on-call coverage, capacity planning, and load testing. A batch job needs monitoring and a plan for reruns. Real time generally demands more of both.
Levers for lowering cost
For batch:
- Use interruptible or spot capacity. A batch job can restart from a checkpoint if an instance is reclaimed, so the discount is usually safe to take.
- Scale the cluster so the job finishes just inside the deadline, not far ahead of it. A job that must finish by 06:00 does not need to finish at 02:00.
- Write results in a columnar format such as Parquet, which reduces storage and downstream read costs.
For real time:
- Autoscale on request rate or CPU, with a floor of at least two instances for availability.
- Use a smaller or cheaper model if the accuracy loss is acceptable. Inference cost scales with model size and with the hardware it needs.
- Batch requests together inside the service (dynamic batching). Grouping several requests into one model call raises throughput per machine at the price of a few milliseconds of added latency. This matters most on GPUs.
- Cache predictions for repeated inputs when the same key is requested often and slightly stale answers are acceptable.
- Scale to zero for rarely used models, accepting a cold start delay on the first request.
Hybrid and cost
A hybrid design precomputes scores for known records and calls the live model only for the rest, as in the get_score function from the hybrid chapter. This usually lands between the two pure costs. The batch job covers the bulk of traffic cheaply. The live service handles a small remainder, so it can be small, but it must still exist and meet its availability target. The fixed cost of running a live service does not shrink to zero just because it sees little traffic.
Common errors
- Sizing real time for average load. Capacity planned from average traffic fails at peaks. Plan from peak plus headroom.
- Ignoring idle cost. A service that sits at 5 percent utilization still pays for 100 percent of its instances.
- Scoring everything in batch by habit. If most outputs are never read, the job is a large recurring bill with little benefit.
- Counting only compute. Feature store, logging, data transfer, and staff time can exceed instance costs.
- Forgetting the cost of staleness. A cheap batch job whose stale scores cause bad decisions is not cheap. Cost is one input to the decision, alongside freshness and latency.
Exercise
A fraud model scores payment transactions. The company processes 400,000 transactions a day, and each must be approved or declined within 200 ms. A nightly batch job would cost far less per prediction. Why is batch still the wrong choice here, and where could you still reduce real-time cost?
Show answer
Batch cannot meet the requirement. Each transaction arrives at an unpredictable time and needs a score within 200 ms, and a nightly job would score it hours after the decision was needed. Cost per prediction is irrelevant when the latency requirement rules batch out. To reduce real-time cost, autoscale with a minimum of two instances, use a smaller or faster model if accuracy allows, use dynamic batching if the hardware benefits, and cache stable features. A batch job can still help in a supporting role, for example precomputing slow-changing customer features that the live service reads.
Exercise
A marketing team scores 20 million customers every night. Only the 500,000 customers in the next day's email campaign use the scores. Name two ways to cut the cost and one risk of each.
Show answer
Option 1: score only the campaign audience. The risk is that someone later wants scores for other customers and they do not exist, so a backfill is needed. Option 2: score incrementally, only customers whose inputs changed. The risk is added pipeline complexity and bugs in change detection, which can leave stale scores for customers wrongly marked as unchanged. Lowering the frequency is also valid, with the risk of staler scores.