Skip to content
Mementropy
SolutionshungersyncNotebookExecuted example

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.

By Ryan HammangUpdated

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.

An HTTP model inference service is modeled as an M/M/kM/M/k queueing system:

  • Inbound requests arrive via a Poisson process with parameter λ(t)\lambda(t).
  • Service time SS is distributed exponentially with parameter μ\mu.
  • kk identical worker threads process requests concurrently.

Traffic intensity is defined as ρ=λkμ\rho = \frac{\lambda}{k\mu}. If ρ≥1\rho \ge 1, queue depth Lq(t)→∞L_q(t) \to \infty. The 99th percentile response latency p99p_{99} is:

p99=inf⁡{t≥0:P(T≤t)≥0.99}p_{99} = \inf \left\{ t \ge 0 : P(T \le t) \ge 0.99 \right\}

The Kubernetes Horizontal Pod Autoscaler (HPA) computes desired replicas R∗R^*:

R∗=⌈Rcurrent⋅McurrentMtarget⌉R^* = \left\lceil R_{\text{current}} \cdot \frac{M_{\text{current}}}{M_{\text{target}}} \right\rceil

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 math
import sys
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Markdown, JSON
SEED = 42
np.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 N=5,000N=5,000 incoming HTTP inference requests during a simulated 45-minute ground stop. Arrival rate λ(t)\lambda(t) surges from baseline λ0=10 req/s\lambda_0 = 10\text{ req/s} to peak λsurge=80 req/s\lambda_{\text{surge}} = 80\text{ req/s}.

N_REQUESTS = 5000
# Surge profile: baseline -> 8x surge -> nominal
t = 0.0
arrival_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:

  1. Synchronous single-worker server (k=1k=1, simulating uncontained Flask).
  2. Asynchronous multi-worker server (k=4k=4, simulating containerized Uvicorn/Gunicorn).

Review simulate_queue. Verify that completion timestamps respect causal sequencing tstart≥tarrivalt_{\text{start}} \ge t_{\text{arrival}}.

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']}

We compute p50,p95,p99p_{50}, p_{95}, p_{99} 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}
0 50 100 150 200 250 300 Simulation Time (s) 0 200 400 600 800 1000 1200 1400 End-to-End Latency (ms) Tail Latency under Disruption Traffic Burst Synchronous Worker (k=1) Asynchronous Container (k=4) SLO Bound (100ms)

Operational Scaling: Kubernetes HPA Algorithm

Section titled “Operational Scaling: Kubernetes HPA Algorithm”

We formulate the HPA decision rule with target CPU utilization τcpu=70%\tau_{\text{cpu}} = 70\%. When traffic exceeds service capacity, new pods are provisioned up to Rmax⁡=10R_{\max} = 10.

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 response
scaled_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

Verify that requests exceeding maximum timeout (T>2,000msT > 2,000\text{ms}) trigger an explicit circuit-breaker rejection.

TIMEOUT_THRESHOLD = 2.0
timeouts = 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
  1. Cloud Run: Deploy container with --concurrency 80 and --min-instances 2.
  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
}