Containerized Inference Runtimes, Queueing Dynamics, and Horizontal Scaling
Model a containerized inference service as an M/M/k queue to study tail latency under bursty traffic and size its autoscaling.
Part III: The Flight Disruption Binary Classifier Series
Authoring standard: Site Reliability Engineering (Beyer et al.) & Queueing Systems (Kleinrock)
Setting: Hartsfield-Jackson Atlanta International Airport (ATL)
Case linkage: HS-OPS-03 · Joey Hutto (On-Call Fleet & Dispatch Ops) & SRE agent
Operational Objective: Analyze microservice inference tail latency distributions under burst Poisson traffic and formulate the horizontal pod autoscaling control loop.
Mathematical Formulation
Section titled “Mathematical Formulation”An HTTP model inference service is modeled as an queueing system:
- Inbound requests arrive via a Poisson process with parameter .
- Service time is distributed exponentially with parameter .
- identical worker threads process requests concurrently.
Traffic intensity is defined as . If , queue depth . The 99th percentile response latency is:
The Kubernetes Horizontal Pod Autoscaler (HPA) computes desired replicas :
Prerequisites and support
Section titled “Prerequisites and support”The saved environment reports Python 3.12.12. For the public download, use an isolated Python environment with JupyterLab and NumPy, Matplotlib, IPython. These are package prerequisites, not a locked or newly tested environment. The Python examples generate their own teaching data and do not require cloud credentials or a pretrained model.
The public download omits the site-only mementropy.mplstyle setup cell; use Matplotlib’s default style. No style file or environment lock is bundled. The cloud, SQL and deployment discussion is explanatory material, not evidence that a service was deployed by this notebook. If a rerun differs, record package versions and compare to the saved outputs rather than treating them as a guaranteed result.
Evidence: these are saved outputs from an earlier execution, not rerun for the 2026-10-29 editorial update. Rendering displays saved cells; it does not execute them. The public download is not a locked environment or a production validation.
import mathimport sysimport numpy as npimport matplotlib.pyplot as pltfrom IPython.display import display, Markdown, JSON
SEED = 42np.random.seed(SEED)print({'python': sys.version.split()[0], 'seed': SEED, 'module': '03-containerized-serving'}){'python': '3.12.12', 'seed': 42, 'module': '03-containerized-serving'}
Queueing Dynamics Simulation under Burst Arrival
Section titled “Queueing Dynamics Simulation under Burst Arrival”We simulate incoming HTTP inference requests during a simulated 45-minute ground stop. Arrival rate surges from baseline to peak .
N_REQUESTS = 5000# Surge profile: baseline -> 8x surge -> nominalt = 0.0arrival_times = []for i in range(N_REQUESTS): # Dynamic arrival rate lambda(t) current_lambda = 80.0 if (1500 <= i <= 3500) else 10.0 inter_arrival = np.random.exponential(scale=1.0 / current_lambda) t += inter_arrival arrival_times.append(t)
arrival_times = np.array(arrival_times)# Execution service time: mean 20ms (mu = 50 req/s per worker thread)service_times = np.random.gamma(shape=4.0, scale=0.005, size=N_REQUESTS)
print({ 'simulated_requests': N_REQUESTS, 'total_duration_seconds': round(arrival_times[-1], 2), 'mean_service_time_ms': round(float(np.mean(service_times) * 1000), 2)}){'simulated_requests': 5000, 'total_duration_seconds': np.float64(321.52), 'mean_service_time_ms': 20.0}
Implementation: Multi-Server Queue Simulator
Section titled “Implementation: Multi-Server Queue Simulator”We simulate request scheduling across worker pools:
- Synchronous single-worker server (, simulating uncontained Flask).
- Asynchronous multi-worker server (, simulating containerized Uvicorn/Gunicorn).
Student Exercise (Stub)
Section titled “Student Exercise (Stub)”Review simulate_queue. Verify that completion timestamps respect causal sequencing .
def simulate_queue(arrival_times, service_times, k_servers=1): """Simulate multi-server FIFO queueing system.""" n = len(arrival_times) server_free_time = np.zeros(k_servers) latencies = np.zeros(n)
for i in range(n): arr = arrival_times[i] dur = service_times[i]
# Earliest available server earliest_idx = np.argmin(server_free_time) start_time = max(arr, server_free_time[earliest_idx]) finish_time = start_time + dur
server_free_time[earliest_idx] = finish_time latencies[i] = finish_time - arr
return latencies
latencies_sync = simulate_queue(arrival_times, service_times, k_servers=1)latencies_async = simulate_queue(arrival_times, service_times, k_servers=4)
print({'simulated_modes': ['single_worker_k1', 'multi_worker_k4']}){'simulated_modes': ['single_worker_k1', 'multi_worker_k4']}
Latency Percentiles and Tail Distribution
Section titled “Latency Percentiles and Tail Distribution”We compute latency metrics across both architectures.
def get_percentiles(lat): return { 'p50': float(np.percentile(lat, 50) * 1000), 'p95': float(np.percentile(lat, 95) * 1000), 'p99': float(np.percentile(lat, 99) * 1000), 'max': float(np.max(lat) * 1000) }
p_sync = get_percentiles(latencies_sync)p_async = get_percentiles(latencies_async)
print("Synchronous (k=1) Latencies (ms):", {k: round(v, 1) for k, v in p_sync.items()})print("Asynchronous (k=4) Latencies (ms):", {k: round(v, 1) for k, v in p_async.items()})
fig, ax = plt.subplots(figsize=(10, 4))ax.plot(arrival_times, latencies_sync * 1000, label='Synchronous Worker (k=1)', color='#cf222e', lw=1.2)ax.plot(arrival_times, latencies_async * 1000, label='Asynchronous Container (k=4)', color='#1a7f64', lw=1.5)ax.axhline(100.0, color='#171817', linestyle='--', label='SLO Bound (100ms)')ax.set(xlabel='Simulation Time (s)', ylabel='End-to-End Latency (ms)', title='Tail Latency under Disruption Traffic Burst')ax.set_ylim(0, 1500)ax.legend(); ax.grid(True, alpha=0.3)plt.tight_layout(); plt.show()Synchronous (k=1) Latencies (ms): {'p50': 39.2, 'p95': 14111.0, 'p99': 15350.3, 'max': 15758.2}
Asynchronous (k=4) Latencies (ms): {'p50': 18.5, 'p95': 38.6, 'p99': 49.5, 'max': 77.1}
Operational Scaling: Kubernetes HPA Algorithm
Section titled “Operational Scaling: Kubernetes HPA Algorithm”We formulate the HPA decision rule with target CPU utilization . When traffic exceeds service capacity, new pods are provisioned up to .
def compute_hpa_replicas(current_replicas, current_metric, target_metric=70.0, max_replicas=10): ratio = current_metric / target_metric desired = math.ceil(current_replicas * ratio) return max(1, min(desired, max_replicas))
# Simulate dynamic autoscaling responsescaled_replicas = compute_hpa_replicas(current_replicas=2, current_metric=180.0, target_metric=70.0)print(f"HPA Action: Scale from 2 to {scaled_replicas} pods to preserve p99 < 100ms SLO")HPA Action: Scale from 2 to 6 pods to preserve p99 < 100ms SLO
Method Invariant and Failure Probe
Section titled “Method Invariant and Failure Probe”Verify that requests exceeding maximum timeout () trigger an explicit circuit-breaker rejection.
TIMEOUT_THRESHOLD = 2.0timeouts = np.sum(latencies_sync > TIMEOUT_THRESHOLD)
try: if timeouts > 0: raise TimeoutError(f"Queue saturation: {timeouts} requests exceeded {TIMEOUT_THRESHOLD}s threshold")except TimeoutError as err: print("EXPECTED REJECTION:", err)EXPECTED REJECTION: Queue saturation: 1935 requests exceeded 2.0s threshold
Google Cloud Platform Transition
Section titled “Google Cloud Platform Transition”- Cloud Run: Deploy container with
--concurrency 80and--min-instances 2. - GKE Autopilot: Deploy horizontal pod autoscaler with CPU/concurrency targets and Pod disruption budgets.
display(JSON({ 'total_requests': N_REQUESTS, 'sync_p99_ms': round(p_sync['p99'], 1), 'async_p99_ms': round(p_async['p99'], 1), 'hpa_scaled_pods': scaled_replicas, 'status': 'VERIFIED_SCALING'})){
"async_p99_ms": 49.5,
"hpa_scaled_pods": 6,
"status": "VERIFIED_SCALING",
"sync_p99_ms": 15350.3,
"total_requests": 5000
}