Engineer a production ML inference gateway with request batching, model registry…
- User
Engineer a production ML inference gateway with request batching, model registry lookups, and zero-downtime swaps.
Assistant
Engineer a production ML inference gateway with request batching, model registry lookups, and zero-downtime swaps.
The user wants a production-grade ML inference gateway with three specific features:
This is a complex system design and implementation task. I need to provide a high-level architecture and a concrete Python implementation (likely using asyncio and FastAPI) to demonstrate the concepts.
Key Components:
Detailed Design & Logic:
Batching:
asyncio.Queue.asyncio.Future.await asyncio.wait_for(queue.get()) loop. Collect items until max_batch_size OR max_latency reached.Model Registry & Lookups:
ModelRegistry class.get_model_version(name, stage) -> Returns a handle/ID.Zero-Downtime Swaps:
self.model variable.self.model = new_model.Implementation Plan (Python):
FastAPI, uvicorn.DynamicBatcher.submit(item) -> await result._batch_loop() runs forever.Refining the Zero-Downtime Swap: To truly avoid downtime, we can't just swap the variable if the inference is blocking the event loop.
run_in_executor (thread pool) or ensure the model engine is async-compatible (like many Triton/PyTorch backends). For this demo, asyncio.to_thread is best.Step-by-Step Code Structure:
/predict.contextvars or a lock-protected variable.Self-Correction/Edge Cases:
Drafting the Code (Mental or scratchpad):
class Model:
version: str
async def predict(batch): ...
class Batcher:
def __init__(self, model):
self.model = model
self.queue = asyncio.Queue()
async def loop():
batch = []
while True:
# try to get item with timeout
item = await asyncio.wait_for(self.queue.get(), timeout=0.05)
batch.append(item)
if len(batch) >= MAX: process()
# tricky part: handling the timeout and processing together elegantly.
Actually, a cleaner batching logic:
Use asyncio.wait with return_when=FIRST_COMPLETED.
Wait for queue item OR timeout.
If item -> add to batch.
If timeout -> run batch if not empty.
If batch full -> run batch.
Zero-Downtime Specifics: I will implement a "ModelReloader" that simulates fetching a new version from a registry every X seconds and hot-swapping the reference in the Batcher.
Let's assemble the final response.
asyncio and FastAPI.Code Details:
InferenceRequest pydantic model.ModelRegistry class.BatchProcessor class (manages the queue and executes the batch).ModelManager (handles the swap).Refining the Batching Logic for Production Robustness: The naive loop is hard to get right with timeouts. A standard pattern:
while True:
try:
req = await asyncio.wait_for(queue.get(), timeout=max_latency)
batch.append(req)
except asyncio.TimeoutError:
pass # Time to run if batch not empty
if len(batch) >= max_size or (batch and timeout_occurred):
await run_inference(batch)
batch = []
Wait, wait_for raises TimeoutError if nothing comes. If we get one item, we loop back. We need to track time since first item or just fixed interval. Fixed interval (scheduling) is easier but less latency-optimal. Max latency usually means "max time the first item waited".
Let's stick to a fixed tick or simplified logic for readability, but mention the constraint.
The Swap Logic:
We need self.model to be thread-safe (or async-safe).
self._model_ref = None.
swap_model(new_model): self._model_ref = new_model.
The batcher reads current_model = self._model_ref before processing a batch.
Let's write the solution. This solution implements a robust ML Gateway using Python (FastAPI) and asyncio. It demonstrates the "Sessions" pattern for request handling and an atomic pointer-swap strategy for zero-downtime model updates.
You will need fastapi, uvicorn, and pydantic installed.
import asyncio
import time
import uuid
import random
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, field
from datetime import datetime
import threading
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel
import uvicorn
# ==========================================
# 1. Domain Models & Mocking
# ==========================================
class InferenceRequest(BaseModel):
input_data: List[float]
request_id: Optional[str] = None
class InferenceResponse(BaseModel):
request_id: str
predictions: List[float]
model_version: str
latency_ms: float
# Mocking a heavy ML Model object
class MLModel:
def __init__(self, version: str):
self.version = version
self.load_time = time.strftime("%H:%M:%S")
# Simulate weight loading
time.sleep(0.1)
def predict(self, batch_inputs: List[List[float]]) -> List[List[float]]:
# Simulate GPU inference latency (e.g., 20ms)
time.sleep(0.02)
# Logic: Simple transformation for demonstration
return [[sum(x) / len(x)] for x in batch_inputs]
# ==========================================
# 2. Model Registry & State Manager
# ==========================================
class ModelRegistry:
"""
Simulates an external registry (e.g., MLflow, S3).
In reality, this would query a DB or file system.
"""
def __init__(self):
self.latest_version = "v1.0"
def check_for_update(self, current_version: str) -> Optional[str]:
# Mock logic: Randomly decide a new version exists 10% of the time
if random.random() < 0.1:
new_version = f"v1.{int(time.time())}"
print(f"[Registry] New model version detected: {new_version}")
return new_version
return None
def load_model(self, version: str) -> MLModel:
print(f"[Registry] Loading model weights for {version}...")
# In reality, download weights and load into memory
return MLModel(version)
class ModelManager:
"""
Handles the atomic swap of the active model.
"""
def __init__(self, registry: ModelRegistry):
self.registry = registry
# Start with an initial model
self._active_model = self.registry.load_model("v1.0")
self._lock = asyncio.Lock() # Lock for swapping
@property
def model(self) -> MLModel:
return self._active_model
async def update_model_if_available(self):
new_version = self.registry.check_for_update(self._active_model.version)
if new_version:
# Perform load in a thread to avoid blocking the event loop
loop = asyncio.get_running_loop()
new_model = await loop.run_in_executor(None, self.registry.load_model, new_version)
async with self._lock:
# Critical Section: Atomic Swap
print(f"[Manager] Swapping model from {self._active_model.version} to {new_model.version}")
self._active_model = new_model
# ==========================================
# 3. Request Batching Engine
# ==========================================
@dataclass
class BatchQueueItem:
request_id: str
inputs: List[float]
future: asyncio.Future
arrival_time: float
class BatchingEngine:
def __init__(self, model_manager: ModelManager, max_batch_size=8, max_latency_ms=20):
self.model_manager = model_manager
self.max_batch_size = max_batch_size
self.max_latency_ms = max_latency_ms / 1000.0
self.queue: List[BatchQueueItem] = []
self.queue_lock = asyncio.Lock()
self._running = False
async def start(self):
self._running = True
asyncio.create_task(self._batch_loop())
print("[Engine] Batching loop started")
async def submit(self, request_id: str, inputs: List[float]) -> InferenceResponse:
loop = asyncio.get_running_loop()
future = loop.create_future()
async with self.queue_lock:
self.queue.append(BatchQueueItem(
request_id=request_id,
inputs=inputs,
future=future,
arrival_time=time.time()
))
# Wait for the result from the batch processor
result = await future
return result
async def _batch_loop(self):
while self._running:
batch_to_process = []
# 1. Accumulation Phase
start_wait = time.time()
# Wait until we have at least one item
while not self.queue:
await asyncio.sleep(0.001) # Prevent busy loop
if time.time() - start_wait > 1.0: continue # Just a safety catch
# Wait for batch to fill OR timeout
while True:
now = time.time()
elapsed = now - self.queue[0].arrival_time if self.queue else 0
if len(self.queue) >= self.max_batch_size:
break # Batch full
if elapsed >= self.max_latency_ms:
break # Max latency reached for the oldest item
await asyncio.sleep(0.001) # Wait a tiny bit more
# 2. Extraction Phase
async with self.queue_lock:
# Take items
batch_to_process = self.queue[:self.max_batch_size]
self.queue = self.queue[self.max_batch_size:]
if not batch_to_process:
continue
# 3. Inference Phase
try:
inputs = [item.inputs for item in batch_to_process]
# Capture model reference to ensure consistency for this batch
# If a swap happens during predict(), self.model_manager.model might change,
# but `current_model` local var stays constant.
current_model = self.model_manager.model
# Run prediction (simulating blocking call via run_in_executor if real model used)
# Here we run it directly if the mock is fast enough, or thread it.
# We assume `predict` is thread-safe.
# Mocking CPU/GPU work
results = await asyncio.get_running_loop().run_in_executor(
None, current_model.predict, inputs
)
# 4. Completion Phase
for item, result in zip(batch_to_process, results):
item.future.set_result(InferenceResponse(
request_id=item.request_id,
predictions=result,
model_version=current_model.version,
latency_ms=(time.time() - item.arrival_time) * 1000
))
except Exception as e:
print(f"Error in batch processing: {e}")
for item in batch_to_process:
item.future.set_exception(e)
# ==========================================
# 4. Gateway Application
# ==========================================
app = FastAPI()
registry = ModelRegistry()
model_manager = ModelManager(registry)
batcher = BatchingEngine(model_manager)
@app.on_event("startup")
async def startup_event():
await batcher.start()
# Start the model updater poller
asyncio.create_task(model_updater())
async def model_updater():
"""Background task to poll registry for new models"""
while True:
await model_manager.update_model_if_available()
await asyncio.sleep(10) # Check every 10 seconds
@app.post("/predict", response_model=InferenceResponse)
async def predict(req: InferenceRequest):
req_id = req.request_id or str(uuid.uuid4())
# Offload to batcher
response = await batcher.submit(req_id, req.input_data)
return response
@app.get("/health")
async def health():
return {
"status": "healthy",
"model_version": model_manager.model.version,
"queue_size": len(batcher.queue)
}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
BatchingEngine)Located in _batch_loop, this logic solves the "Batching Dilemma" (Latency vs. Throughput).
elapsed).max_batch_size), we fire immediately (Throughput optimized).max_latency_ms), we fire immediately (Latency capped).ModelManager)update_model_if_available, we load the new model weights into memory (new_model) before touching the active reference._batch_loop starts processing, it captures current_model = self.model_manager.model. Even if the manager swaps the model in the middle of predict(), the current batch continues using the old model object until it finishes. The next batch will pick up the new model.asyncio.Lock during the swap and run_in_executor to ensure the heavy loading process doesn't block the API event loop (keeping the gateway responsive).BatchQueueItem uses asyncio.Future. If an exception occurs during inference, it is propagated back to the specific caller via future.set_exception, allowing the API to return a proper 500 error./health endpoint exposes the queue size, which is critical for autoscaling (if the queue grows indefinitely, you need more replicas).