Design a Real-Time Translation API with Batching
System DesignModel answerLast updated
Design an inference backend that aggregates single-sentence translation requests into GPU batches running on a fixed 80 ms execution loop.
You are tasked with designing the backend infrastructure for a high-throughput, low-latency text translation API. Clients send individual sentences over a synchronous network connection (such as gRPC or HTTP/2) and block until the translated text is returned.
To maximize GPU hardware efficiency, the backend cannot run sentences individually. Instead, incoming requests are aggregated into dynamic batches before execution on worker nodes.
The core constraint of your system is: Every batch, regardless of how many sentences it contains, requires exactly 80 ms of processing time on a worker.
Key Requirements & Constraints
- Capacity & Sizing: Derive the throughput bounds per worker and establish a sizing methodology for the GPU fleet based on peak traffic goals and target latencies.
- Batching Policy: Design the trigger mechanisms that close a batch and initiate execution. Analyze the trade-offs between system throughput and end-to-end tail latency across light and bursty traffic patterns.
- Request Lifecycle & Async Routing: Detail how an incoming synchronous request transitions into a batch, executes on a worker, and correctly routes its output back to the waiting client. Explain how client disconnects are handled without corrupting batch state.
- Resilience & Fault Tolerance: Explain how worker node failures, out-of-memory (OOM) faults, or execution timeouts are managed across the impacted batch.
- Real-World Violations: Detail how the design evolves when the assumption of a static 80 ms execution time is relaxed to account for dynamic sentence lengths, token padding, and multiple distinct language pairs.
Present your design systematically, addressing capacity planning, architectural topology, lifecycle routing, and edge-case failure modes.
Hints
Hint 1
Break the batching lifecycle into two distinct delays: assembly time in the queue (accumulation delay) and processing time on the GPU (fixed 80 ms).
Hint 2
Consider using a dual-trigger mechanism for batch closure: max batch size (B) or max waiting time (T).
Hint 3
Map how asynchronous completion futures or channel bridges allow multi-tenant batches to fan out results to individual client HTTP/gRPC streams.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
To fulfill the requirements, we separate the system into two primary tiers:
- API Gateway / Router Tier (Stateless): Accepts incoming client connections, validates requests, assigns unique request IDs, and pushes tasks into language-pair queue aggregators.
- Batch Accumulator & Worker Pool (Stateful/Compute): Consumes requests from language-pair queues, packages them into batches according to a defined closing policy, and dispatches them to GPU worker instances running the translation model.
Client 1 \
Client 2 -> [ API Gateway ] -> [ Aggregator / Batcher ] -> [ GPU Worker Pool ]
Client 3 / | | |
(Awaits Future) (Flushes Batch) (Fixed 80ms Run)
1. Capacity Math & Worker Sizing
Given the fixed batch execution time $T_{\text{exec}} = 80\text{ ms}$:
-
Batches per worker per second: $$\text{Throughput}_{\text{batches}} = \frac{1000\text{ ms}}{80\text{ ms}} = 12.5\text{ batches/sec/worker}$$
-
Single Worker Throughput: If a batch holds at most $B$ sentences, maximum worker capacity is: $$\text{Throughput}_{\text{worker}} = 12.5 \times B\text{ sentences/sec}$$
-
Fleet Sizing Formula: To support a peak incoming load of $R$ requests/sec with an operational headroom factor $H$ (typically $1.2$ to $1.5$ to handle unexpected bursts): $$N_{\text{workers}} = \left\lceil \frac{R}{12.5 \times B} \times H \right\rceil$$
Worked Example:
If $R = 10,000\text{ RPS}$, max batch size $B = 32$, and headroom $H = 1.25$: $$\text{Throughput}{\text{worker}} = 12.5 \times 32 = 400\text{ RPS}$$ $$N{\text{workers}} = \left\lceil \frac{10,000}{400} \times 1.25 \right\rceil = \lceil 25 \times 1.25 \rceil = 32\text{ GPU workers}$$
2. Batch-Closing Policy
The batching engine balances GPU utilization against added queuing latency. We employ a Hybrid Dual-Trigger Policy governed by two limits:
- Maximum Count ($B$): Hard limit on sentences per batch.
- Maximum Hold Time ($T_{\text{wait}}$): Maximum delay an incoming request can wait before forcing a batch close (e.g., $10\text{–}15\text{ ms}$).
Trigger Logic
A batch closes and dispatches to an available GPU worker as soon as either condition is met:
count(batch) == Bcurrent_time - batch.first_item_timestamp >= T_wait
Request 1 arrives -> Start Timer (T_wait = 10ms)
Request 2 arrives -> Count = 2
...
IF Count == B OR Timer expires -> Flush Batch to Worker
Trade-Off Analysis
| Traffic Regime | Dominant Trigger | GPU Utilization | Added Queue Latency | Total Expected Latency |
|---|---|---|---|---|
| High Load ($R \gg B \times 12.5$) | Size Limit ($B$) | Near 100% | $\approx 0\text{ ms}$ | $\approx 80\text{ ms}$ |
| Low / Sparse Load | Timer Limit ($T_{\text{wait}}$) | Sub-optimal ($< B$) | $\le T_{\text{wait}}$ | $\approx 80\text{ ms} + T_{\text{wait}}$ |
Under this model, the worst-case queuing latency added by the accumulator is bounded by $T_{\text{wait}}$, guaranteeing an end-to-end execution window of $\approx T_{\text{wait}} + 80\text{ ms} + \text{network overhead}$.
3. Lifecycle & Response Routing
Because batches group requests from multiple distinct callers, we use an Async Promise/Completer pattern to un-batch outputs.
Detailed Request Lifecycle
[Client] ---> (HTTP/gRPC Stream) ---> [Gateway Handler]
|
1. Creates Promise & UUID
2. Enqueues (UUID, Text)
|
v
[Batch Aggregator]
|
3. Forms Batch [Req1, Req2...]
4. Dispatches to Worker
|
v
[GPU Worker]
|
5. Execs batch (80 ms)
6. Returns Array [Trans1, Trans2...]
|
v
[Client] <--- (HTTP Response) <--- [Gateway Handler] (Resolves Promise)
- Ingress: Client submits a sentence via an HTTP/2 or gRPC connection.
- Handle Allocation: The API Gateway creates a unique
request_id, instantiates a local completion channel (or thread-safe Future), and registers(request_id, Future)in an in-memoryPendingMap. - Queue Enqueue: The Gateway pushes
(request_id, source_text)onto the internal batch queue. - Batch Assembly: The Aggregator collects items, closes the batch according to the dual-trigger policy, and issues an RPC call to a GPU worker.
- Execution & Fan-Out: The GPU returns an ordered list of translations corresponding to the index positions of the input batch.
- Resolution: The Gateway iterates through the result array, looks up each
request_idin thePendingMap, and pushes the translated string into the corresponding channel, resolving the client’s request.
Handling Disconnections
- If a client drops their TCP connection mid-request, the Gateway marks the associated local
Futureas cancelled. - Worker Isolation: The batch executing on the GPU is not cancelled. Because the GPU run takes a fixed 80 ms, attempt to interrupt or slice an active batch mid-flight costs more control-plane overhead than letting it finish.
- Cleanup: When the batch finishes, the Gateway attempts to write results to the local response channel. If marked cancelled/closed, the output for that specific sentence is discarded silently.
4. Failure Modes & Resilience
Worker Crash / Hardware Fault
- If a worker node crashes or encounters a GPU driver panic mid-execution, the RPC between the Aggregator and the Worker fails.
- Retry Strategy: The Aggregator re-submits the entire batch to a healthy worker. Retries are capped at
max_retries = 1. - Idempotency: Because requests carry a globally unique
request_id, duplicated downstream processing won't duplicate state.
Queue Overflow & Admission Control
If all GPU workers are saturated ($100%$ utilization) and incoming RPS exceeds maximum system throughput:
- Queue Bounds: Enforce a hard maximum depth on the pending queue ($Q_{\text{max}}$).
- Load Shedding: If $Q_{\text{max}}$ is exceeded, incoming requests are rejected immediately with
HTTP 429 Too Many RequestsorgRPC ResourceExhausted. - Shedding Strategy: Immediate shedding prevents unbounded queuing delays where requests wait hundreds of milliseconds in memory only to time out on the client side.
5. Relaxing the Fixed 80 ms Assumption
In production ML pipelines, the fixed 80 ms assumption breaks due to three primary operational realities:
Dynamic Token Lengths & Padding Overhead
- Issue: Sentences vary in sequence length. Model attention layers scale quadratically or linearly with sequence length ($O(N^2)$ or $O(N)$). Padding short sentences to match the longest sentence in a batch wastes compute.
- Solution: Transition from fixed request-count batching ($B$) to Token Budget Batching (e.g., maximum $4096$ tokens per batch). Group requests by similar sentence length (bucketed batching) prior to execution.
Multi-Language Routing Constraints
- Issue: Different language pairs (e.g., EN$\rightarrow$ES vs. EN$\rightarrow$ZH) often require different model weights or specific decoder sub-networks, preventing cross-language batching within a single model instance.
- Solution: Partition queues and GPU worker pools by language pair routes. Use dynamic worker re-allocation (shifting GPUs between language pools) based on real-time traffic demand per language.
Production Monitoring Metrics
To detect when hardware bounds or model characteristics diverge from operational assumptions, track these key metrics:
+------------------------------------+---------------------------------------------------+
| Metric | Significance |
+------------------------------------+---------------------------------------------------+
| gpu_execution_duration_ms (p50/p99)| Detects drift from 80ms target due to token size. |
| batch_fill_ratio (size / B) | Evaluates efficiency of batch-closing timer. |
| aggregator_queue_wait_time_ms | Measures queue delay before batch assembly. |
| client_cancel_rate | Indicates client-side timeouts from long queues. |
+------------------------------------+---------------------------------------------------+