Batch Inference Cost Structure and Concurrency Limits
Batch LLM inference presents two separate planning problems: token pricing and cache behavior determine spend, while concurrency, quotas, retries, and client resources determine elapsed time and stability. This article presents an additive cost model for cached input, uncached input, and output tokens; explains the practical limits of prefix caching; and shows how to find a stable concurrency level by measuring latency, errors, memory, CPU, connections, and thermals. It also provides a checklist and pseudocode for building batch jobs that finish within budget and deadline.
What Goes Wrong in Practice
A common goal for batch inference is simple: process a large number of independent or loosely coupled computations as quickly as possible at an acceptable cost. In practice, two misconceptions often appear.
The first is treating “cached input is cheap” as meaning the entire bill will be cheap. Teams over-optimize prompt caching while ignoring the volume of uncached input and output tokens. The second is treating the maximum concurrency allowed by the service as the concurrency the client can simply run at full blast. As a result, local memory, CPU, connection counts, or thermals run out before the quota does.
Separating these two concerns makes planning much clearer. The unit-price structure determines how much the same workload costs. Concurrency, quotas, and client capacity determine how long the same spend takes and whether the machine can sustain it. Increasing parallelism usually does not change the per-token price; it changes completion time, until you hit rate limits, error retries, or a local resource wall.
Build an Additive Cost Model First
Common billing dimensions in the industry include at least cached input, uncached input, and output. Some platforms also distinguish context length, modality, or tool calls, but the method is the same: add up quantity × unit price by category instead of extrapolating the whole bill from the cheapest unit price.
Before running a production batch, estimate three token volumes on a small, representative sample:
- Cached input: reusable system prompts, fixed instructions, long document prefixes, and similar content.
- Uncached input: per-task questions, variables, retrieved chunks, and other unique content.
- Output: answers, structured fields, and reasoning traces if they are billed.
Let the unit prices be Ph, Pm, and Po, and the quantities be Th, Tm, and To. The approximate cost is:
Cost ≈ Th × Ph + Tm × Pm + To × Po
If failures and retries are involved, include the input and output generated by retries, not only the successful samples.
After a large batch run, the right retrospective question is not “did the cache hit?” but “what share of cost came from each of the three categories?” A near-even split is possible: cached input has a low unit price but a very long prefix; uncached input has many items; output is not short, and its unit price is often significantly higher. In that case, watching only cache hit rate systematically underestimates the bill. Conversely, if tasks hardly reuse prefixes and outputs are very short, cache optimization has little value. The cost share must be calculated from your own samples, not extrapolated from someone else’s task shape.
When prices change, recalculate all three categories for the same workload rather than comparing a single list price. For example, if the output price rises and your tasks have a high output share, total cost will increase more than the unchanged-looking input list price suggests. When comparing two periods or two routing strategies, keep prompts, sample set, and output limits fixed, and change only the price table or routing. Otherwise the comparison is meaningless.
Cache Hits Help, but They Are Not the Whole Cost
The engineering meaning of prefix caching is straightforward: keep stable, reusable long prefixes byte-identical, including whitespace, field order, and system instructions. Any rewrite that “looks the same” can cause a cache miss. Content suitable for a stable prefix usually includes role instructions, output format, and invariant business rules. Content that changes per item, such as user data, timestamps, and random seeds, is not suitable.
Even with a high hit rate, estimate output separately. Generation length is affected by the maximum output token limit, stop conditions, whether step-by-step reasoning is required, and whether complete JSON is required. Setting the maximum output very high does not mean the model will use it every time, but if the task encourages long-form responses, output cost can rise quickly. For batch tasks, a safer approach is to define the shortest usable answer, constrain length with structured fields, and measure the actual output-token distribution from samples. Budget using P90 rather than the mean so that a few unusually long samples do not exhaust the quota.
Concurrency Saves Time, Not Unit Price
The server-side concurrency limit answers one question: how many in-flight requests can be accepted at once? If average request latency is T, effective concurrency is C, and tasks are independent with no server slowdown, rough throughput is about C/T and total wall-clock time is about N × T / C. Raising concurrency from tens to hundreds or thousands can reduce completion time proportionally, but the listed price per token does not change. Total cost is still determined by token volume and unit price. Retries, queuing, and rate limiting will make the real speedup lower than this ideal.
Therefore, “if there is enough money, open concurrency to the maximum” is only approximately correct when all of the following hold: quota and balance are sufficient; error rate does not worsen as concurrency rises; the client has enough connections, memory, and CPU; and no downstream system is a narrower bottleneck, such as result writes, object storage, or a database.
Plan concurrency in layers rather than maxing it out in one step:
- Start at low concurrency and measure per-request latency, output length, and error rate to derive token consumption per unit time.
- Work backward from the budget to the affordable total token volume, and backward from the deadline to the required throughput. Take the tighter of the two.
- Increase concurrency in small steps and watch P95 latency, 429/5xx rates, client memory, and CPU. When latency or error rate degrades noticeably, effective concurrency has passed the sweet spot; adding more lanes only amplifies retries.
Rate-limit responses should include backoff and jitter so that all workers do not retry at the same moment. Idempotent tasks can be deduplicated by task ID to prevent retries from causing duplicate billing and duplicate writes.
The Client Often Falls Before the Quota Does
High concurrency is not just opening more HTTP connections. Every in-flight request occupies connection and TLS state, request and response buffers, parsed JSON objects, retry queues, and memory reserved for results. If response bodies are large, or if results are accumulated in memory before being written to disk, the footprint will be much higher than the intuition of “lanes × one small request.”
In practice, watch four classes of signals at the same time:
- Memory: Does the working set rise linearly with concurrency and approach physical memory, causing swapping? Once frequent swapping begins, CPU time is wasted on I/O, fans and temperatures rise, and throughput falls.
- CPU: Are serialization, compression, TLS, and business post-processing saturating the cores? At full utilization, adding concurrency only increases context switching.
- Connections and file descriptors: Is the connection pool exhausted? Are there too many ports in TIME_WAIT?
- Heat and power: Laptops and small chassis throttle under sustained full load. Nominal CPU utilization may remain high while actual compute capacity drops. In this case, “the machine configuration and cooling are insufficient” is not a slogan; it is a physical constraint on concurrency.
If memory in the 64 GB range reaches about 90% at tens of lanes, the per-lane memory footprint is too large, or results are accumulating inside the process. The right direction is usually to reduce per-lane buffering, stream results to disk, and limit in-flight response size, rather than first switching to a larger server-side concurrency number. A service allowing thousands of concurrent requests only means the remote quota is wide; your process, language runtime, and disk write speed determine how many in-flight requests you can actually hold stably.
One operational split is to separate concurrent collection from local post-processing. Inference workers only fetch tasks, make calls, and append raw results to disk or object storage. A separate rate-limited consumer then parses, validates, and writes results to the database. This way, the inference process has a memory upper bound of approximately concurrency × maximum response size, not the entire day’s result set.
Illustrative in-flight control is shown below. The point is to limit concurrency and release capacity promptly, not to bind to any specific vendor SDK:
sem = Semaphore(capacity = target_concurrency)for task in task_stream:sem.acquire()run_async:try:resp = call_with_timeout(task, max_output=budget_cap)append resp immediately to shard filefinally:sem.release()
Timeouts, cancellation, and shard-file rolling must be designed together. Otherwise, slow requests fill the semaphore, fast requests pile up in the queue, and the memory curve looks like “concurrency is not high, but memory keeps rising.”
How to Set Up a Batch Job That Finishes
The pre-launch checks can be summarized as a checklist.
Budget side: Estimate Th, Tm, To, and failure rate from samples, then apply the current price table to get a total cost range. Use P90 output length for the upper-bound budget. Reserve a retry factor, such as twice the historical error rate. After a price change, recalculate with the same formula instead of judging cost from a single list price.
Time side: Measure average latency and effective token rate at low concurrency. Calculate the required concurrency from the deadline. Then take the minimum of that number, the account concurrency limit, and the stable concurrency obtained from local stress testing. Stable concurrency is defined as the maximum number of lanes at which error rate is acceptable, memory does not keep climbing, and CPU is not distorted by swapping.
Correctness side: Define a machine-readable completion condition for each task so that the model does not make output look “more complete” with longer text while doubling output cost. Tasks that require long output should have a separate queue and a separate budget; do not mix them with short tasks in the same unlimited retry pool.
Operations side: Use sharding, resumability, and deduplication by task ID. After a process crash, rerun only shards whose writes have not been confirmed. Log itemized token counts and cost estimates, not just call counts, so you can later check whether a 1
1 share is accidental or determined by task shape.
Conclusion
When calling large models in batch, cost is determined by cached input, uncached input, and output together; caching is only one lever. Higher concurrency mainly compresses wall-clock time and does not change the unit price. Server-side concurrency limits are remote constraints, while local memory, CPU, connections, and cooling are near-side constraints. Both must be measured. Use fixed samples for itemized costs, stress testing to find a concurrency level that does not trigger swapping or an error storm, and streaming result writes to disk. That is how a large batch can finish within budget and deadline, instead of forcing a choice between fans at full speed and an uncontrolled bill.
