Optimizing Concurrency and Cost for Large-Model Batch Inference
For batch classification, validation, extraction, and report generation, model quality is often no longer the primary bottleneck. This article presents a practical framework for balancing throughput, concurrency, cost, and reliability. It covers effective throughput modeling, peak/off-peak scheduling, subscription and pay-as-you-go cost allocation, output optimization, local resource limits, concurrency control, task routing, and capacity testing.
1. When Model Capability Is No Longer the Main Constraint
For batch data processing, rule validation, structured extraction, and report generation, task definitions are usually clear: input formats are fixed, decision rules are explicit, output structures can be validated, and individual tasks are independent. For these workloads, mainstream large language models have already passed the “usable” threshold. Because the tasks themselves are relatively deterministic, quality differences between models are often less significant than expected. Continuing to debate which model is “smarter” usually produces limited marginal value.
The factor that most directly determines delivery time is time investment. The same workload may take dozens of hours when executed serially, but only one or two hours with well-designed concurrency. Engineering priorities should therefore shift from model capability comparisons to the balance between throughput, cost, and stability.
2. Quantifying Time Investment: An Effective Throughput Model
Do not look only at how many concurrent requests are running. Focus on effective throughput:
Effective throughput ≈concurrency × average per-worker rate × task success rate× (1 - retry and queueing overhead)
The average rate of each worker is determined by output token volume and time to first token. Task success rate is affected by output-format compliance. Retry overhead is introduced by rate limiting and network instability.
This formula explains a common misjudgment: increasing concurrency from five to ten may appear to double capacity, but if the success rate falls from 98% to 85% and retries double, actual throughput may increase by only 30%.
The relationship between concurrency and throughput usually has three stages:
- Linear region: Throughput increases approximately linearly as concurrency rises because both local resources and service quotas have sufficient headroom.
- Plateau region: A service-side rate limit or local resource bottleneck is reached. Throughput stops increasing while latency begins to rise.
- Declining region: Backoff retries, request queueing, local memory swapping, or CPU throttling cause throughput to fall.
The engineering goal is not to maximize concurrency. It is to identify the beginning of the plateau and maintain a safety margin. In practice, 70%–80% of the concurrency at the inflection point is often a reasonable steady-state operating range.
3. Peak and Off-Peak Scheduling: An Underused Lever
Inference services commonly show significant time-of-day variation. During off-peak hours, quotas may be more relaxed and rate limits higher. Some pricing plans may also offer lower off-peak rates. During daytime peaks, concurrency limits may be tighter and long-running tasks more likely to be interrupted.
This leads to a simple but effective scheduling principle: assign time windows according to how much delay each task can tolerate.
- Run delay-tolerant batch workloads—such as offline cleaning, bulk labeling, and full recalculation—during off-peak hours, using higher concurrency to reduce completion time.
- Run blocking and interactive workloads during peak hours with lower concurrency to protect success rates.
- Add checkpoint-based resumption to long-running jobs. Persist completed results so an interruption during peak hours does not force the entire job to restart.
Specific time windows, discounts, and rate limits are operational policies that may change. They should not be hard-coded into the architecture. Instead, expose them as configuration and use runtime measurements to guide scheduling decisions.
4. Cost Modeling: Balancing Subscription Quotas and Usage-Based Billing
Assume a category of batch jobs requires D tokens per month, a subscription provides Q usable tokens after conversion to a monthly amount, and usage-based pricing is p per token:
Usage-based cost = max(0, D - Q) × pTotal cost = subscription fee + usage-based cost
This produces three practical rules:
- When
Dis significantly greater thanQ, prioritize increasing subscription capacity rather than increasing concurrency. Concurrency changes completion time, not the unit price. - When
Dis slightly belowQ, route as much batch work as possible through the subscription quota, using usage-based billing only for overflow and fallback. - When latency is extremely sensitive and the workload cannot wait for the subscription cycle, pay the usage-based premium only to “buy time.”
A typical layered strategy is to process interactive and medium-sized batch workloads with stable daytime concurrency, then run full batch workloads at higher concurrency overnight. This allows both channels to be used efficiently and avoids the structural waste of leaving subscription capacity unused while spending on usage-based requests.
5. The Real Weight of Cached Inputs: Optimize the Right Target
Discussions about cached input often lose focus. In large-sample billing structures, the cost shares of cached input, uncached input, and output may be close to 1
1. This means that output pricing and output length may dominate total cost, rather than input cache-hit rate.
A practical cost-reduction priority is therefore:
- Compress output: Use JSON Schema to constrain fields, prohibit unnecessary explanations, and require enum values instead of free-form text.
- Split and filter input: Apply rule-based pre-filtering first, and send only the necessary content to the model.
- Use stable prefixes to obtain cache benefits naturally: Keep system prompts, few-shot examples, and tool definitions in fixed positions with byte-level consistency.
- Optimize cache-hit rate only after the previous steps.
Example schema constraints:
{"type": "object","required": ["label", "confidence", "evidence_span"],"properties": {"label": {"type": "string", "enum": ["A", "B", "C"]},"confidence": {"type": "number", "minimum": 0, "maximum": 1},"evidence_span": {"type": "string", "maxLength": 120}},"additionalProperties": false}
Reducing output length by 40% often saves more than increasing cache-hit rate by 20%, while also improving task success rates.
6. Hidden Bottlenecks on the Client Side: Memory, CPU, and Thermal Limits
The most common cause of failure during high-concurrency load testing is not service-side rate limiting. It is that the request generator runs out of resources first.
Each concurrent request requires context buffers, request and response objects, and intermediate parsing state. Memory usage therefore grows roughly linearly with concurrency and per-task context length.
The following are empirical operating ranges. Actual limits vary with context length, runtime, and parsing methods, so they must be calibrated:
- With 64 GB of memory, around 50 concurrent requests is usually stable, with an upper limit of approximately 60.
- With 96 GB of memory, around 80 concurrent requests is usually stable, with an upper limit of approximately 90.
- Once memory utilization exceeds 85%, swapping and garbage collection introduce long-tail latency. Throughput may decline instead of increasing.
Another counterintuitive effect is that higher memory frequency does not necessarily improve end-to-end throughput. Higher frequency can increase power consumption and heat. If this triggers CPU throttling, parsing, serialization, and validation may become slower, reducing total throughput. In practice, stable cooling and sustained clock speeds should take priority over peak specifications.
Official API concurrency limits may be far higher than the local client can support—for example, limits in the thousands of concurrent requests. Capacity planning should therefore be based on local resource benchmarks, not quota limits alone.
7. Engineering Concurrency Control
The core requirements are rate limiting, isolation, and backoff.
import asyncio, randomclass TokenBucket:"""Smooth burst traffic and avoid consuming the quota instantly."""def __init__(self, rate: float, capacity: float):self.rate, self.capacity = rate, capacityself.tokens, self.ts = capacity, asyncio.get_event_loop().time()self.lock = asyncio.Lock()async def acquire(self, n: float = 1.0):async with self.lock:now = asyncio.get_event_loop().time()self.tokens = min(self.capacity,self.tokens + (now - self.ts) * self.rate)self.ts = nowif self.tokens < n:await asyncio.sleep((n - self.tokens) / self.rate)self.tokens = 0else:self.tokens -= nasync def worker(sem: asyncio.Semaphore, bucket: TokenBucket, task):async with sem: # Concurrency isolationfor attempt in range(6):await bucket.acquire() # Rate shapingtry:return await call_model(task)except RateLimited: # 429: backoff with jitterawait asyncio.sleep(min(60, 2 ** attempt) + random.random())except TransientError: # 5xx / timeout: limited retriesawait asyncio.sleep(1 + attempt)raise TaskFailed(task.id) # Persist for later reprocessingasync def run(tasks, concurrency: int, rate: float):sem, bucket = asyncio.Semaphore(concurrency), TokenBucket(rate, rate * 2)return await asyncio.gather(*(worker(sem, bucket, t) for t in tasks))
Important implementation details include:
- Treat 429 responses as quota or rate-limit signals. Back off and reduce concurrency when necessary.
- Treat 5xx responses and timeouts as transient failures that can usually be retried more quickly.
- Write failed tasks to a separate queue instead of retrying indefinitely.
- Make concurrency and request rate runtime-adjustable, allowing them to converge automatically based on observed conditions.
8. Task Tiers and Channel Routing
Classify tasks by latency sensitivity and unit value, then map them to different channels. This is one of the most effective ways to control total cost.
| Tier | Task characteristics | Channel | Concurrency strategy |
|---|---|---|---|
| Interactive | User waiting, one request at a time | Stable low-concurrency channel | 1–2 workers, prioritize success rate |
| Daily batch | Can tolerate an hour-scale delay | Subscription quota channel | 70% of plateau concurrency |
| Overnight batch | Can be delayed until the next day | Off-peak high-concurrency channel | 80% of plateau concurrency with checkpoint resumption |
| Overflow | Sudden additional workload | Usage-based channel | Run as close to the rate limit as practical |
The routing layer should support switching models and channels based on task labels. Make these routing rules hot-reloadable so that a promotion, quota change, or rate-limit adjustment does not require a code change.
9. Observability and Capacity Calibration
Optimization is impossible without measurement. At minimum, collect:
- Throughput: Completed tasks per minute and output tokens per minute.
- Latency: Time-to-first-token P50/P95 and end-to-end P95.
- Stability: Task success rate, format compliance rate, 429 ratio, and retry rate.
- Cost: Average cost per task and cost per thousand results.
- Local resources: Peak memory usage, CPU utilization, temperature, and throttling events.
Use stepwise load testing for capacity calibration. Start with five concurrent requests and increase concurrency in steps of five. Run each level steadily for 10 minutes, recording throughput and error rates. The highest level at which throughput no longer increases and the error rate remains below the target threshold can be used as the capacity limit.
In production, container platforms can host concurrent workers, message queues can distribute tasks and requeue failures, object storage can archive results and intermediate state, and logging and monitoring systems can collect metrics and trigger threshold alerts. These capabilities are available as general-purpose service categories on platforms such as Baidu AI Cloud and can be combined as needed.
10. Implementation Checklist
- Quantify effective throughput before discussing concurrency values.
- Set normal concurrency to 70%–80% of the plateau point and retain automatic downgrade logic.
- Move delay-tolerant tasks to off-peak periods and support checkpoint-based resumption for long jobs.
- Use a two-layer cost structure—subscription quota plus usage-based overflow—and consume quota first.
- Focus cost reduction on output length and format constraints rather than cache-hit rate.
- Use local memory and thermal stability as the real capacity limits during load testing; do not rely solely on API quotas.
- Establish metrics and alerts for throughput, latency, success rate, and cost per task.
- Make time windows, concurrency, pricing, and routing configurable so that strategy changes do not require code changes.
With this approach, batch delivery timelines can often be reduced from days to hours. At the same time, total cost can decline through better quota utilization and shorter outputs. After model capabilities become broadly comparable for a given workload, these engineering improvements remain a reliable source of measurable gains.
