DEV Community

Aman Kumar
Aman Kumar

Posted on Originally published at dev.to

Building an Asynchronous Dynamic Batching Engine for LLM Streaming in FastAPI

Deploying Large Language Model (LLM) services to production presents a fundamental systems challenge: balancing operational throughput with per-request latency. Traditional synchronous HTTP paradigms fail under generative AI loads. Running one GPU forward pass per incoming request degrades GPU utilization (often dropping compute engine Tensor Core efficiency below 15%) while naively batching requests can introduce unbounded tail latencies ($p_{99}$) for concurrent streams.

To achieve production efficiency, systems engineers must construct continuous, dynamic micro-batching engines that sit between high-concurrency async web frameworks (like FastAPI) and low-level GPU execution contexts.

This deep dive covers the implementation of a memory-bounded, backpressure-aware, dynamic micro-batching middleware capable of streaming Server-Sent Events (SSE) using Python’s native asyncio primitives.


Systems Architecture: High-Throughput Stream Pipeline

In a high-concurrency LLM inference architecture, the web server layer must never directly trigger synchronous tensor computations. Instead, incoming requests are decoupled from compute execution via a multi-producer, single-consumer (MPSC) async event pipeline.

Below is the architectural flow illustrating how concurrent async client requests are routed through a bounded queue, aggregated into dynamic batches by a scheduler task, and dispatched back through client-specific stream channels.

+------------------+      +------------------+      +------------------+
|  HTTP Client 1   |      |  HTTP Client 2   |      |  HTTP Client N   |
+--------+---------+      +--------+---------+      +--------+---------+
         |                         |                         |
         +-------------------------+-------------------------+
                                   |
                                   v  [HTTP SSE Request]
+----------------------------------------------------------------------+
|                         FastAPI Router Layer                         |
|  - Request Validation & Token Allocation                             |
|  - Backpressure Semaphore Check (Rejects with 429 if Overloaded)     |
+----------------------------------+-----------------------------------+
                                   |
                                   v Push Task to Bounded Queue
+----------------------------------------------------------------------+
|             Inference Scheduler Queue (asyncio.Queue)                |
|  Bounded Memory Buffer (maxsize=1024)                                |
+----------------------------------+-----------------------------------+
                                   |
                                   v Poll (Batch Trigger: Max Size OR Timeout)
+----------------------------------------------------------------------+
|                   Dynamic Batch Scheduler Loop                       |
|  - Aggregates up to N prompts into batch tensor matrix                |
|  - Flushes when batch size == BATCH_SIZE or elapsed >= TIMEOUT       |
+----------------------------------+-----------------------------------+
                                   |
                                   v Non-blocking Thread/CUDA Dispatch
+----------------------------------------------------------------------+
|                    Mock Compute / Inference Engine                   |
|  - Continuous Iterative Generation Pass                              |
|  - PagedAttention / Token Generation Loop                            |
+----------------------------------+-----------------------------------+
                                   |
                                   v Chunk-wise Yield to Response Queue
+----------------------------------------------------------------------+
|                 Client Response Stream Queue Channel                 |
|  - Dedicated asyncio.Queue per active streaming response             |
+----------------------------------+-----------------------------------+
                                   |
                                   v SSE Response Dispatch
+----------------------------------------------------------------------+
|                    Client Stream Receiver (SSE)                      |
+----------------------------------------------------------------------+
Enter fullscreen mode Exit fullscreen mode

Key Architectural Controls

  1. Backpressure via Bounded Queues: Memory is finite. Unbounded queues lead to Out-Of-Memory (OOM) crashes under traffic spikes. We enforce strict limits via a capacity-bounded queue coupled with a semaphore guard to fail fast (HTTP 429) when queue depth exceeds safety limits.
  2. Dynamic Batching Window: The scheduler task uses a dual-trigger flushing strategy:
    • Size Trigger: Flush immediately when batch size reaches MAX_BATCH_SIZE.
    • Time Trigger: Flush partial batches if MAX_WAIT_TIME_SECONDS elapses to satisfy time-to-first-token (TTFT) SLAs.
  3. Async Channel Decoupling: Each client request injects an isolated asyncio.Queue into the pending job metadata. As tokens generate, the execution worker emits tokens directly into individual client response channels.

Production Implementation

The script below is a fully functional, zero-dependency (other than FastAPI and Uvicorn) implementation of an asynchronous dynamic batching streaming server. It simulates an asynchronous inference engine producing tokens iteratively for multiple concurrent clients.

import asyncio
import json
import logging
import time
import uuid
from contextlib import asynccontextmanager
from typing import AsyncGenerator, Dict, List, Optional
from fastapi import FastAPI, HTTPException, status
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field

# Setup production logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger("LLMInferenceEngine")

# Configuration Constants
MAX_BATCH_SIZE = 8
MAX_WAIT_TIME_SECONDS = 0.05  # 50ms aggregation window
MAX_QUEUE_DEPTH = 500
MAX_CONCURRENT_REQUESTS = 100

# System Health and Backpressure State
REQUEST_SEMAPHORE = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)


class GenerationRequest(BaseModel):
    prompt: str = Field(..., min_length=1, max_length=4096)
    max_tokens: int = Field(default=64, ge=1, le=512)
    temperature: float = Field(default=0.7, ge=0.0, le=2.0)


class InferenceTask:
    """Internal task tracking wrapper containing input parameters and yield queues."""

    def __init__(self, request_id: str, prompt: str, max_tokens: int):
        self.request_id = request_id
        self.prompt = prompt
        self.max_tokens = max_tokens
        self.response_queue: asyncio.Queue[Optional[str]] = asyncio.Queue()
        self.created_at = time.perf_counter()


class DynamicBatchScheduler:
    """Core Scheduler aggregating individual jobs into micro-batches for vector processing."""

    def __init__(self, input_queue: asyncio.Queue[InferenceTask]):
        self.input_queue = input_queue
        self.is_running = False
        self._worker_task: Optional[asyncio.Task] = None

    async def start(self):
        self.is_running = True
        self._worker_task = asyncio.create_task(self._batch_processing_loop())
        logger.info("Dynamic Batch Scheduler initialized.")

    async def stop(self):
        self.is_running = False
        if self._worker_task:
            self._worker_task.cancel()
            try:
                await self._worker_task
            except asyncio.CancelledError:
                pass
        logger.info("Dynamic Batch Scheduler halted.")

    async def _batch_processing_loop(self):
        while self.is_running:
            batch: List[InferenceTask] = []
            start_time = time.perf_counter()

            # Block until at least one item is available
            try:
                first_task = await self.input_queue.get()
                batch.append(first_task)
                self.input_queue.task_done()
            except asyncio.CancelledError:
                break

            # Accumulate additional requests up to MAX_BATCH_SIZE or until timeout hit
            while len(batch) < MAX_BATCH_SIZE:
                elapsed = time.perf_counter() - start_time
                remaining_time = MAX_WAIT_TIME_SECONDS - elapsed
                if remaining_time <= 0:
                    break

                try:
                    task = await asyncio.wait_for(
                        self.input_queue.get(), timeout=remaining_time
                    )
                    batch.append(task)
                    self.input_queue.task_done()
                except (asyncio.TimeoutError, asyncio.CancelledError):
                    break

            if batch:
                logger.info(
                    f"Executing batch of size {len(batch)}. "
                    f"Wait duration: {(time.perf_counter() - start_time)*1000:.2f}ms"
                )
                # Dispatch execution concurrently without blocking the scheduler loop loop
                asyncio.create_task(self._execute_batch(batch))

    async def _execute_batch(self, batch: List[InferenceTask]):
        """Simulates iterative generation forward pass across a batched tensor context."""
        try:
            max_iterations = max(t.max_tokens for t in batch)

            for step in range(max_iterations):
                # Simulate token processing latency per step (e.g., CUDA forward pass)
                await asyncio.sleep(0.02)  # 20ms per token generation

                for task in batch:
                    if step < task.max_tokens:
                        token_payload = {
                            "token_id": step,
                            "text": f" token_{step}",
                            "finished": step == (task.max_tokens - 1),
                        }
                        await task.response_queue.put(json.dumps(token_payload))
                    elif step == task.max_tokens:
                        # Signal stream completion for this stream
                        await task.response_queue.put(None)

        except Exception as exc:
            logger.error(f"Execution failure during batch run: {str(exc)}")
            for task in batch:
                await task.response_queue.put(None)


# Global Engine Infrastructure References
pending_queue: asyncio.Queue[InferenceTask] = asyncio.Queue(maxsize=MAX_QUEUE_DEPTH)
scheduler = DynamicBatchScheduler(input_queue=pending_queue)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup Engine Logic
    await scheduler.start()
    yield
    # Graceful Shutdown
    await scheduler.stop()


app = FastAPI(
    title="High-Throughput LLM Engine",
    version="1.0.0",
    lifespan=lifespan,
)


async def sse_generator(task: InferenceTask) -> AsyncGenerator[str, None]:
    """Reads tokens from the task's private queue and yields formatted SSE data."""
    try:
        while True:
            token_json = await task.response_queue.get()
            if token_json is None:
                # Execution finished
                break
            yield f"data: {token_json}\n\n"
    except asyncio.CancelledError:
        logger.warning(f"Client disconnected early from request {task.request_id}")
    finally:
        REQUEST_SEMAPHORE.release()


@app.post("/v1/generate", response_class=StreamingResponse)
async def generate_stream(payload: GenerationRequest):
    # Enforce backpressure limit
    if not REQUEST_SEMAPHORE.acquire():
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Engine capacity reached. Backpressure threshold active.",
        )

    request_id = str(uuid.uuid4())
    task = InferenceTask(
        request_id=request_id,
        prompt=payload.prompt,
        max_tokens=payload.max_tokens,
    )

    try:
        # Push into bounded scheduler queue non-blocking
        pending_queue.put_nowait(task)
    except asyncio.QueueFull:
        REQUEST_SEMAPHORE.release()
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Inference scheduler queue full.",
        )

    return StreamingResponse(
        sse_generator(task),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",  # Disables proxy buffering (e.g., NGINX)
        },
    )


@app.get("/healthz")
async def health_check():
    return {
        "status": "healthy",
        "queue_depth": pending_queue.qsize(),
        "available_capacity": REQUEST_SEMAPHORE._value,
    }
Enter fullscreen mode Exit fullscreen mode

Technical Deep-Dive: Critical Performance Patterns

1. Dual-Trigger Dynamic Batching

The core logic of the micro-batching mechanism resides within _batch_processing_loop. If an engine processes requests one by one, compute capability is wasted on baseline memory overhead (loading model parameters into GPU SRAM).

However, if an engine waits until a batch is 100% full before running inference, early incoming requests suffer severe tail latency penalty.

The implementation balances these needs using asyncio.wait_for:

$$\text{Timeout}{\text{remaining}} = \text{T}{\text{max}} - (t_{\text{current}} - t_{\text{start}})$$

By recalculating remaining_time dynamically inside the accumulation loop, the scheduler guarantees that no individual request waits longer than MAX_WAIT_TIME_SECONDS before being dispatched to a micro-batch, while still filling up the batch context as fast as concurrent incoming traffic permits.

2. Preventing GIL Contention and Managing Async Queues

Python's Global Interpreter Lock (GIL) can become a bottleneck when handling high packet rates. The architecture isolates operational concerns:

  • I/O Worker Tasks: FastAPI endpoints run entirely non-blocking on the asyncio event loop. Pushing an InferenceTask into an asyncio.Queue takes $\mathcal{O}(1)$ time.
  • Compute Execution Tasks: Real inference code (e.g., PyTorch models, C++ bindings via Pybind11) should execute inside a dedicated thread pool via asyncio.to_thread or an external IPC worker pool. The simulated sleep in _execute_batch mimics an async-yielding tensor framework executor (such as TensorRT-LLM or vLLM).

3. Graceful Backpressure & Memory Bounding

Under extreme load, an uncontrolled system degrades due to queue buildup. This issue is handled through two complementary mechanisms:

  1. REQUEST_SEMAPHORE: Restricts total simultaneous in-flight connections (both queued and currently generating).
  2. pending_queue = asyncio.Queue(maxsize=MAX_QUEUE_DEPTH): Hard limits system buffer depth. If the queue fills up, put_nowait() instantly raises asyncio.QueueFull, translating into a fast HTTP 429 Too Many Requests response.

This ensures memory footprint bounds are enforced at all times, preventing system crashes due to memory exhaustion under unexpected traffic spikes.


Conclusion & Next Steps

When scaling AI systems, high availability and low latency require treating compute as an isolated, asynchronous execution context. Implementing a micro-batching scheduler directly within your FastAPI service yields an efficient middleware pattern that maximizes token generation throughput while maintaining control over tail latency.

For production systems, consider extending this system by adding:

  • PagedAttention integration for dynamic KV-Cache allocations.
  • Priority Queue Scheduling to process short prompts ahead of long-context background runs.
  • Continuous (Iterative) Batching, where finished streams leave the batch instantly to allow new incoming requests to join mid-generation.

To review more real-world system implementations, visit my repository on GitHub.

Top comments (0)