Low-Latency Multi-Tenant Text Classification Service
Easy · ML System Design · Software Engineer · Technical Screen
Prompt
Architect a high-availability, synchronous HTTP service that classifies caller-supplied text snippets into fixed label taxonomies—such as abuse moderation, customer-support topic routing, or sentiment polarity—and returns predicted labels and confidence scores inside the same HTTP round trip.
For example, a caller might send a batch of live chat messages (item_1, item_2) to a moderation endpoint pinned to "stable" while revisions v2.3 and v2.4 are both active in the cluster.
Your design must satisfy these functional and operational guarantees:
- Concurrent model revisions: Host multiple immutable model versions side by side (for example,
v2.3andv2.4) alongside movable aliases so callers can either pin an exact artifact or adopt safe upgrades seamlessly. - Multi-tenant authentication and quotas: Authenticate every caller credential and enforce per-tenant throughput limits cleanly at ingress.
- Synchronous response SLA: Compute and return classification outputs directly within the active HTTP request under tight tail-latency budgets, without falling back to asynchronous job polling.
- Overload containment: Keep latency bounded during sudden traffic spikes by shedding excess work cleanly rather than letting deep queues trigger cascading timeouts.
- Warm rollouts and sub-second rollbacks: Ensure newly deployed model weights finish loading and warming up before receiving live requests, and allow operators to revert traffic to a prior version within seconds.
- Privacy-safe telemetry and drift tracking: Monitor serving latency, error rates, and live prediction drift while guaranteeing that sensitive personal data inside caller text never enters logs or traces.
Scope & Expectations
- REST API specification: Endpoint routes, request/response schemas, batching rules, rate-limit metadata, and distinct status codes for tenant throttling versus cluster saturation.
- Serving topology: How load balancers, stateless API gateways, dynamic configuration stores, GPU inference pools, and immutable model storage fit together.
- Version routing and release safety: Pre-warming GPU workers, progressive canary traffic splitting, and instant rollback mechanics.
- Fault tolerance and overload defense: Handling node crashes, slow replicas, and GPU exhaustion without risking cluster collapse or PII exposure.
Step-by-step walkthrough
Clarify requirements and ML framing
We are designing a hosted machine-learning classification API: a customer's server sends one or more pieces of text over HTTPS, and our service returns the predicted category inside that same HTTP response. That is what synchronous means here—the caller keeps the connection open and waits for the answer rather than receiving a job ID and polling later.
Because many independent customer organizations share the same fleet of servers and GPUs, this is a multi-tenant system. The hardest parts are operational rather than model architecture: protecting scarce GPUs when traffic spikes, rolling out new model versions without dropping or slowing live requests, and monitoring model quality without logging private customer text.
Functional requirements
- Tasks and output:
POST /v1/classifyaccepts a task name—sentiment(3 labels),toxicity(2 labels), ortopic(~30 labels)—and 1 to 16 text strings. For each text, it returns the top label and a calibrated probability for every label in that task. - Model versioning: Models have immutable versions such as
v2.3andv2.4. A client can pin an exact version ("version": "v2.3") for reproducibility or use a moving alias ("stable", the default) to receive safe upgrades automatically. - Tenant auth and throttling: Every request carries a tenant API key and is rate-limited per tenant according to that tenant's subscription tier.
Non-functional requirements
- Latency: Server-side p50 (median) around 25 ms and p99 (the latency that 99 out of 100 requests beat) under 100 ms for texts up to 512 tokens.
- Availability: 99.95% uptime, which leaves only about 22 minutes of unplanned downtime per month (
0.0005 × 43,200 minutes). - Bounded overload: When incoming traffic exceeds cluster capacity, the system must continue serving up to its capacity within the 100 ms budget and immediately reject excess requests—never queue everything until every caller times out.
- Warm deployments and instant rollbacks: A new model version receives live traffic only after its weights are in GPU memory and warmed up; rolling back to the previous version takes seconds.
- Privacy: Input texts may contain PII (Personally Identifiable Information, such as names, emails, or phone numbers). Raw text is never stored or logged by default.
ML problem framing and labels. A model version is a strict contract bundling three pieces together: the tokenizer (which splits raw text into integer token IDs), the neural network weights, and the ordered label list. Changing the label list is a breaking API change and requires a new major version (
v3.0). Because clients rarely tell us whether a live prediction was right, online ground-truth labels are scarce; we collect evaluation labels from a small human-reviewed sample of tenants who explicitly opt in, plus an optional/v1/feedbackendpoint.- Tasks and output:
Back-of-the-envelope numbers and capacity math
Before choosing components, we estimate traffic, GPU count, latency budget, and log volume to see where the real bottlenecks live.
Traffic 2,000 active tenants Average load: 5,000 texts/s total Peak load: 20,000 texts/s total - toxicity (60%): 12,000 texts/s - sentiment (30%): 6,000 texts/s - topic (10%): 2,000 texts/s Average text: ~400 characters (~100 tokens); hard cap = 512 tokens Peak network ingress: 20,000 texts/s x ~1 KB (text + JSON/HTTP) = ~20 MB/s GPU capacity (planning figures; benchmark on target GPU before launch) Model size: ~110M-parameter transformer encoder (BERT-base scale) Half-precision (fp16, 2 bytes/param) weights: ~220 MB in GPU memory Throughput: 1 batch of 32 texts (~128 tokens) runs in ~20 ms -> 1,600 texts/s Use conservative planning rate = 1,500 texts/s per GPU at 100% load Minimum GPUs at 100% load vs. 3-zone production fleet (~60% target load): - toxicity: 12,000 / 1,500 = 8.0 GPUs -> 5 GPUs/zone x 3 zones = 15 GPUs (53% busy) - sentiment: 6,000 / 1,500 = 4.0 GPUs -> 3 GPUs/zone x 3 zones = 9 GPUs (44% busy) - topic: 2,000 / 1,500 = 1.33 GPUs -> 1 GPU/zone x 3 zones = 3 GPUs (44% busy) Total steady-state fleet = 27 GPUs (+ temporary extra pool during version rollouts) Server-side p99 latency budget (100 ms total) L7 load balancer + TLS + ingress auth & rate limit 8 ms Stateless inference API + internal gRPC hop 7 ms Model-server batching / queue wait <= 25 ms GPU forward pass (including 512-token bucket) <= 35 ms Safety margin 25 ms Observability volume (metadata only, zero raw text) ~400 bytes per classified text: Average (5,000/s): 2 MB/s -> ~173 GB/day Sustained peak (20,000/s): 8 MB/s -> ~691 GB/dayThree design lessons jump right out of these numbers:
- GPUs are the bottleneck and scale slowly. Spinning up a new GPU node, pulling container images, loading weights, and warming CUDA kernels takes minutes. Overload protection must sit in front of the GPUs and keep GPU queues tiny.
- Symmetric 3-zone sizing buys instant failover. Spreading replicas evenly across three Availability Zones (isolated data centers inside one cloud region) means losing an entire zone leaves 10 toxicity GPUs (
8 / 10 = 80%busy), 6 sentiment GPUs (4 / 6 = 67%busy), and 2 topic GPUs (1.33 / 2 = 67%busy). Every pool stays safely below saturation without waiting for autoscaling. - Logs are huge even without raw text. At ~173 GB/day average, structured success logs should be sampled or pre-aggregated into metrics, and omitting raw text saves both storage cost and privacy risk.
API contract
A clean synchronous contract gives callers predictable error codes, rate-limit visibility, and version transparency.
POST /v1/classify Authorization: Bearer <api_key> X-Request-Timeout-Ms: 250 optional client deadline in milliseconds { "task": "toxicity", "version": "stable", optional: exact "v2.4" or alias "stable" "inputs": [ { "id": "item_1", "text": "order arrived two days early, thank you!" }, { "id": "item_2", "text": "..." } 1 to 16 items per request ], "options": { "return_all_scores": true, "truncation": "head_tail" "head" (default) or "head_tail" } } 200 OK RateLimit-Limit: 200 RateLimit-Remaining: 142 RateLimit-Reset: 1 { "task": "toxicity", "version": "v2.4", concrete version that actually ran "request_id": "req_4d9b1e", "results": [ { "id": "item_1", "label": "non_toxic", "score": 0.99, "scores": { "non_toxic": 0.99, "toxic": 0.01 }, "truncated": false }, { "id": "item_2", "label": "toxic", "score": 0.91, "scores": { "non_toxic": 0.09, "toxic": 0.91 }, "truncated": true } ] } Error format: { "error": { "code": "...", "message": "...", "retryable": true } } 400 invalid_request malformed JSON, >16 inputs, or batch exceeds tenant burst size 401 unauthenticated missing or revoked API key 403 task_not_enabled tenant plan does not include this task 404 unknown_version requested model version does not exist 410 version_retired pinned version passed its sunset date 413 payload_too_large request body exceeds byte limit (e.g., 256 KB) 429 rate_limited tenant exceeded its own quota (includes Retry-After: <seconds>) 503 overloaded shared service is shedding load (includes Retry-After: 1) 504 deadline_exceeded remaining X-Request-Timeout-Ms cannot fit inference Supporting endpoints: GET /v1/tasks list tasks, label sets, versions, sunset dates POST /v1/feedback { "request_id": "req_4d9b1e", "id": "item_2", "true_label": "non_toxic" }Key contract decisions:
- Always echo the concrete
version. When"stable"points tov2.4, returning"version": "v2.4"lets a customer debug sudden score changes and pinv2.3if needed. - Separate
429from503.429tells the caller "you used up your own plan's rate limit—pace yourself."503tells the caller "our cluster is temporarily full—not your fault." Both includeRetry-Afterso clients back off cleanly instead of hammering the API. - Charge quota per text, not per HTTP call. Otherwise a caller packing 16 texts into one request consumes 16x the GPU work for the price of 1 request.
- No idempotency key is required. Classification is a pure read with no database writes or billing side effects on failed calls, so retrying a timed-out call is naturally safe.
- Always echo the concrete
Data model and high-level architecture
We separate control-plane metadata (models, routing rules, tenants) from the fast request path so no database query sits on the per-request critical path.
Model Registry (PostgreSQL) tasks: task PK, label_set_version, labels[] model_versions: (task, version) PK, artifact_uri, sha256, gpu_memory_mb, max_tokens, offline_metrics jsonb, status (registered | validated | serving | deprecated | retired) Artifact Store (S3 / GCS, immutable — versions are never overwritten) s3://models/toxicity/v2.4/ model.onnx (or TensorRT plan), tokenizer.json, labels.json, golden_outputs.jsonl, manifest.json (SHA-256 hashes) Dynamic Routing Config (etcd or Consul, watched in memory by API pods) /routing/toxicity/aliases {"stable": "v2.3", "canary": "v2.4"} /routing/toxicity/split {"v2.3": 95, "v2.4": 5} /routing/toxicity/overrides/t_42 {"stable": "v2.4"} /routing/toxicity/pools {"v2.3": "tox-v23.svc:8001", "v2.4": "tox-v24.svc:8001"} Tenant & Rate-Limit Stores PostgreSQL (cached 60 s in gateway memory): tenants(tenant_id, plan_tier, rate_texts_per_sec, burst_texts, enabled_tasks) api_keys(key_id, tenant_id, key_sha256, revoked_at) Redis Cluster (sharded by tenant_id): bucket:{tenant_id} -> {tokens, last_refill_ms}High-level architecture
Client servers (HTTPS) | v +------------------------------------+ | Regional L7 Load Balancer (TLS) | +------------------------------------+ | v +------------------------------------+ +----------------------+ | Ingress Gateway (CPU pods) |<---->| Local key cache (60s)| | - API key auth | | + Redis token buckets| | - Per-tenant token bucket -> 429 | +----------------------+ +------------------------------------+ | v +------------------------------------+ +----------------------+ | Stateless Inference API (CPU pods) |<watch| Config service | | - Validate payload & deadline | | (etcd / Consul): | | - Resolve version & canary split | | aliases, splits, | | - Adaptive concurrency cap -> 503 | | target pool addresses| +------------------------------------+ +----------------------+ | | | | gRPC | gRPC | gRPC v v v +-------------+ +-------------+ +-------------+ | toxicity | | toxicity | | sentiment | Dedicated GPU model- | v2.3 pool | | v2.4 pool | | v3.0 pool | server pools (Triton, | (stable) | | (canary) | | (stable) | TorchServe, TF Serving) +-------------+ +-------------+ +-------------+ ^ ^ ^ +--------+--------+--------+--------+ | pull & verify SHA-256 at pod startup +--------------------------------------------------+ | Immutable Artifact Store (S3) + Registry (PG) | +--------------------------------------------------+Why dedicated model-server pools instead of a sidecar? Both patterns separate web API code from ML execution (Triton, TorchServe, or TensorFlow Serving), so let's compare them directly:
- Sidecar pattern (one API container + one model-server container inside the same Kubernetes pod talking over
localhost): saves ~1 ms of network hop, but forces CPU web servers and expensive GPUs to scale in lockstep, requires every pod to hold every model in GPU memory, and couples model rollouts to API pod restarts. - Dedicated model-server pools (one separate GPU deployment per
(task, version)called over internal gRPC): lets lightweight CPU API pods scale on HTTP traffic while each GPU pool scales independently on GPU queue depth. A new version (toxicity v2.4) warms up in its own pool without touchingv2.3or the API tier, and switching traffic is a config change. That easily justifies ~1 ms of internal network latency. (Lightweight sidecars still fit next to each model server for mutual TLS and metrics scraping.)
- Sidecar pattern (one API container + one model-server container inside the same Kubernetes pod talking over
Deep dive 1: Per-tenant rate limiting and bounded overload
Without overload protection, a sudden traffic spike fills queues in front of the GPUs. Once queue wait exceeds 250 ms, clients time out and retry while our GPUs still spend time computing those timed-out requests. Throughput of useful answers collapses toward zero—a failure mode called congestive collapse. Bounded overload prevents this with four fast-reject layers.
Layer 1: Per-tenant token bucket at the Ingress Gateway. Each tenant gets a bucket holding at most
bursttokens that refills continuously atratetokens per second. Classifyingktexts spendsktokens.- Why token bucket instead of a leaky-bucket queue? A leaky bucket smooths bursts by placing excess requests into a FIFO queue and draining them at a fixed rate—great for background jobs, bad for a synchronous API because queueing adds unpredictable latency. A token bucket lets legitimate short bursts up to
burstpass with zero added wait and immediately rejects anything beyond that with429and an exactRetry-Afterheader. - Central Redis with local fallback. Because a tenant's requests land on many gateway pods, we store buckets in a small Redis cluster sharded by
tenant_idand run the refill-and-deduct logic as a single atomic Lua script (< 1 ms inside the region). If Redis becomes unreachable, each of theNgateway pods falls back to an in-memory bucket withrate / N—slightly approximate, but keeps the API up instead of failing closed.
Here is the exact token-bucket math that the Redis Lua script (and local fallback) executes:
import math import time class TokenBucket: """Refills at `rate` tokens/sec up to `burst` capacity; 1 token = 1 text.""" def __init__(self, rate: float, burst: int): self.rate = rate self.burst = burst self.tokens = float(burst) self.last_refill = time.monotonic() def try_take(self, text_count: int): """Return (allowed, retry_after_sec). retry_after_sec is None if request > burst.""" now = time.monotonic() elapsed = now - self.last_refill # Refill tokens earned since the last check, capped at burst capacity. self.tokens = min(float(self.burst), self.tokens + elapsed * self.rate) self.last_refill = now # A single batch larger than the tenant's max burst can never succeed -> 400. if text_count > self.burst: return False, None if self.tokens >= text_count: self.tokens -= text_count return True, 0 # Compute integer seconds until enough tokens refill for the Retry-After header. missing_tokens = text_count - self.tokens return False, math.ceil(missing_tokens / self.rate)Layer 2: Cluster-wide adaptive concurrency limits. Like airlines or cloud providers, subscription plans are oversubscribed: 2,000 tenants each allowed 50 texts/s could legally send 100,000 texts/s together even though our GPUs handle 20,000/s. So the Inference API enforces an in-flight concurrency cap per GPU pool, shedding excess load immediately with
503(dropping lower-priority free-tier requests before enterprise requests).Layer 3: Token-bounded GPU queues. Inside each model server, we cap the waiting queue by token count (
<= 4,096queued tokens per GPU—equivalent to thirty-two 128-token texts or eight 512-token texts), not raw request count. Counting requests alone would let thirty-two 512-token essays pile up ~85 ms of GPU work and blow the 100 ms SLA. When the token cap is full, the model server rejects immediately.Layer 4: Deadlines and retry budgets. Every internal gRPC call carries the remaining
X-Request-Timeout-Msdeadline. If a queued request's deadline expires before reaching the GPU, the model server drops it without running inference. Client SDKs retry at most twice with exponential backoff and jitter (randomizing wait times so thousands of clients don't retry on the exact same millisecond), and internal retries on pod crashes are capped at 10% of active traffic.- Why token bucket instead of a leaky-bucket queue? A leaky bucket smooths bursts by placing excess requests into a FIFO queue and draining them at a fixed rate—great for background jobs, bad for a synchronous API because queueing adds unpredictable latency. A token bucket lets legitimate short bursts up to
Deep dive 2: GPU dynamic batching and tail-latency control
Running 1 text at a time on a GPU leaves most of its thousands of compute cores idle. Dynamic batching inside the model server (built into Triton and TorchServe) collects individual texts arriving within a short window (up to
5 msor32texts, whichever comes first) and runs them as one matrix multiplication.Naive 1-by-1 on GPU (4 ms each): req A -> [4 ms] req B --------> [4 ms] req C ---------------> [4 ms] ... 32 requests take ~128 ms serially! Dynamic batching + length buckets: Bucket <=128 tokens: collect for <=5 ms -> [run 32 short texts together in 20 ms] Bucket <=256 tokens: collect for <=5 ms -> [run 16 medium texts together in 24 ms] Bucket <=512 tokens: collect for <=5 ms -> [run 8 long texts together in 32 ms]Four optimizations keep p99 tail latency well below 100 ms:
- Length bucketing avoids padding waste. Every sequence in a GPU batch must be padded to match the longest sequence in that batch. If one 512-token review lands in a batch with thirty-one 20-token chat messages, the GPU wastes >90% of its math on padding zeros! Routing incoming texts into three separate batch queues (
<= 128,<= 256,<= 512tokens) keeps short texts fast while capping long batches at 8 items so they still finish in<= 35 ms. - Smart truncation. Transformer encoders cap input length at 512 tokens.
headkeeps the first 510 content tokens plus[CLS]and[SEP](510 + 2 = 512). For toxicity, abusive language often appears at the very end of a post, sohead_tailkeeps the first 128 tokens and last 382 tokens (128 + 382 + 2 = 512) and sets"truncated": truein the response. - Compiled fp16 weights. Models are exported to ONNX or TensorRT in 16-bit floating point (
fp16), roughly doubling throughput vs.fp32. Every compiled artifact is checked againstgolden_outputs.jsonlbefore serving to ensure quantization did not shift class probabilities. - Tenant-scoped exact-match cache. Viral posts and spam bots repeat identical strings. An in-memory cache with a 10-minute TTL keyed by
(tenant_id, task, version, sha256(normalized_text))absorbs repeat hits without touching GPUs. Includingtenant_idprevents a cross-tenant timing side channel (where a 2 ms cache hit reveals to Tenant B that Tenant A recently classified that exact string), and storing only SHA-256 hashes keeps raw text out of memory.
- Length bucketing avoids padding waste. Every sequence in a GPU batch must be padded to match the longest sequence in that batch. If one 512-token review lands in a batch with thirty-one 20-token chat messages, the GPU wastes >90% of its math on padding zeros! Routing incoming texts into three separate batch queues (
Deep dive 3: Model versioning, warm deploys, and instant rollbacks
Deploying a new model (
toxicity v2.4) must never stall live requests or require redeploying API containers. We decouple pool startup from traffic routing using a configuration store (etcdorConsul).Step 1: Register & validate Step 2: Warm pool tox-v24 Step 3: Shift routing in etcd +------------------------+ +---------------------------+ +----------------------------+ | S3: model + tokenizer | --> | Download & check SHA-256 | -> | Shadow 5% (discard output) | | + golden_outputs.jsonl | | Load GPU + warmup batches | | Canary 1% -> 5% -> 25%... | +------------------------+ | Verify golden outputs | | Promote stable = v2.4 | | Pass Kubernetes readiness | | Instant rollback -> v2.3 | +---------------------------+ +----------------------------+- Warm startup before readiness. When Kubernetes launches
tox-v24pods, each pod downloadss3://models/toxicity/v2.4/, verifies SHA-256 hashes, loads weights onto the GPU, runs ~200 synthetic warmup batches across all three length buckets (forcing CUDA kernel compilation and memory allocation up front), and verifies its predictions ongolden_outputs.jsonlmatch training within1e-3. Only after passing all checks does the pod mark its readiness probe healthy. Cold pods never see live traffic. - Dynamic traffic shifting via etcd/Consul. Every Inference API pod maintains a long-lived watch on
/routing/in etcd and caches the routing table in local memory. Moving from99% v2.3 / 1% v2.4to95% / 5%is a single key-value write in etcd that propagates to all API pods within ~1 second—no container rebuilds or restarts. - Deterministic split hashing. For requests using
"version": "stable", the API picks a version usinghash(tenant_id, sha256(text)) mod 100. Hashing(tenant_id, text)ensures the same text from the same tenant gets consistent labels across retries during a canary, while avoiding the lumpiness of hashingtenant_idalone (where one giant tenant represents 25% of all traffic). Explicit"version": "v2.3"pins bypass the split completely. If etcd goes down, API pods keep serving with their last known good in-memory routing table (fail static), and newly started pods bootstrap from a backup snapshot in S3. - Instant rollback. If automated canary guardrails see elevated p99 latency,
5xxerrors, or abnormal label shifts onv2.4, the controller writessplit = {"v2.3": 100}to etcd. Traffic moves back in ~1 second because thev2.3GPU pool is kept warm. We keep the old pool at 100% size for 24 hours after promotion (15 temporary extra GPUs for toxicity), then taper it to 3 minimum replicas for 7 days.
- Warm startup before readiness. When Kubernetes launches
ML lifecycle: features, offline gates, A/B testing, drift, and PII safety
Bundled preprocessing. The #1 silent bug in ML serving is training-serving skew—for instance, stripping accents or lowercasing differently in Python training vs. production serving. Packaging Unicode normalization rules,
tokenizer.json, andlabels.jsoninside the immutable S3 artifact and runninggolden_outputs.jsonlat pod boot eliminates this skew.Offline release gates. Before
v2.4can enter shadow or canary, an automated evaluation job records: - Classification quality: macro/per-class Precision, Recall, F1, plus PR-AUC (Precision-Recall Area Under the Curve, preferred over ROC-AUC for toxicity because toxic messages are a small fraction of all traffic). - Calibration: Expected Calibration Error (ECE), checking that texts scored0.80toxic are actually toxic ~80% of the time. Customers hard-code business thresholds (like blocking posts>= 0.85), so uncalibrated score shifts break customer apps even if accuracy rises! - Subgroup slices & prediction churn: fairness slices across languages/dialects (so harmless slang isn't falsely flagged toxic) and churn (percentage of held-out texts whose predicted label flips betweenv2.3andv2.4).Online canary (A/B test) and privacy-safe drift monitoring. During canary steps (
1% -> 5% -> 25% -> 50% -> 100%), we comparev2.4againstv2.3on latency, error rates, score distributions, human-labeled samples from opt-in tenants, and/v1/feedbackcorrection rates. In production, we detect model drift (when live traffic shifts away from training data) without ever logging raw customer text:- Allowlisted structured logs: The logging library only accepts fixed metadata fields (
request_id,tenant_id,task,version,token_length_bucket,detected_language,predicted_label,top_score,latency_ms,status_code). Because there is notextfield in the schema and exception handlers redact input strings, PII cannot leak accidentally; a regex/Luhn log scrubber acts only as a defense-in-depth alarm. - Prediction and input drift signals: Hourly jobs compute each task's predicted class distribution, low-confidence share (
top_score < 0.60), token-length histogram, unknown-token rate, and mean embedding vector over fixed, non-overlapping windows of>= 100texts. If the Population Stability Index (PSI)—a standard formula measuring how much two probability histograms diverge—exceeds0.2against the baseline week, on-call ML engineers get an alert and trigger targeted human labeling on opt-in tenant samples.
- Allowlisted structured logs: The logging library only accepts fixed metadata fields (
Failure handling and trade-off summary
Failure scenario How we detect it Automated response GPU pod crashes or hardware error gRPC error / readiness probe Remove pod from pool; API retries once on a peer replica if deadline and 10% retry budget allow Single slow "straggler" GPU node Replica p99 > 2x pool median Eject slow pod; optionally send a hedged request (a backup copy to a second replica if no reply arrives by p95) Traffic spike saturates a GPU pool Token queue full / rising latency Shed excess immediately with 503+Retry-After; autoscale GPU pool; optional fallback to smaller distilled model ("degraded": true)Redis rate-limit cluster unreachable Connection / Lua timeout > 2 ms Gateway pods switch to local in-memory buckets ( rate / num_gateways) so traffic keeps flowingetcd / Consul config cluster down Watch stream disconnect API pods keep last known good routing table in memory; new pods read backup snapshot from S3 Entire Availability Zone goes offline Load balancer / health checks Remaining 2 zones absorb traffic (~67%–80% GPU load thanks to 3-zone headroom) while autoscaler replenishes capacity Summary of core trade-offs
- Dedicated GPU model-server pools vs. sidecars: Adds ~1 ms internal gRPC hop, but unlocks independent CPU/GPU scaling, multi-model packing, warm pool rollouts, and 1-second routing rollbacks.
- Token bucket (
429) + bounded token queues (503) vs. deep queues: Rejects excess calls during spikes, preserving <100 ms latency for every accepted request instead of collapsing under timeouts. - Central Redis buckets with local fallback: Exact tenant fairness in normal operation (<1 ms overhead) without turning a Redis outage into a global API outage.
- Keeping previous version warm for 24 hours: Temporarily doubles GPU cost for the updated task on release day in exchange for true 1-second rollback safety.
- 60% steady-state GPU target + 3-zone symmetry: Costs ~1.67x minimum GPUs, buying instant survival of a full Availability Zone outage and slack while slow GPU nodes autoscale.
Intuition & how it works
Think of GPU classification like running high-speed express ferries across a narrow river. A GPU ferry takes almost the same ~20 milliseconds to cross whether it carries 1 passenger or 32 passengers together—so grouping passengers into small batches multiplies throughput dramatically. At the same time, every caller is holding an open HTTP connection expecting an answer in under 100 milliseconds (synchronous inference, meaning the prediction comes back inside the initial HTTP response rather than via a callback later). Our job is to pack arriving texts onto warm, versioned GPU ferries quickly, enforce per-customer ticket limits at the dock, and immediately turn away overflow crowds during rush hour so the waiting line never grows longer than 100 milliseconds.
The naive approach—loading PyTorch models directly inside ordinary web-server containers and letting incoming requests wait in an unbounded queue—fails quickly in production. Every web-server replica would require an expensive GPU and hold every model version in memory, rolling out v2.4 would restart active HTTP servers, and a sudden traffic surge would create a multi-second queue where every single client times out and retries at once.
Here is how a tiny burst of three requests travels through our architecture during a 95% v2.3 / 5% v2.4 rollout:
- Tenant A sends 2 texts (
item_1,item_2on"stable"): The Ingress Gateway checks Tenant A's API key and deducts 2 tokens from Tenant A's token bucket (a fast counter in Redis that refills steadily up to a burst cap). Tenant A has 140 tokens left, so the request passes in <2 ms. - Tenant B sends 10 texts while out of quota: Tenant B's token bucket has only 1 token left. The gateway rejects it immediately in 1 ms with
429 Too Many RequestsandRetry-After: 2, never touching the GPUs. - Version routing & dynamic batching: The stateless Inference API reads its in-memory routing snapshot (watched from etcd, a distributed configuration store). Hashing
(tenant_A, item_1)lands in the 95% slice (tox-v23), while(tenant_A, item_2)lands in the 5% canary slice (tox-v24). Each GPU model server groups short texts arriving within 5 ms into one padded batch, runs a 20 ms forward pass, and returns probabilities—finishing end-to-end in ~35 ms while logging only structured metadata (zero raw text).
Key trade-offs
- Dedicated GPU model-server pools vs. sidecar containers. A sidecar runs the model server inside the same pod as the web API over
localhost, saving ~1 ms of network hop, but it forces CPU API logic and expensive GPUs to scale together and load every model on every pod. Separate GPU pools per(task, version)add ~1 ms of internal gRPC latency in exchange for independent GPU scaling, isolated warmups, and 1-second config-driven rollbacks. - Token bucket vs. leaky bucket at ingress. A leaky bucket places bursty requests into a FIFO queue and drains them at a steady rate, turning bursts into added waiting time that breaks a 100 ms synchronous SLA. A token bucket lets legitimate bursts up to
burstpass immediately and rejects excess right away with429andRetry-After, keeping latency honest. - Central Redis rate limits with local fallback vs. purely local limits. Storing token buckets in Redis gives exact per-tenant enforcement across dozens of gateway pods for <1 ms overhead. Falling back to local per-pod
rate / Nbuckets if Redis goes down (failing open with bounded GPU queues behind it) avoids turning a cache hiccup into a total API outage. - Fast load shedding (
503) vs. deep queueing. Returning an immediate503 Service Unavailabledisappoints excess callers during an unexpected surge, whereas deep queueing causes every caller to time out while GPUs waste cycles computing answers nobody will read. - Deterministic
hash(tenant_id, text_hash)splits vs. random or per-tenant canary splits. Purely random splits can flip the predicted label when a client retries the exact same text; pure per-tenant splits are too coarse when one large customer sends 25% of total traffic. Hashing both tenant and text gives smooth 1% steps and repeatable labels per text. - Keeping the previous model pool warm vs. immediate GPU teardown. Leaving
v2.3warm for 24 hours after promotingv2.4temporarily doubles GPU cost for that task, which is the direct price of guaranteeing a 1-second rollback if a subtle bug surfaces in production. - 60% GPU utilization target across 3 Availability Zones vs. running hot. Provisioning
1 / 0.6 ≈ 1.67xminimum GPUs across three zones ensures that if one entire data center goes offline, the remaining two zones rise to ~67%–80% load and keep meeting the 100 ms p99 target while new GPU nodes take minutes to boot.
Common mistakes
- Embedding model weights directly inside the HTTP web process, forcing every API pod onto GPU machines and turning model updates into full application redeployments.
- Allowing unbounded queues and uncapped retries, which turns a brief traffic spike into congestive collapse as timed-out retries multiply cluster load.
- Rate-limiting HTTP requests instead of texts or tokens, allowing a 16-text batch to consume 16x the GPU compute for the quota cost of 1 text.
- Returning
429for internal server overload, confusing customers into thinking they broke their contract quota when our own GPU pool is saturated (503is the right code for server overload). - Marking new GPU pods ready before running warmup batches, causing the first wave of live customer requests to stall for seconds during lazy CUDA kernel compilation.
- Mixing short and long texts in one GPU batch, where one 512-token document forces thirty-one 20-token messages to be padded to 512 tokens and triples batch latency.
- Shipping tokenizers separately from model weights or skipping golden-output checks, introducing silent training-serving skew (preprocessing differences that quietly ruin accuracy without throwing errors).
- Ignoring probability calibration across model versions, shifting confidence scores (
0.75vs.0.90) and breaking downstream customer rules even when top-label accuracy improves. - Logging raw request bodies or exception tracebacks, leaking sensitive customer PII into log storage.
Follow-up questions
- How do you roll out a new model revision with zero dropped requests when its weights demand a much larger GPU memory footprint than the currently active version? Because
v2.4may no longer fit alongsidev2.3or on the same smaller GPU type, deploy it blue/green onto a separate node pool provisioned with larger GPUs (enforced via Kubernetes GPU resource requests and node selectors). Spin uptox-v24, verify SHA-256 hashes, run warmup batches across max-length 512-token inputs to prove it cannot trigger out-of-memory errors, and pass golden-output checks before shifting traffic (1% -> 5% -> 25% -> 100%) via etcd. If cloud GPU quota is tight, schedule the rollout during the daily traffic trough and shrinkv2.3step-by-step asv2.4scales up (accepting slower rollback), or apply validatedfp16/int8quantization (storing weights in fewer bits) to fit the original GPU footprint. - When tail inference latency threatens to exceed caller timeout budgets, what techniques keep responses fast while keeping the HTTP contract strictly synchronous? First propagate
X-Request-Timeout-Msend-to-end so the server drops doomed work early and returns a fast error instead of hanging until socket timeout. Next cut tail latency with token-length buckets (so short texts never wait behind 512-token texts), shorter dynamic-batching wait windows (2 msinstead of5 ms), tenant-scoped hash caching for repeated strings, and request hedging (sending a backup RPC to a second GPU replica if the first has not replied by p95 latency, taking whichever finishes first). For long texts or tight deadlines, applyhead_tailtruncation, or fall back to a smaller distilled model (a compact student network trained to mimic the larger model) when remaining deadline < 40 ms and mark"degraded": true; for multi-text batches, stream completed items incrementally over HTTP chunked transfer encoding inside the single synchronous response. - What concrete safeguards guarantee that logs, metrics, and distributed traces never capture personal data embedded inside caller text payloads? Prevent leaks by construction rather than hoping regex scrubbers catch everything afterward: disable HTTP body logging at the load balancer and gateway, wrap incoming strings in a
SensitiveTextwrapper class whose__str__and__repr__print only[REDACTED len=...], and restrict the structured logger and OpenTelemetry trace spans to a strict allowlist of non-text fields (request_id,tenant_id,task,version,length_bucket,scores,latency_ms). Sanitize parser and tokenizer exception messages so stack traces never echo offending input substrings. Finally, run a streaming PII detector (emails, phone numbers, Luhn-checked credit cards) on the log pipeline as an alarm that pages engineers if anything ever slips through, and continuously inject synthetic canary requests containing unique marker tokens—alerting immediately if a marker ever appears in any log, metric, or trace store.
Follow-up questions
- How do you roll out a new model revision with zero dropped requests when its weights demand a much larger GPU memory footprint than the currently active version?
- When tail inference latency threatens to exceed caller timeout budgets, what techniques keep responses fast while keeping the HTTP contract strictly synchronous?
- What concrete safeguards guarantee that logs, metrics, and distributed traces never capture personal data embedded inside caller text payloads?
Similar questions
- Reachable Negative-Weight Cycle Detection
- Rainwater Collected Across Column Heights
- Streaming Integer Median Queries
- Cycle-Safe Edge Addition in a DAG
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving