Elastic Architecture for High-Concurrency AI Inference Services
This article explains how to build an elastic architecture for high-concurrency AI inference services. It breaks the design into five layers—ingress, scheduling, compute, resources, and governance—and covers admission control, request prioritization, asynchronous results, dynamic batching, stateless instances, model warm-up, composite scaling metrics, multi-level caching, graceful degradation, circuit breaking, and observability. It also suggests a four-phase rollout order so teams can first stay available under spikes, then improve throughput and cost, and finally validate capacity with regular load tests.
1. Why Traffic Spikes Always Arrive at the Busiest Moment
A last name is added to a travel delegation’s roster just before departure, and by the time the media are still analyzing the composition of the list, the delegation has already boarded. This “plans can’t keep up with changes” rhythm is equally common in business systems: a campaign configuration is adjusted at the last minute, an upstream partner suddenly increases traffic, or trending content is instantly reshared—any of these can multiply request volume several times within minutes. For AI inference services, the impact is even more pronounced: the compute cost of a single request is far higher than that of an ordinary query, and the scaling speed of accelerator pools such as GPUs is constrained by instance startup, model loading, and GPU memory warm-up, so they cannot be rolled out in seconds the way stateless web services can.
Therefore, the goal of an elastic architecture is not to “never be overloaded,” but to keep the impact of overload within a controllable range: the core path stays available, non-core capabilities degrade in an orderly way, and the system recovers automatically after traffic subsides. The following sections break this down across five layers: ingress, scheduling, compute, resources, and governance.
2. Ingress Layer: Turning an Uncontrollable Flood into a Controllable Queue
The core responsibility of the ingress layer is to “shape” traffic, not to “absorb” it. Three common practices apply.
First, admission control. Set concurrency and queue limits at the gateway; requests beyond the limits fail fast or enter a waiting queue, preventing all requests from piling onto the backend and causing an avalanche.
# Example: token-bucket-based admission controlclass TokenBucket:def __init__(self, rate: float, capacity: int):self.rate, self.capacity = rate, capacityself.tokens, self.last = capacity, time.monotonic()def allow(self) -> bool:now = time.monotonic()self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)self.last = nowif self.tokens >= 1:self.tokens -= 1return Truereturn False
Second, priority classification. Divide requests into three types—interactive (low latency required), batch (throughput required), and retryable—each with its own queue and quota, so offline jobs cannot crowd out the online path.
Third, asynchronous results. For generative tasks with unstable latency, use a “submit–query” or callback pattern: the request first returns a task identifier, the result is written to object storage or a message queue, and the client polls or subscribes to retrieve it. This releases the ingress connection quickly, so long-running compute no longer occupies connection resources.
3. Scheduling Layer: Batching and Queues Are the Key Levers for Throughput
Low accelerator utilization is often not a lack of compute but a sign that per-request granularity is too small. Dynamic batching merges multiple requests within a short time window into a single forward pass, significantly increasing output per unit of resource. In engineering terms, three parameters must be constrained at the same time: maximum batch size, maximum wait window, and maximum sequence length per batch.
# Example: window-based batchingasync def batch_worker(queue, model, max_batch=16, window_ms=8):while True:batch, first = [], time.monotonic()while len(batch) < max_batch and (time.monotonic() - first) * 1000 < window_ms:try:batch.append(await asyncio.wait_for(queue.get(), timeout=window_ms / 1000))except asyncio.TimeoutError:breakif batch:outputs = model.infer([r.payload for r in batch]) # one forward passfor req, out in zip(batch, outputs):req.future.set_result(out)
If the window is too small, a batch cannot form; if it is too large, latency exceeds the limit. It is advisable to use online latency percentiles as a feedback signal for dynamic adjustment. In addition, the queue itself needs a maximum length and a timeout-drop policy to avoid a backlog in which “the results are ready but nobody wants them anymore.”
4. Compute Layer: Statelessness, Externalized Sessions, and Warm-Up
Inference instances should be designed as stateless: session context, multi-turn conversation history, and intermediate task state are all externalized to a cache or storage service, and the instance retains only model weights and temporary compute buffers. Only then can any instance be replaced or scaled at any time.
Model loading is the main cost of cold starts. Viable approaches include: storing model files in object storage with a read-only cache on the node locally; preinstalling a base runtime in the image and mounting the model on demand; keeping a set of always-on “warm instances” to absorb bursts; and using parallel reads and pre-allocation of GPU memory during loading. Note that actual loading time depends on model size and hardware, so it should be based on your own measurements rather than copying someone else’s numbers.
5. Resource Layer: Scaling Policies Must Separate Metrics and Cooldowns
Scaling decisions should be based on a composite metric of “queue backlog duration + latency percentiles + resource utilization,” not a single CPU utilization metric—in inference scenarios, the CPU is often idle while the accelerator is saturated. Recommended policies:
- Scale out early: use predictive or scheduled policies to complete scaling and warm-up before predictable peaks;
- Scale in conservatively: set a longer cooldown window and graceful instance exit (drain traffic first, then wait for in-flight requests to finish);
- Tiered resource pools: the online pool guarantees latency, while the offline pool uses interruptible resources for batch jobs, with queues decoupling the two types of load.
6. Governance Layer: Caching, Degradation, Circuit Breaking, and Observability
Multi-level caching can eliminate a large amount of repeated compute: cache results for identical requests, reuse prefix state for long prefixes, and apply semantic-level caching for retrieval requests. Cache keys must include the model version and key parameters to avoid reading stale data after a version update.
Degradation must follow a predefined order: first disable non-core enhancement capabilities, then reduce generation length or sampling precision, and finally rate-limit non-critical tenants. Circuit breaking is triggered by error rate and timeout rate, combined with exponential backoff retries and jitter to prevent retry storms.
Observability should cover at least four categories of signals: request-level (latency percentiles, error code distribution, queue wait time), resource-level (utilization, GPU memory usage, temperature), model-level (input/output length distribution, batch size distribution), and cost-level (resource consumption per request). Logs, metrics, and traces should land in a logging service, monitoring and alerting, and a tracing system respectively, with capacity watermark alerts so that “scaling” shifts from reactive firefighting to a proactive plan.
7. Recommended Rollout Order
Phase one: statelessness and queue-based peak shaving, to solve “staying unbreakable.” Phase two: introduce dynamic batching and multi-level caching, to solve “handling load at low cost.” Phase three: refine predictive scaling and degradation plans, to solve “staying stable.” Phase four: make load testing routine and build a capacity model, using fixed scenarios to validate the architecture’s effectiveness on a regular basis. Baidu AI Cloud provides composable base components in general capabilities such as container platforms, message queues, object storage, and monitoring and alerting, which can serve as the foundation for implementing the architecture above.
