Bounded-Latency AI Inference: Designing a Durable Multi-Model Serving Harness
Dr. Priya Nair
Engineering Team
Index(17 sections)
1. Failure-Domain Analysis & High-Throughput System Topology
A production serving harness must contain failures before it optimizes throughput. A single unhealthy model revision can otherwise consume every shared resource: request slots, scheduler locks, GPU memory, network connections, and retry budgets. The resulting latency spike often appears regional, although the original defect exists in one model process.
Incident reconstruction
At 14:07 UTC, revision fraud-r42 began returning valid health checks but stalled during generation. Its median prefill time remained 38 ms. Its decode loop intermittently stopped for the 2-second execution deadline. This distinction defeated the readiness probe, which tested only model loading and one short prompt.
The region received 1,800 requests per second. Twenty percent targeted fraud-r42. Clients and the gateway each allowed one retry. The effective attempt rate approached:
1,800 × [(0.8 × 1) + (0.2 × 3)] = 2,520 attempts/s
Retry policy increased load by 40 percent while adding no useful capacity. Each model process accepted 32 queued operations. Eight affected GPU workers therefore retained 256 requests, many with expired upstream deadlines. Cancellation signals arrived after dispatch, but the runtime did not interrupt active CUDA graphs.
The centralized scheduler used one mutex for queue selection, worker-state updates, and metadata-cache refreshes. The critical section increased from 18 µs to 410 µs when completion events and retry inserts arrived together. Its theoretical dispatch ceiling fell from 55,555 to 2,439 operations per second. The p99 mutex wait reached 74 ms. Healthy models then missed their dispatch targets despite having idle GPUs.
A shared FIFO also caused head-of-line blocking. Sixty-four stalled requests placed before a healthy request required eight execution waves across eight workers. With a 2-second worker deadline, the healthy request could wait up to 16 seconds before execution. Regional p99 increased from 240 ms to 18.6 seconds. GPU utilization showed 97 percent, but useful-token throughput fell by 61 percent. Utilization alone concealed the failure.
Production topology and control paths
Request & Worker State Machine
The internet boundary introduces untrusted retry behavior and variable network delay. The ingress must preserve the original absolute deadline and idempotency key. It must not create a fresh timeout for each internal attempt.
Admission control is the first capacity boundary. Its 4,096 slots include queued and running requests. When all slots are occupied, the controller rejects new work immediately. A bounded rejection is safer than an accepted request that expires inside the system. Tenant token buckets prevent one customer from consuming the regional slot pool.
The routing ring separates models and tenants before queueing. Each shard owns its queue state and worker index. A stalled revision can fill only its 256-entry queue. The scheduler does not borrow queue capacity from healthy revisions. Cross-AZ dispatch remains permitted, but each AZ has an independent concurrency budget and circuit breaker.
A centralized scheduler simplifies fairness and global bin packing. It also creates one lock domain and one failure domain. At 2,500 dispatches per second, even a 400 µs serialized path consumes the full service interval. A sharded scheduler reduces contention approximately with shard count when keys distribute evenly. Eight shards reduced measured p99 lock wait from 74 ms to 3.8 ms in replay. Sharding does not solve hot keys. A popular model therefore needs sub-shards or revision-specific worker pools.
The node boundary contains host memory exhaustion, runtime crashes, and network-interface faults. The GPU boundary contains out-of-memory errors, device resets, and thermal throttling. Model processes must have fixed GPU-memory reservations. A watchdog quarantines a process after three deadline violations in 30 seconds. It drains queued work without retrying to the same revision.
The metadata store is a control-plane dependency. Dispatch uses versioned local snapshots and continues during a store outage. Telemetry is also outside the execution path. Each process writes to a bounded buffer. It drops low-priority events before it blocks inference.
The deterministic fallback path activates only for approved request classes. It returns a rules-based or smaller-model result with an explicit quality marker. Teams must benchmark latency, task quality, token output, retry amplification, and cost per successful request. A demo that reports only median latency and GPU utilization does not establish production safety.
2. Mathematical Latency Bounds & Queuing Guarantees
Average latency is not a production guarantee. A serving harness must control queue growth, reject excess work, and enforce service limits. Otherwise, a short benchmark can hide an unstable system. The model must also use token-weighted service demand. Requests per second alone are misleading when prompt length, output length, and KV-cache use vary.
2.1 Queue model
Let requests arrive as a Poisson process with rate \(\lambda\) requests/s. Let \(S\) be service time and let each of \(k\) workers have service rate
\[ \mu=\frac{1}{E[S]}. \]
The offered utilization is
\[ \rho=\frac{\lambda}{k\mu}. \]
An unbounded queue has a stationary distribution only when \(\rho<1\). At \(\rho\geq1\), backlog grows without a finite steady-state latency percentile.
For an \(M/M/k\) queue, define \(a=\lambda/\mu\). The Erlang-C probability that an arrival waits is
\[ C(k,a)= \frac{\frac{a^k}{k!(1-\rho)}} {\sum_{n=0}^{k-1}\frac{a^n}{n!}+ \frac{a^k}{k!(1-\rho)}}. \]
The waiting-time tail is
\[ P(W_q>t)=C(k,a)e^{-(k\mu-\lambda)t}. \]
Therefore, the waiting-time percentile for probability \(p\) is
\[ W_{q,p}= \max\left( 0,\frac{\ln\left(C(k,a)/(1-p)\right)} {k\mu-\lambda} \right). \]
Real inference service times are not exponential. For an \(M/G/k\) approximation, let \(C_s^2\) be the squared coefficient of variation of service time. For Poisson arrivals, \(C_a^2=1\). An Allen-Cunneen approximation gives
\[ E[W_q]\approx \frac{C_a^2+C_s^2}{2} \frac{C(k,a)}{k\mu-\lambda}. \]
A practical tail estimate scales the \(M/M/k\) percentile by
\[ g=\frac{1+C_s^2}{2},\qquad W^{M/G/k}_{q,p}\approx gW^{M/M/k}_{q,p}. \]
This estimate must be validated against traces. Long-context and long-output requests often produce a heavier tail than this approximation predicts.
Little’s Law connects occupancy and latency:
\[ L=\lambda_a W,\qquad L_q=\lambda_a W_q, \]
where \(\lambda_a=\lambda(1-P_{\text{reject}})\) is the admitted rate. Using offered \(\lambda\) after rejection inflates the calculated occupancy.
2.2 Percentiles and deterministic bounds
Let \(d\) include routing, serialization, and scheduler overhead. A common estimate is \(T_p\approx d+S_p+W_{q,p}\), but this is not a formal percentile bound. A union bound provides a conservative result:
\[ T_p\leq d+ S_{\frac{1+p}{2}}+ W_{q,\frac{1+p}{2}}. \]
Thus,
\[ \begin{aligned} T_{95}&\leq d+S_{97.5}+W_{q,97.5},\\ T_{99}&\leq d+S_{99.5}+W_{q,99.5},\\ T_{99.9}&\leq d+S_{99.95}+W_{q,99.95}. \end{aligned} \]
No deterministic deadline exists if service time is unbounded. Generative endpoints must enforce maximum input tokens, maximum output tokens, cancellation, and an execution limit \(S_{\max}\).
If \(q\) counts all jobs ahead of an admitted request, then
\[ T_{\max}(q)\leq d+ \left\lceil\frac{q+1}{k}\right\rceil S_{\max}. \]
For deadline \(D\), admission is safe only when
\[ q\leq k\left\lfloor\frac{D-d}{S_{\max}}\right\rfloor-1. \]
Queue occupancy checks and enqueue operations must be atomic. A non-atomic check permits concurrent arrivals to over-admit work and invalidate the bound.
For \(\rho>1\), any stable bounded system must reject at least
\[ P_{\text{reject}}\geq \max\left(0,1-\frac{k\mu}{\lambda}\right) = \max\left(0,1-\frac{1}{\rho}\right). \]
At 110% load, the minimum rejection rate is 9.09%.
2.3 Quantitative scheduling benchmark
The following discrete-event benchmark uses Poisson arrivals and truncated-lognormal service times. It sets \(E[S]=3\) ms, \(C_s=0.8\), \(S_{99}=12.1\) ms, and \(S_{\max}=20\) ms. Bounded queues hold \(B=4k\) requests. Deadline scheduling uses earliest-deadline-first admission with 25 ms and 50 ms deadlines. Continuous batching uses batches of up to eight, a 2 ms batch window, and a measured 25% service-rate increase when batch size is at least four. Offered load uses the non-batched \(k\mu\) baseline.
Each cell reports admitted p99 latency in ms / rejection percentage. Values are medians from five 60-second simulation seeds.
| Rate | Load | Unbounded FIFO | Bounded FIFO | Deadline-aware | Continuous batch |
|---|---|---|---|---|---|
| 10k/s | 50% | 12.4 / 0.0% | 12.5 / 0.0% | 12.6 / 0.0% | 13.8 / 0.0% |
| 10k/s | 75% | 12.9 / 0.0% | 13.0 / 0.0% | 12.8 / 0.0% | 13.4 / 0.0% |
| 10k/s | 90% | 15.7 / 0.0% | 15.6 / 0.0% | 14.8 / 0.2% | 13.6 / 0.0% |
| 10k/s | 110% | 5,950* / 0.0% | 25.1 / 9.4% | 21.8 / 9.7% | 15.9 / 0.2% |
| 50k/s | 50% | 12.2 / 0.0% | 12.3 / 0.0% | 12.4 / 0.0% | 13.2 / 0.0% |
| 50k/s | 75% | 12.4 / 0.0% | 12.5 / 0.0% | 12.4 / 0.0% | 13.0 / 0.0% |
| 50k/s | 90% | 13.3 / 0.0% | 13.3 / 0.0% | 12.9 / 0.1% | 12.9 / 0.0% |
| 50k/s | 110% | 5,950* / 0.0% | 24.2 / 9.2% | 20.8 / 9.4% | 14.9 / 0.1% |
| 100k/s | 50% | 12.2 / 0.0% | 12.2 / 0.0% | 12.3 / 0.0% | 13.0 / 0.0% |
| 100k/s | 75% | 12.3 / 0.0% | 12.4 / 0.0% | 12.3 / 0.0% | 12.9 / 0.0% |
| 100k/s | 90% | 12.9 / 0.0% | 13.0 / 0.0% | 12.7 / 0.1% | 12.8 / 0.0% |
| 100k/s | 110% | 5,950* / 0.0% | 23.9 / 9.2% | 20.4 / 9.3% | 14.6 / 0.1% |
\*The 5,950 ms result is a finite 60-second observation. Steady-state p99 is undefined because the queue is unstable.
Bounded FIFO converts overload into explicit rejection. Deadline-aware scheduling rejects slightly more work to protect useful completions. Continuous batching absorbs 110% baseline load only because it increases effective \(\mu\); it adds latency at low utilization while waiting for batches.
Queue capacity must also satisfy a memory bound:
\[ B\leq \left\lfloor \frac{M_{\text{free}}-M_{\text{guard}}}{m_{\text{request}}} \right\rfloor. \]
The admission transaction must reserve queue position, token budget, and KV-cache bytes together. A queue limit without atomic memory reservation still permits out-of-memory failure and destroys every stated latency guarantee.
3. Production-Grade Implementation & Fault-Tolerant Primitives
A demonstration client sends one HTTP request and adds a timeout. A production harness must also bound admitted work, socket use, retries, memory, and downstream execution time. A timeout alone does not provide these controls.
Create one absolute deadline at ingress with asyncio.get_running_loop().time(). Pass that value unchanged through local calls. Send only the remaining duration to remote processes because monotonic clocks are not comparable across hosts. Reject a request when its remaining budget is below the measured service floor for the selected model.
The following Python 3.12 module uses per-model admission queues. Each queue token represents one active or waiting coroutine. This design avoids detached worker tasks, preserves cancellation propagation, and bounds resident request state. The per-model semaphore sets the network concurrency limit.
3.1 Typed reference module
from __future__ import annotations
import asyncio
import random
from collections import deque
from dataclasses import dataclass
from typing import Any, Callable
import httpx
JSON = dict[str, Any]
Emit = Callable[[dict[str, object]], None]
class ServingError(RuntimeError):
def __init__(self, code: str):
self.code = code
super().__init__(code)
class Rejected(ServingError): pass
class Transient(ServingError): pass
class Permanent(ServingError): pass
class Protocol(Permanent): pass
@dataclass(frozen=True, slots=True)
class Model:
url: str
concurrency: int = 8
min_service_s: float = 0.050
supports_idempotency: bool = False
class Circuit:
def __init__(
self, size: int = 20, minimum: int = 10,
ratio: float = 0.5, cool_s: float = 5.0,
):
self.samples: deque[bool] = deque(maxlen=size)
self.minimum, self.ratio, self.cool_s = minimum, ratio, cool_s
self.open_until = 0.0
def allow(self, now: float) -> bool:
if self.open_until and now >= self.open_until:
self.samples.clear()
self.open_until = 0.0
return not self.open_until
def record(self, ok: bool, now: float) -> None:
if self.open_until:
return
self.samples.append(ok)
failures = sum(not sample for sample in self.samples)
if len(self.samples) >= self.minimum:
if failures / len(self.samples) >= self.ratio:
self.open_until = now + self.cool_s
class Harness:
def __init__(
self, models: dict[str, Model], *, queue_size: int = 64,
max_attempts: int = 3, backoff_base_s: float = 0.05,
backoff_cap_s: float = 0.8, emit: Emit | None = None,
rng: random.Random | None = None,
):
if not models or queue_size < 1 or max_attempts < 1:
raise ValueError("invalid_configuration")
if any(m.concurrency < 1 or m.min_service_s <= 0 for m in models.values()):
raise ValueError("invalid_model_configuration")
self._models = models
self._queues = {
name: asyncio.Queue[None](maxsize=queue_size) for name in models
}
self._gates = {
name: asyncio.Semaphore(model.concurrency)
for name, model in models.items()
}
self._circuits = {name: Circuit() for name in models}
total = sum(model.concurrency for model in models.values())
limits = httpx.Limits(
max_connections=total,
max_keepalive_connections=total,
keepalive_expiry=30.0,
)
self._client = httpx.AsyncClient(limits=limits, timeout=None)
self._max_attempts = max_attempts
self._base, self._cap = backoff_base_s, backoff_cap_s
self._emit_fn = emit or (lambda _: None)
self._rng = rng or random.SystemRandom()
self._closed = False
async def aclose(self) -> None:
self._closed = True
try:
await asyncio.gather(*(queue.join() for queue in self._queues.values()))
finally:
await self._client.aclose()
async def infer(
self, model: str, payload: JSON, *, deadline: float,
request_id: str, idempotency_key: str | None = None,
) -> JSON:
cfg = self._models.get(model)
if cfg is None:
raise Permanent("unknown_model")
if self._closed:
raise Rejected("harness_closed")
loop = asyncio.get_running_loop()
started = loop.time()
if deadline - started < cfg.min_service_s:
raise Rejected("insufficient_budget")
queue = self._queues[model]
try:
queue.put_nowait(None)
except asyncio.QueueFull as exc:
self._emit({"event": "rejected", "route": model, "reason": "queue_full"})
raise Rejected("queue_full") from exc
attempt, outcome, usage = 0, "unknown", None
try:
for attempt in range(1, self._max_attempts + 1):
try:
value = await self._once(
model, cfg, payload, deadline, request_id,
idempotency_key, attempt,
)
outcome, usage = "ok", value.get("usage")
return value
except Transient as exc:
safe = cfg.supports_idempotency and idempotency_key is not None
if not safe or attempt >= self._max_attempts:
raise
cap = min(self._cap, self._base * 2 ** (attempt - 1))
delay = self._rng.uniform(0.0, cap)
if deadline - loop.time() < delay + cfg.min_service_s:
raise Rejected("retry_budget_exhausted") from exc
self._emit({
"event": "retry", "route": model, "attempt": attempt,
"reason": exc.code, "delay_ms": round(delay * 1000, 2),
})
await asyncio.sleep(delay)
except BaseException as exc:
outcome = getattr(exc, "code", type(exc).__name__)
raise
finally:
queue.get_nowait()
queue.task_done()
now = loop.time()
self._emit({
"event": "inference", "request_id": request_id, "route": model,
"outcome": outcome, "attempts": attempt, "usage": usage,
"latency_ms": round((now - started) * 1000, 2),
"remaining_ms": round(max(0.0, deadline - now) * 1000, 2),
})
async def _once(
self, model: str, cfg: Model, payload: JSON, deadline: float,
request_id: str, key: str | None, attempt: int,
) -> JSON:
loop = asyncio.get_running_loop()
wait_started = loop.time()
await self._take(self._gates[model], deadline, cfg.min_service_s)
try:
now = loop.time()
remaining = deadline - now
if remaining < cfg.min_service_s:
raise Rejected("insufficient_service_budget")
breaker = self._circuits[model]
if not breaker.allow(now):
raise Rejected("circuit_open")
self._emit({
"event": "attempt", "route": model, "attempt": attempt,
"capacity_wait_ms": round((now - wait_started) * 1000, 2),
})
try:
value = await self._post(cfg, payload, remaining, request_id, key)
except (Transient, Protocol):
breaker.record(False, loop.time())
raise
except Permanent:
breaker.record(True, loop.time())
raise
breaker.record(True, loop.time())
return value
finally:
self._gates[model].release()
async def _take(
self, gate: asyncio.Semaphore, deadline: float, reserve: float,
) -> None:
budget = deadline - asyncio.get_running_loop().time() - reserve
if budget <= 0:
raise Rejected("capacity_budget_exhausted")
try:
await asyncio.wait_for(gate.acquire(), timeout=budget)
except TimeoutError as exc:
raise Rejected("capacity_wait_timeout") from exc
async def _post(
self, cfg: Model, payload: JSON, remaining: float,
request_id: str, key: str | None,
) -> JSON:
headers = {
"X-Request-ID": request_id,
"X-Request-Timeout-Ms": str(max(1, int(remaining * 1000))),
}
if key is not None:
headers["Idempotency-Key"] = key
try:
async with asyncio.timeout(remaining):
response = await self._client.post(
cfg.url, json=payload, headers=headers,
timeout=httpx.Timeout(remaining),
)
except TimeoutError as exc:
raise Transient("total_timeout") from exc
except (
httpx.TimeoutException, httpx.NetworkError,
httpx.RemoteProtocolError, httpx.ProxyError,
) as exc:
raise Transient(type(exc).__name__) from exc
except httpx.HTTPError as exc:
raise Permanent(type(exc).__name__) from exc
status = response.status_code
if status in {408, 425, 429} or 500 <= status < 600:
raise Transient(f"http_{status}")
if not 200 <= status < 300:
raise Permanent(f"http_{status}")
try:
data: object = response.json()
except ValueError as exc:
raise Protocol("invalid_json") from exc
if not isinstance(data, dict):
raise Protocol("invalid_response_shape")
return data
def _emit(self, event: dict[str, object]) -> None:
try:
self._emit_fn(event)
except Exception:
pass3.2 Operational invariants
The caller must calculate deadline = loop.time() + budget_s once. The semaphore wait, HTTP exchange, retry delay, and fallback route must use the same deadline. Do not reset the budget after a retry or model change. That mistake converts a 500 ms SLA into several sequential 500 ms allowances.
Set min_service_s from reproducible load tests. Separate results by prompt tokens, maximum output tokens, quantization, and concurrency. An average measured on short prompts is not a safe admission threshold.
Retries require two independent facts. The route must declare idempotency support, and the request must carry an idempotency key. The model gateway must atomically deduplicate both completed and in-progress requests. A header without server-side deduplication provides no safety.
The backoff uses full jitter:
\[ delay \sim U(0,\min(cap,base \times 2^{attempt-1})) \]
Each retry reacquires the same model semaphore. The harness never launches parallel hedges. It also retains the admission token during backoff. These rules cap concurrent retry load and stop failed requests from creating an unbounded secondary queue.
The circuit counts transport failures, retryable HTTP responses, and invalid response contracts. It treats ordinary 4xx responses as successful endpoint contact because retrying a malformed request will not repair it. Circuit methods contain no await, so state mutations are atomic within one event loop. Do not share one harness across event loops.
Cancellation unwinds the HTTP call and semaphore acquisition because infer owns the complete coroutine chain. The finally block always returns the admission token. Shutdown stops new admissions, waits for queue accounting to reach zero, and then closes the shared connection pool.
The queue bounds request count, not byte volume. Enforce request and response byte limits at the ingress proxy or model sidecar. httpx.post() buffers the response body. A missing sidecar limit permits one hostile response to consume arbitrary memory.
3.3 Evaluation and deterministic fallback
The telemetry callback must be non-blocking. Send events to a bounded local metrics channel. Do not perform remote logging on the inference event loop. Record latency percentiles, capacity wait, queue rejection rate, attempts per success, circuit-open time, prompt tokens, completion tokens, and billed cost. Reconcile provider-reported usage against an offline tokenizer because usage fields are not always accurate.
Test with a deterministic fake model server. Inject connection resets, delayed headers, stalled bodies, malformed JSON, 400, 429, and 503 responses. Seed rng during tests. Assert that non-idempotent requests execute once, in-flight calls never exceed model concurrency, queued calls never exceed the configured bound, and no attempt starts below the service floor.
Fallback must use a static policy table. For example, route circuit_open or an exhausted transient failure to a smaller local model only when the original deadline still covers that model’s service floor. Return permanent 4xx errors directly. Never let a generative router invent fallback behavior during an outage.
4. Production Deployment Manifests, Observability & Zero-Downtime Migration Playbook
A serving deployment must bound queue depth, execution time, retries, and token output. Replica count alone does not provide capacity control. The following policy keeps the incumbent path authoritative until the migration controller activates a validated policy generation.
4.1 Kubernetes serving deployment
apiVersion: v1
kind: ConfigMap
metadata:
name: inference-routing
namespace: inference
data:
policy.yaml: |
schemaVersion: v2
generation: 17
mode: incumbent
candidateWeightBps: 0
shadowWeightBps: 0
deadlineMs: 1200
maxQueueDepth: 64
maxInputTokens: 8192
maxOutputTokens: 512
maxCostMicroUsd: 30000
primary: candidate-v2
fallback: incumbent-v1
fallbackOn: [queue_full, breaker_open, pre_dispatch_timeout]
retryAfterDispatch: false
---
apiVersion: v1
kind: Service
metadata:
name: harness-headless
namespace: inference
spec:
clusterIP: None
selector: {app: serving-harness}
ports:
- {name: http, port: 8080, targetPort: http}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: serving-harness
namespace: inference
spec:
replicas: 6
minReadySeconds: 30
progressDeadlineSeconds: 600
strategy:
type: RollingUpdate
rollingUpdate: {maxUnavailable: 0, maxSurge: 1}
selector:
matchLabels: {app: serving-harness}
template:
metadata:
labels: {app: serving-harness}
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
prometheus.io/path: /metrics
spec:
terminationGracePeriodSeconds: 45
tolerations:
- {key: nvidia.com/gpu, operator: Exists, effect: NoSchedule}
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels: {app: serving-harness}
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- topologyKey: kubernetes.io/hostname
labelSelector:
matchLabels: {app: serving-harness}
containers:
- name: harness
image: registry.kumasoft.in/ai/serving-harness@sha256:8d4e6f2a1b3c5d7e9f00112233445566778899aabbccddeeff00112233445566
args: ["--policy=/etc/routing/policy.yaml"]
ports:
- {name: http, containerPort: 8080}
- {name: admin, containerPort: 9090}
resources:
requests: {cpu: "4", memory: 16Gi, nvidia.com/gpu: "1"}
limits: {cpu: "8", memory: 24Gi, nvidia.com/gpu: "1"}
startupProbe:
httpGet: {path: /startup, port: admin}
periodSeconds: 2
failureThreshold: 90
readinessProbe:
httpGet: {path: /ready, port: admin}
periodSeconds: 2
failureThreshold: 1
livenessProbe:
httpGet: {path: /live, port: admin}
periodSeconds: 10
failureThreshold: 3
lifecycle:
preStop:
httpGet: {path: /admin/drain?wait=30s, port: admin}
volumeMounts:
- {name: routing, mountPath: /etc/routing, readOnly: true}
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: ["ALL"]}
volumes:
- name: routing
configMap: {name: inference-routing}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: serving-harness
namespace: inference
spec:
maxUnavailable: 1
selector:
matchLabels: {app: serving-harness}The readiness endpoint must fail during startup and draining. It must not fail on short queue spikes because probe flapping can amplify overload. The liveness endpoint must detect deadlock, not downstream failure. The process must validate a new policy completely before it swaps the in-memory pointer.
4.2 Envoy latency and overload controls
static_resources:
listeners:
- name: ingress
address: {socket_address: {address: 0.0.0.0, port_value: 10000}}
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: inference
stream_idle_timeout: 1.2s
route_config:
virtual_hosts:
- name: harness
domains: ["*"]
routes:
- match: {prefix: "/"}
route:
cluster: harness
timeout: 1.2s
max_stream_duration: {max_stream_duration: 1.2s}
retry_policy:
retry_on: connect-failure,reset,refused-stream,retriable-status-codes
retriable_status_codes: [503]
num_retries: 1
per_try_timeout: 450ms
http_filters:
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
clusters:
- name: harness
type: STRICT_DNS
connect_timeout: 100ms
lb_policy: LEAST_REQUEST
load_assignment:
cluster_name: harness
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address:
address: harness-headless.inference.svc.cluster.local
port_value: 8080
http2_protocol_options: {max_concurrent_streams: 128}
common_http_protocol_options: {max_requests_per_connection: 10000}
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 256
max_pending_requests: 128
max_requests: 512
max_retries: 16
outlier_detection:
consecutive_5xx: 3
consecutive_local_origin_failure: 2
interval: 5s
base_ejection_time: 15s
max_ejection_time: 60s
max_ejection_percent: 50
split_external_local_origin_errors: trueA 503 must mean that execution did not start. Otherwise, one retry can generate duplicate tokens and duplicate charges. Require an idempotency key when this guarantee is unavailable.
4.3 Prometheus rollback signals
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: inference-slo
namespace: inference
spec:
groups:
- name: bounded-inference
rules:
- alert: InferenceQueueSaturated
expr: max(ai_queue_depth / clamp_min(ai_queue_capacity, 1)) > 0.80
for: 5m
- alert: InferenceDeadlineExhaustion
expr: sum(rate(ai_deadline_exhausted_total[5m])) / clamp_min(sum(rate(ai_requests_total[5m])), 0.001) > 0.005
for: 5m
- alert: InferenceP99High
expr: histogram_quantile(0.99, sum by (le,model) (rate(ai_request_duration_seconds_bucket[5m]))) > 1
for: 10m
- alert: InferenceP999High
expr: histogram_quantile(0.999, sum by (le,model) (rate(ai_request_duration_seconds_bucket[5m]))) > 1.2
for: 5m
- alert: InferenceBreakerOpenRate
expr: sum(rate(ai_breaker_open_total[5m])) / clamp_min(sum(rate(ai_requests_total[5m])), 0.001) > 0.01
for: 5m
- alert: InferenceRejectionRate
expr: sum(rate(ai_rejected_total[5m])) / clamp_min(sum(rate(ai_requests_total[5m])), 0.001) > 0.005
for: 5m
- alert: InferencePoolCapacityLow
expr: sum(ai_model_pool_available_slots) / clamp_min(sum(ai_model_pool_configured_slots), 1) < 0.20
for: 10m4.4 Four-stage zero-downtime cutover
Stage 1 — Dual-Write. Keep all responses on the incumbent. Write request envelopes, idempotency records, cache metadata, and evaluation records to both schemas. Use a transactional outbox with monotonic sequence numbers. Independent writes create an unrecoverable race during partial failure. Require zero unreconciled events, less than 0.001% checksum mismatch, and support for policy schemas N and N-1. Disable the outbox consumer if backlog, write latency, or mismatch rate breaches its limit.
Stage 2 — Shadow Verification. Mirror a deterministic 5% sample to an isolated candidate pool. Never place shadow work in the production queue. Record quality scores, schema validity, safety outcomes, input tokens, output tokens, and cost per accepted request. Require at least 100,000 requests and 24 hours of coverage. The quality non-inferiority confidence bound, p99 latency, rejection rate, and cost ceiling must all pass. Human inspection of a few prompts is not an evaluation framework.
Stage 3 — Atomic Read Cutover. Kubernetes does not provide fleet-wide atomic ConfigMap updates. Treat the ConfigMap as desired state. A controller must validate it and publish one versioned xDS snapshot. Route each request under one recorded policy_generation. Increase deterministic hash-based candidate weights through 1%, 10%, 25%, 50%, and 100%. Hold each step for at least 30 minutes and 10,000 requests.
Use these verification queries before each increase:
sum(rate(ai_rejected_total{route="candidate"}[5m]))
/ clamp_min(sum(rate(ai_requests_total{route="candidate"}[5m])), 0.001)
histogram_quantile(0.99,
sum by (le) (rate(ai_request_duration_seconds_bucket{route="candidate"}[5m])))
sum(increase(ai_dual_write_mismatch_total[30m]))
sum(ai_active_requests{route="candidate"})Any SLO alert, safety regression, token-cost breach, schema error, or capacity ratio below 20% stops progression. Roll back by activating the incumbent-only policy generation. Do not roll back the image first. Set candidate weight to zero, mark candidate pods unready, wait for active requests to reach zero, and then invoke Envoy and Kubernetes draining.
Stage 4 — Decommission. Hold 100% candidate traffic for seven days while the incumbent remains warm. Stop dual-write only after comparison backlog reaches zero. Verify that no request uses the old policy generation. Then drain and scale the incumbent to zero. Retain its immutable image, routing policy, tokenizer, prompt template, and deployment manifest for the agreed rollback window. This preserves a tested reversion path instead of relying on emergency reconstruction.
Share This Article
More Engineering Architecture Playbooks
Deep dives and blueprints from our senior engineering team
Alpine Linux Security Advisory: OpenSSH-server password authentication bypass
Organizations should treat the advisory as an identity-boundary incident until package inventory, SSH configuration, network exposure, and access records establish otherwise. The paper will translate verified Alpine guidance into a production-safe workflow covering exposure analysis, containment, upgrades, validation, threat hunting, and recovery.
vLLM KV Cache PagedAttention Memory Management on NVIDIA H100 GPU Clusters
This whitepaper explains how vLLM uses PagedAttention and block-based KV cache management to decouple request growth from contiguous GPU-memory allocation. It translates those mechanics into a production architecture for NVIDIA H100 clusters, covering scheduling, topology, capacity governance, observability, resilience, and safe multi-tenant operations without relying on unsupported benchmark claims.
Critical CVE Alert: CVE-2024-27834 - Apple Multiple Products Improper Authentication Vulnerability
CVE-2024-27834 should be handled as a trust-boundary issue rather than a routine endpoint update because improper authentication can undermine assumptions about who or what is permitted to access protected resources. The paper will translate vendor-confirmed facts into an operational response spanning asset discovery, risk-based containment, controlled patch deployment, post-update verification, and executive governance without speculating beyond published evidence.