Architecting a Multi-Workload Audio ML Platform
Medium · ML System Design · Software Engineer · Technical Screen
Prompt
Design the core backend and ML serving infrastructure for an audio intelligence platform. Customers send spoken audio to run tasks including automatic speech recognition (ASR), speaker diarization, voice separation/isolation, and translation. Your architecture must serve two fundamentally different traffic profiles on the same platform: low-latency interactive workloads (such as real-time captioning or clinician voice notes) and high-throughput asynchronous batch workloads (such as processing multi-hour university lecture repositories or recorded customer-support calls).
Core functional capabilities:
- Two-mode ingestion: Handle short interactive requests (clips up to 60 seconds with an end-to-end latency budget under 2 seconds) alongside large offline batch recordings (files up to 2 hours or 1.5 GB).
- Composable pipeline DAGs: Orchestrate multi-step processing graphs (for example: normalization and voice-activity chunking, optional source separation, speech transcription, and downstream post-processing or translation).
- Chunk-level lineage and crash recovery: Partition long recordings into tracked audio segments with deterministic lineage so that a worker failure triggers idempotent retries of only the affected segments rather than restarting the full recording.
- Confidence gating and model fallbacks: Evaluate confidence after primary inference and automatically route low-confidence segments to stronger fallback models.
Scale and operational targets:
- Throughput and concurrency: Process 50,000 hours of ingested audio per day while supporting peaks of 10,000 simultaneous live streams.
- Hardware efficiency: Keep GPUs well saturated using dynamic batching across clips and mixed-precision execution.
- Workload isolation: Ensure heavy batch queues never starve compute resources or violate interactive latency SLAs.
Scope & Expectations
- End-to-end topology: Show how the ingestion layer, object-storage data plane, DAG orchestrator, and CPU/GPU worker pools fit together.
- Large-media streaming and segmentation: Explain how multi-gigabyte recordings are uploaded, normalized, sliced, and read by workers without exhausting memory or network links.
- GPU scheduling and isolation: Detail how variable-duration segments are dynamically batched, how interactive SLAs are protected from batch traffic, and how noisy tenants are contained.
- Persistence and lineage schema: Define the data model for jobs, segments, stage checkpoints, and confidence evaluations enabling idempotent retries.
Step-by-step walkthrough
Clarify requirements and frame the platform + ML problem
An enterprise audio AI platform serves two workloads with opposite physics on shared GPU hardware: live users who notice a 500-millisecond hiccup, and multi-hour recorded support sessions or university lecture archives where throughput per dollar and chunk-level crash recovery dominate.
Key domain terms up front
- ASR (Automatic Speech Recognition): Converting spoken audio into timestamped words.
- VAD (Voice Activity Detection): A lightweight CPU model that labels which milliseconds contain human speech versus silence or background hum.
- Speaker diarization: Segmenting audio by who spoke when (
Speaker A: 0.0s–4.2s,Speaker B: 4.5s–9.1s). - Voice separation / isolation: Extracting clean primary speech out of overlapping talkers or loud background noise.
- DAG (Directed Acyclic Graph): A multi-stage processing pipeline with dependencies and no cycles, such as
normalize -> VAD & chunk -> [separation] -> primary ASR -> quality gate -> [fallback ASR] -> global diarization & stitch -> punctuation -> [translation].
Functional and non-functional requirements
- Dual ingestion: Interactive clips (
<= 60 s, sub-2-second p99 turnaround) plus live WebSocket streams (~1 s partial updates), alongside asynchronous batch files (<= 2 hours/1.5 GB) delivered via webhook or polling. - Granular lineage & idempotent retries: Track every chunk and stage execution so a worker crash retries only the unfinished 25-second chunk, never the whole 2-hour recording, without duplicating words or double-billing.
- Automated quality gates: Score every primary inference output and route uncertain segments to stronger fallback models within a strict GPU budget.
- Scale & isolation: Ingest 50,000 audio hours/day with 10,000 concurrent live streams at peak, saturating GPUs via dynamic batching and mixed precision while guaranteeing batch backlogs never starve interactive SLAs.
ML framing of the quality gate
While ASR, diarization, and translation are underlying foundation models (evaluated offline by WER — Word Error Rate, DER — Diarization Error Rate, SI-SDR — Scale-Invariant Signal-to-Distortion Ratio for audio separation, and COMET / BLEU for translation), the platform itself trains and operates a calibrated quality-gate classifier predicting
P(segment WER > 20%)against human-transcribed audit slices to decide when spending 4x extra GPU compute on a fallback model pays off.Back-of-the-envelope capacity, bandwidth, and GPU math
We express GPU speed as RTFx (Real-Time Factor, how many seconds of audio one GPU processes in 1 wall-clock second — always benchmarked on your actual models and GPUs). Let's run the math step by step:
1. Ingestion rate & concurrency Daily audio: 50,000 h x 3,600 s / 86,400 s/day = ~2,083 audio-s arriving per second Workload split: 20,000 h/day interactive + 30,000 h/day batch Interactive streams: 20,000 h / 24 h = ~833 concurrent streams average; 10,000 at peak (12x!) 2. Network & object storage bytes Worst-case raw upload (48 kHz stereo 16-bit PCM): 48,000 x 2 x 2 B = 192 KB/s -> One 2-hour file: 7,200 s x 192 KB/s = 1.38 GB (fits cleanly under the 1.5 GB limit) -> Daily raw upper bound: 180M audio-s x 192 KB/s = ~34.6 TB/day (~400 MB/s avg ingress) Normalized internal format (16 kHz mono 16-bit PCM): 16,000 x 1 x 2 B = 32 KB/s (32 bytes/ms!) -> One 2-hour file: 230.4 MB | One 30 s chunk: 960 KB | Daily normalized: ~5.8 TB/day 3. GPU fleet sizing (assumed per-GPU RTFx on L4/A10G-class hardware in FP16) Streaming ASR = 40x | Batched ASR = 200x | Diarization = 300x | Separation = 150x | Fallback = 50x Peak interactive pool (10,000 streams; separation on 20%, fallback on 10%): ASR: 10,000 / 40 = 250 | Diarization: 10,000 / 300 = 33.3 Separation: 2,000 / 150 = 13.3 | Fallback: 1,000 / 50 = 20 -> ~317 active GPUs With 65% target utilization ceiling for < 2 s p99 headroom: 317 / 0.65 = ~490 GPUs Daily batch workload (30,000 h/day; separation on 50%, fallback on 10%): GPU-s per audio-s = (0.5 / 150) + (1 / 300) + (1 / 200) + (0.1 / 50) = 0.0137 GPU-s/audio-s Total batch compute = 30,000 h x 0.0137 = ~410 GPU-hours/day -> ~22 GPUs standalone at 80% util! 4. Durable orchestration task rate (batch: ~25 s avg chunk, ~4 durable stages/chunk) 30,000 h x 3,600 s / 25 s = 4.32M chunks/day -> ~17.3M stage runs/day = ~200 stage runs/s avgThree architectural insights jump straight out of these numbers:
- Interactive peak concurrency (~490 GPUs) dominates hardware cost, whereas all 30,000 hours of daily batch work need only ~22 GPUs — meaning batch can run almost for free off-peak on idle interactive GPUs if we reclaim capacity safely!
- Heavy audio bytes (~400 MB/s) must flow directly to object storage, never through API pods, queues, or the workflow orchestrator.
~200 stage runs/sfits comfortably in PostgreSQL, whereas persisting every20 mslive WebSocket frame (500,000 frames/sat peak!) would melt a database — so interactive requests run in-memory while batch jobs use durable chunk checkpoints.
API design
1. Asynchronous batch jobs (up to 2 h / 1.5 GB) POST /v1/uploads -> 200 { "upload_id": "u_81", "part_urls": [...] } (64 MB parts) POST /v1/uploads/{upload_id}/complete -> 200 { "media_id": "m_7f3" } POST /v1/jobs { "media_id": "m_7f3", "pipeline": "asr+diarize", "pipeline_version": 12, "options": { "language": "auto", "translate_to": ["es"] }, "callback_url": "https://...", "idempotency_key": "tenantA-call-9912" } -> 202 { "job_id": "j_91c", "status": "queued" } GET /v1/jobs/{job_id} -> 200 { "status": "running", "segments_total": 288, "segments_done": 194, "result_uri": null } 2. Interactive short clip (<= 60 s, < 2 s p99 turnaround) POST /v1/transcribe (body: Opus/FLAC bytes <= 2 MB + query options) -> 200 { "text": "...", "words": [{"w": "hello", "start_ms": 120, "end_ms": 410, "conf": 0.94}], "speakers": [...], "low_confidence": false } 3. Interactive live stream (live captioning, clinician voice notes) WS /v1/stream Client -> Server: binary 20 ms Opus frames tagged with monotonic seq number Server -> Client: { "type": "partial"|"final", "seq": 431, "text": "...", "revision": 2 }Why three API details matter in production:
- Presigned multipart URLs let clients upload twenty-four
64 MBchunks in parallel straight to object storage and retry one dropped64 MBpart without restarting a1.5 GBtransfer. idempotency_keyunique per tenant guarantees that retryingPOST /v1/jobsafter a network timeout returns the existingjob_idinstead of double-charging GPU hours.- Non-blocking
revisionupdates on live streams: When a live utterance fails the quality gate, the server immediately emits the primary"final"(revision: 1) so live captions never freeze, then asynchronously runs the fallback model and pushes a corrected"final"(revision: 2).
- Presigned multipart URLs let clients upload twenty-four
Data model, deterministic lineage, and idempotent retries
Every segment and stage execution is keyed by a deterministic cryptographic hash of its inputs, turning checkpoints, deduplication, and lineage queries into simple primary-key lookups.
media media_id PK, tenant_id, sha256, raw_uri, normalized_uri, duration_ms, bytes pipeline_versions (pipeline_id, version) PK, dag_spec JSONB (stages, model_versions, params) jobs job_id PK, tenant_id, mode, media_id, pipeline_id, pipeline_version, status, idempotency_key UNIQUE(tenant_id, idempotency_key), result_uri segments segment_id PK = sha256(media_id, start_ms, end_ms, chunker_version) media_id, idx, start_ms, end_ms, -- audio slice sent to GPU (w/ overlap) own_start_ms, own_end_ms, -- non-overlapping slice this chunk owns byte_offset, byte_len -- exact HTTP Range in normalized_uri stage_runs run_key PK = sha256(input_keys_or_segment_id, stage, model_version, params_hash) segment_id NULLABLE, stage, status IN ('pending','leased','done','failed'), attempt INT, lease_owner, lease_expires_at, input_run_keys[], output_uri, started_at, finished_at job_runs (job_id, run_key) PK -- links jobs to shared stage_runs quality_evals run_key PK -> stage_runs, p_bad FLOAT, threshold FLOAT, features JSONB, decision IN ('accept','fallback','flag'), fallback_run_key NULLABLE job_artifacts (job_id, kind) PK, uri, source_run_keys[] -- final transcript / diarization JSONHow this schema guarantees fault-tolerant, idempotent execution
- Chunk-level checkpoints for free: If a worker or orchestrator crashes at minute 110 of a 120-minute recording, reconciling
job_runssees 260stage_runsalready markeddoneand re-enqueues only the 28 unfinished chunks. - Attempt-isolated storage + Compare-And-Swap commit: Because dynamic GPU batching groups different neighbors on a retry, floating-point rounding means two runs of the same chunk are not bit-for-bit identical. Workers write outputs to
outputs/{run_key}/attempt_{attempt}.jsonand commit via an atomic conditional update:UPDATE stage_runs SET status = 'done', output_uri = :output_uri WHERE run_key = :run_key AND status <> 'done'. If a slow "zombie" worker wakes up after its lease (temporary time-bounded task lock) expired and another worker already finished,0rows update and the zombie's file is ignored! - Zero-waste partial reprocessing: Upgrading ASR from
v3tov4changesrun_keyonly forASRand downstream stages while reusing existingnormalize,VAD, andseparationoutputs automatically.
- Chunk-level checkpoints for free: If a worker or orchestrator crashes at minute 110 of a 120-minute recording, reconciling
High-level architecture: decoupled control plane and data plane
CONTROL PLANE (lightweight IDs, offsets, tokens) DATA PLANE (heavy audio bytes) Batch Client --- POST /uploads, /jobs ---> [ API Gateway ] -----------> presigned URL tokens | | | +========= multipart PUT (<= 1.5 GB) =======|============================> v | [ Object Storage (S3) ] v raw/, norm/, outputs/ [ DAG Orchestrator ] ^ | (stateless reconciler) | | HTTP Range GET | | | (~960 KB/chunk) v | v [ PostgreSQL Lineage Store ] | +------------------+ (jobs, segments, stage_runs) | | Stage Workers | | +--| (CPU pre/post + | +-----------------+-----------------+ | commit outputs) | v v +--------+---------+ ( CPU Task Queue ) ( Tenant-Fair Batch Queues ) | | bucketed by duration: 5s..30s | gRPC PCM v | v [ Streaming Normalizer ] +-------------> +------------------+ ffmpeg -> 16kHz s16le, | Triton GPU Fleet | CPU VAD & cut planner | - Interactive | | Pool (~490) | Live Client == WS 20ms Opus ==> [ Stream Gateway ] -- sticky stream_id ----------> | - Base Spot | Clip Client == <=60s audio ===> [ Clip Service ] -- in-memory DAG (no DB hop) -> | Batch Pool | +------------------+- Batch flow: Clients upload raw files directly to S3. A CPU normalizer streams the raw file through
ffmpeginto headerless16 kHzmono PCM in S3, runs CPU VAD, and writessegmentsrows. The orchestrator enqueues per-segment tasks carrying only(run_key, normalized_uri, byte_offset, byte_len)(~200 bytes per message). Stage workers fetch their960 KBslice via a ranged HTTPGET, send duration-bucketed RPCs to Triton GPU servers, writeoutputs/{run_key}/attempt_{n}.json, and commit in PostgreSQL. Once all segment runs finish, a fan-in stage clusters speaker embeddings globally, stitches words, punctuates, translates, and fires the webhook. - Interactive flow: Bypasses PostgreSQL stage persistence completely so the entire 2-second budget goes to model execution, writing only final results and billing events asynchronously.
- Batch flow: Clients upload raw files directly to S3. A CPU normalizer streams the raw file through
Deep dive 1: Large-file streaming, byte-seekable PCM, and silence-aware chunking
Streaming normalization without RAM blowups
Decoding a
1.5 GBstereo WAV into a 32-bit float array in memory allocates~3 GBof RAM per file and crashes multi-tenant workers. Instead, the normalizer pipes an HTTP stream fromraw_uristraight throughffmpeg -f s16le -ac 1 -ar 16000into an S3 multipart upload buffer (~16 MB constant RAM).Why headerless
s16le(signed 16-bit little-endian PCM) instead of compressed FLAC or WAV?- Exact
O(1)byte-offset arithmetic: At16,000 samples/s x 2 bytes = 32 bytes/ms, any chunk[start_ms, end_ms]sits at exact byte offset32 * start_mswith byte length32 * (end_ms - start_ms). Any GPU stage worker fetches its 30-second chunk (960 KB) in one S3Range: bytes=...request without downloading the whole230 MBfile or creating 300 tiny S3 objects! - No WAV header offset bugs: Standard WAV headers are 44 bytes only when no extra
LIST/INFOmetadata chunks are present (ffmpeginserts aLISTchunk by default, shifting sample offsets!). Storing raws16leand recording sample rate in themediarow eliminates off-by-N byte corruption.
Silence-aware chunking and midpoint ownership (preventing split words)
Many speech encoders (like Whisper) have a
30 scontext window. Cutting blindly every30,000 msslices words in half! Instead, we scan CPU VAD silence intervals inside[pos + 20s, pos + 30s]and cut at the midpoint of the longest silence inside that window. Only when someone speaks non-stop for 30 seconds with zero pause do we perform an overlapped hard cut (1,000 msoverlap), assigning non-overlapping ownership[own_start_ms, own_end_ms]split right at the midpoint of the overlap (+500 ms) so both adjacent chunks have at least500 msof surrounding audio context:Hard cut with 1,000 ms overlap (continuous speech, no silence in 20s..30s): Segment 0 audio sent to GPU: [0 ms ............................ 30,000 ms] Segment 1 audio sent to GPU: [29,000 ms .......................... 59,000 ms] |<-- 1,000ms -->| Non-overlapping word ownership: Segment 0 owns: [0 ms ....................... 29,500 ms) Segment 1 owns: [29,500 ms ...................... 58,500 ms) (During stitching, keep a predicted word iff its midpoint (start+end)/2 falls inside [own_start, own_end)!)def plan_segments(pauses_ms, total_ms, target_min=20_000, target_max=30_000, overlap=1_000): """ Split [0, total_ms] into 20-30s segments using sorted VAD silence intervals `pauses_ms`. Returns [(start_ms, end_ms, own_start_ms, own_end_ms), ...]. """ segments = [] audio_start = 0 own_start = 0 while total_ms - audio_start > target_max: win_start = audio_start + target_min win_end = audio_start + target_max # Clip each silence interval to [win_start, win_end] so even a 40s hold-music silence # spanning across the whole window is recognized cleanly! best_span = None for p_start, p_end in pauses_ms: clipped_start = max(p_start, win_start) clipped_end = min(p_end, win_end) if clipped_end > clipped_start: if best_span is None or (clipped_end - clipped_start) > (best_span[1] - best_span[0]): best_span = (clipped_start, clipped_end) if best_span is not None: # Clean cut inside silence: zero overlap needed because nobody is speaking cut_ms = (best_span[0] + best_span[1]) // 2 segments.append((audio_start, cut_ms, own_start, cut_ms)) audio_start = cut_ms own_start = cut_ms else: # No pause found: overlap audio by `overlap` ms and split ownership at overlap midpoint next_audio_start = audio_start + target_max - overlap audio_end = audio_start + target_max own_boundary = next_audio_start + overlap // 2 segments.append((audio_start, audio_end, own_start, own_boundary)) audio_start = next_audio_start own_start = own_boundary segments.append((audio_start, total_ms, own_start, total_ms)) return segmentsInternal long silences (like 3 minutes of on-hold silence) are stripped on CPU before calling the GPU, saving massive GPU compute while storing an offset map to restore original wall-clock word timestamps.
- Exact
Deep dive 2: GPU-aware dynamic batching for variable-length audio
Standard GPU tensor batches must be rectangular, meaning every clip in a batch is zero-padded up to the longest clip in that batch. Grouping a
3 sclip with a30 sclip wastes 90% of the matrix multiplications on zeros for the short clip!Duration bucketing + audio-seconds batch budgets
Stage workers route each segment to a duration-specific queue (
0–5 s,5–10 s, ...,25–30 s) on the NVIDIA Triton inference server. Within each bucket, every clip differs in length by less than5 s:def duration_bucket(duration_s, width_s=5.0): """Map clip length in seconds to its 5-second bucket index (0..5 for <=30s clips).""" return int(duration_s // width_s) def padding_efficiency(batches): """Fraction of rectangular tensor compute spent on real audio vs. zero-padding.""" real_audio_s = sum(sum(batch) for batch in batches) padded_tensor_s = sum(len(batch) * max(batch) for batch in batches) return real_audio_s / padded_tensor_sSimulating 25,600 realistic segments (70% between
20–30 s, 30% between1–20 s, batch size 16) shows the jump immediately:Batching strategy Real-audio efficiency (100% = zero waste) ---------------------------------------------------- ----------------------------------------- Naive FIFO arrival order ~70.9% (~29% of GPU FLOPs wasted on zeros!) 5-second duration buckets (online + batch friendly) ~90.5% Windowed length-sort of 256 queued chunks (batch) ~96.1%Four complementary GPU optimizations push saturation even higher:
- Token / audio-second batch budgets: Cap batches at
480 audio-secondsrather than16 items— allowing sixteen30 schunks or ninety-six5 schunks in one pass! - Workload-specific queue delays: Interactive buckets wait at most
15 msto form a batch; batch buckets wait up to300 msto pack full tensors. - Mixed precision (
FP16/BF16): Halves activation and weight memory bandwidth versusFP32, roughly doubling max batch size on Tensor Core GPUs (INT8enabled per model/language only after passing WER regression gates). - Architecture-aware routing: Fixed-window encoders (like standard Whisper, which always pads inputs to
30 s) are fed packed25–30 sbatch segments, while short interactive clips use variable-length Conformer/transducer encoders (or ragged flash-attention kernels) and sticky stream-ID routing for stateful20 msstep-batching.
- Token / audio-second batch budgets: Cap batches at
Deep dive 3: Capacity isolation, GPU borrowing, and noisy-neighbor control
Why priority queues alone fail to protect the 2-second interactive SLA
GPU kernels are non-preemptible once launched: if an idle interactive GPU starts executing a massive
480 audio-secondbatch pass (480 / 200 RTFx = 2.4 secondsof uninterrupted GPU compute!), a live user arriving 10 ms later waits2.4 secondsin the queue before even starting — blowing the entire< 2.0 sSLA!We combine three mechanisms to achieve hard SLA isolation + high off-peak utilization:
- Dedicated interactive GPU pool (~490 GPUs at peak): Autoscaled on
active_streamsandinteractive_queue_wait_ms(never on GPU%, since we intentionally hold <= 65% utilization for tail-latency headroom), plus a small dedicated spot-GPU floor (~25 GPUs) so batch never stalls completely at peak. - Micro-budget batch borrowing on idle interactive GPUs: Off-peak, batch workers may submit tasks to interactive GPUs at Triton
priority = LOWonly wheninteractive_queue_depth == 0AND local utilization< 50%, with the batch budget clamped to<= 40 audio-seconds(40 / 200 = 200 msmax GPU kernel runtime). If an interactive request arrives 1 ms later, it jumps topriority = HIGHat the front of the queue and waits at most200 ms! - Drain-on-demand reclaim: When interactive traffic ramps up, the scheduler flips borrowed nodes to
interactive-only; in-flight200 msbatch passes finish naturally with zero wasted work.
Multi-tenant noisy-neighbor protection
- Batch fairness via Deficit Round Robin (DRR) in audio-seconds: Each tenant has its own logical queue; the dispatcher visits active tenants round-robin, granting each tenant a credit quantum of audio-seconds per round so a customer uploading 10,000 hours of archived lectures cannot delay another customer's single 30-minute consultation.
- Per-tenant interactive concurrency caps & poison-chunk quarantine: Enforce
max_concurrent_streamsat the WebSocket gateway (returning429withRetry-After), and quarantine any chunk that triggers 2 worker OOMs/crashes so malformed audio never crash-loops the fleet.
- Dedicated interactive GPU pool (~490 GPUs at peak): Autoscaled on
Deep dive 4: Calibrated quality gates and bounded fallbacks
After primary ASR finishes a chunk, a lightweight CPU evaluator computes fast confidence features from the primary output and audio stats:
- Mean token log-probability, minimum 3-gram log-probability, and fraction of tokens with
prob < 0.50. - Text
gzipcompression ratio (a high ratio like> 2.4reliably catches classic decoder repetition loops such as"thank you thank you thank you..."!). - Words-per-second ratio vs. speech duration, VAD speech fraction, language-ID entropy, and estimated SNR / overlapping-speaker ratio.
Calibrated gate and hard cost ceiling
A lightweight gradient-boosted tree (or logistic regression) — calibrated via Platt/isotonic scaling on human-labeled audit segments stratified across languages, accents, and noise levels — predicts
p_bad = P(segment WER > 20%):p_bad < threshold -> ACCEPT primary transcript immediately p_bad >= threshold (budget <= 10%) -> FALLBACK: route segment once to large ASR (or separation + ASR) after fallback (max 1 hop!) -> pick higher-scoring transcript; set low_confidence=true if still high- Why cap at 1 fallback hop: Making fallback a distinct
stagein the DAG prevents infinite retry loops. Thresholds are tuned offline on the Pareto curve of total WER reduction per fallback GPU-second. - Latency-guarded interactive fallback: Interactive
<= 60 sclips run synchronous fallback only if elapsed time so far leaves>= 800 msbefore the 2-second SLA; otherwise they return immediately withlow_confidence: true. - Online monitoring & A/B testing: Track fallback trigger rate by language/tenant (spikes signal upstream audio drift), user transcript-edit rate, and weekly human WER audits. A/B tests of new models or gate thresholds randomize by
job_idorsession_id(never per chunk, so speaker labels and vocabulary stay coherent within one recording).
- Mean token log-probability, minimum 3-gram log-probability, and fraction of tokens with
Bottlenecks, failure recovery, and summary of trade-offs
Scaling bottlenecks & straggler mitigation
- GPU cold starts during
:00/:30live-session surges: Pre-scale 5 minutes ahead of top-of-hour schedule boundaries, bake container images + model weights onto local NVMe snapshots so GPU boot loads weights at3–5 GB/sfrom disk instead of network pulls, and instantly evict borrowed batch tasks (< 200 msreclaim!). - PostgreSQL task-table growth:
~200 stage_runs/s(~600 writes/s) fits one primary + read replicas cleanly; partitionstage_runsdaily bycreated_atand drop partitions older than 30 days inO(1)metadata time (sharding bymedia_idhash if scale grows 10x). - Fan-in stragglers: Because final diarization clustering and sentence stitching wait for all 288 chunks of a 2-hour file, launch a speculative duplicate attempt for any tail chunk running
> 3xits duration bucket's p50 latency; our conditionalstatus <> 'done'commit safely takes whichever finishes first!
Granular failure-recovery matrix
Failure Mode Detection & Automatic Recovery ------------------------------------ ----------------------------------------------------------------- Worker dies mid-chunk Lease expires (~2x bucket p95); orchestrator re-queues ONLY that chunk with attempt + 1; finished chunks stay untouched. Slow "zombie" worker finishes late Writes to attempt_1.json; SQL CAS `status <> 'done'` updates 0 rows; committed attempt_2.json wins with zero corruption. Poison chunk crashes worker 3x Quarantined at attempt=3; job finishes 99.6% of transcript with an explicit `[unintelligible 14:20-14:45]` gap marker + error array. 2 hours of pure silence uploaded CPU VAD detects 0 speech intervals -> finishes in seconds, 0 GPU! Live WebSocket gateway pod restarts Client reconnects sending `last_final_seq` + rolling 5s local Opus ring buffer; new replica resumes seamlessly without dropped words.Summary of key trade-offs
- In-memory interactive pipeline vs. durable PostgreSQL DAG for batch: Spends zero database latency on
< 60 srequests that are cheap to retry whole, while guaranteeing chunk-level crash recovery on 2-hour recordings. - Headerless
16 kHzPCM (230 MB / 2h) vs. FLAC (~100 MB / 2h): Trades ~2x temporary object storage for exact32 * msbyte-range seeking and zero repeated CPU decoding across DAG stages. - Dedicated interactive GPU pool +
<= 200 msmicro-batch borrowing: Guarantees hard< 2 sinteractive SLAs while still letting batch soak up off-peak GPUs for nearly zero marginal hardware cost.
- GPU cold starts during
Intuition & how it works
Picture a hospital radiology department that handles both emergency-room trauma scans (live interactive requests needing answers in under 2 seconds) and thousands of routine annual checkup scans mailed in from clinics (2-hour asynchronous batch archives). Emergency patients walk straight into reserved express scanners with zero paperwork delay. Routine archive reels are sliced at natural quiet breaks into 25-second film strips, tagged with barcodes in a central locker room (object storage), sorted into trays of matching strip lengths so no scanner wastes time scanning blank film (duration bucketing), and fed into spare scanners using tiny 200-millisecond micro-batches whenever no emergency patient is waiting!
Why does a naive single-pipeline audio backend collapse at 50,000 hours/day and 10,000 concurrent live streams? First, passing 1.5 GB audio files through web servers or message brokers exhausts memory and network sockets immediately, and re-running a whole 2-hour recording from minute 0:00 whenever a spot GPU dies at minute 1:58 wastes hours of GPU work. Second, batching a 3-second clinician voice note alongside a 30-second lecture clip pads the 3-second clip with 27 seconds of zeros — burning 90% of its GPU matrix math on silence. Third, because a running GPU kernel cannot be paused mid-flight, letting a batch worker launch a 2.4-second mega-batch on a shared GPU instantly breaks the < 2.0-second interactive SLA for every live user arriving behind it.
Let's trace how a 90-second noisy customer-support recording and a live captioning stream move through the platform side by side:
1. Batch ingest & byte-seekable normalization (90 s stereo file):
-> Client uploads straight to S3 via presigned URL; CPU normalizer streams ffmpeg into headerless
16 kHz mono 16-bit PCM (`32 bytes/ms` -> 2.88 MB total) in S3.
-> CPU VAD finds silences at 24.0s, 51.5s, and none near 80s -> creates 4 deterministic segments:
Seg 0: [0..24,000 ms], Seg 1: [24,000..51,500 ms],
Seg 2: [51,500..81,500 ms, owns 51,500..81,000], Seg 3: [80,500..90,000 ms, owns 81,000..90,000].
2. GPU execution, crash recovery & quality gate:
-> Stage worker fetches Seg 1's exact 880 KB slice via HTTP `Range: bytes=768000-1647999`, places it
in the `25-30s` Triton duration bucket (~90.5% non-padding efficiency!).
-> Worker dies mid-Seg 2! Lease expires; replacement worker retries ONLY Seg 2 (Segs 0,1,3 untouched).
-> Seg 3 has heavy crosstalk -> quality gate scores `p_bad = 0.62 >= 0.35` -> triggers 1 fallback pass
through voice separation + large ASR -> global speaker clustering stitches final transcript!
3. Concurrent live stream arrives on an interactive GPU currently borrowed by batch:
-> Borrowed batch runs <= 40 audio-s micro-batches (~200 ms max GPU pass).
-> Live stream frame jumps to HIGH priority, waits 110 ms for in-flight micro-batch, and streams
partial words well inside its sub-second budget!
Key trade-offs
- Dedicated interactive GPU pool + micro-budget borrowing vs. one shared priority pool. Separate pools guarantee SLAs at the price of ~300+ GPUs sitting idle overnight, whereas a pure priority queue fails because GPU kernels are non-preemptible once launched (a
480 audio-secondbatch takes ~2.4 sat200xRTFx — audio-seconds processed per GPU-second — blowing a2 sSLA by itself!). Reserving an interactive pool and letting batch borrow idle GPUs with a strict<= 40 audio-second(~200 ms) micro-batch cap gets hard SLA protection and free off-peak batch compute. - In-memory interactive execution vs. durable DAG checkpoints for batch. Writing a PostgreSQL row before and after every stage in a DAG (Directed Acyclic Graph, a multi-stage dependency pipeline) gives chunk-level crash recovery for 2-hour files, whereas skipping durable orchestration on
<= 60 sinteractive clips saves tens of milliseconds of database latency on work that is cheap to retry end-to-end. - Headerless
16 kHzuncompressed PCM (32 KB/s) vs. compressed FLAC (~14 KB/s). Storing normalized internal audio as raws16lePCM uses ~2x more temporary S3 storage than FLAC, in exchange for exactbyte_offset = 32 * start_msHTTPRangereads — letting hundreds of downstream GPU workers fetch single960 KBchunks with zero full-file downloads and zero repeated decompression. - Silence-aligned
20–30 schunks vs. tiny5 schunks.20–30 ssegments match standard speech-encoder windows (such as Whisper's 30 s encoder), cut boundary errors by 5x, and keep PostgreSQL orchestration down to~200 stage_runs/s; shorter chunks would parallelize a single file faster at the cost of acoustic context loss and database write amplification. - Duration bucketing width and max queue wait. Narrow
5 sbuckets boost real-audio tensor efficiency from~71%to~90.5%(and~96%with windowed sorting on batch backlogs), trading a tiny bucket-fill wait (<= 15 msinteractive,<= 300 msbatch) for ~30% more usable GPU capacity. - Calibrated quality-gate threshold (
p_bad) vs. running the largest model everywhere. Routing only the hardest10%of segments to a4xheavier fallback model captures most of the accuracy gain of the giant model at a fraction of its fleet cost, in exchange for maintaining human-audited calibration labels.
Common mistakes
- Streaming heavy audio bytes through API servers, Kafka messages, or the DAG orchestrator instead of uploading straight to object storage via presigned URLs (temporary signed upload links) and passing tiny
(uri, byte_offset, byte_len)pointers. - Decoding an entire
1.5 GBfile intofloat32RAM at once (~3 GB per worker) or hardcoding a44-byteWAV header offset (which silently corrupts audio wheneverffmpegor encoders embed variable-length metadata headers). - Cutting chunks at blind
30.0 sclock marks instead of VAD (Voice Activity Detection) silences, slicing words in half without acoustic overlap or midpoint ownership deduplication. - Batching variable-length audio in FIFO arrival order, wasting ~30–80% of GPU FLOPs multiplying zero-padding tokens, or feeding
4 sclips into a fixed-window30 sWhisper encoder. - Autoscaling the interactive GPU pool on GPU utilization %, missing that tail queueing latency spikes past 2 seconds long before average GPU utilization reaches 85%; always scale interactive pools on
active_streamsandqueue_wait_ms. - Re-running a 2-hour job from scratch on single-worker failure, or retrying chunks without fenced leases and atomic SQL Compare-And-Swap (
WHERE status <> 'done'), allowing slow zombie workers to overwrite finished files or double-bill customers. - Trusting chunk-local speaker IDs globally, forgetting that
"SPEAKER_00"in Chunk 4 and"SPEAKER_00"in Chunk 5 are arbitrary local cluster labels until speaker embeddings are clustered across the entire recording! - Allowing unbounded fallback loops where a noisy segment repeatedly triggers fallbacks instead of enforcing a hard 1-hop DAG transition.
Follow-up questions
- When audio clips arrive with widely different lengths, how can you batch them on GPUs without burning most of your compute on padding zeros? Route chunks into fine-grained duration buckets (for example
0–5 s,5–10 s, ...,25–30 s) before they enter the inference server's dynamic batcher so every sequence in a rectangular tensor is padded by less than5 s(raising real-audio efficiency from~71%to~90.5%), and size batches by a total audio-seconds budget (such as480 audio-s) rather than a fixed clip count so short buckets pack larger batches. For asynchronous batch queues where a 500 ms wait is invisible, sort each sliding window of ~256 queued chunks by exact duration before slicing batches (~96% efficiency). At the model kernel level, use variable-length Conformer/transducer architectures with ragged / packed flash-attention tensors (concatenating unpadded sequences end-to-end with block-diagonal attention masks) to eliminate zero-padding FLOPs almost completely! - How do you prevent clipped words and inconsistent speaker labels at chunk boundaries when splitting long recordings? Primary chunk boundaries are placed at the midpoint of the longest VAD silence inside each
20–30 swindow, so >95% of cuts fall in clean pauses between phrases rather than mid-word or mid-turn. Whenever continuous speech forces a hard cut, adjacent segments include1–2 secondsof overlapping audio on both sides while owning strictly disjoint intervals[own_start_ms, own_end_ms)split at the overlap midpoint — giving both decoders>= 500 msof left and right acoustic context while keeping each word once based on whether its timestamp midpoint falls inside the segment's owned interval. For speaker transitions, chunks output local frame-level speaker embeddings (voiceprint vectors) rather than final speaker numbers; a lightweight job-level fan-in stage clusters those embeddings globally across the whole file (using overlapping regions as cross-chunk consistency anchors), and punctuation plus translation run after stitching on complete reconstructed sentences. - When live traffic surges abruptly, how do you hide or minimize GPU worker cold-start delays while new capacity boots? Combine four layers from fastest (milliseconds) to slowest (minutes): first, keep instant reclaimable buffer capacity by running batch tasks on idle interactive GPUs in
<= 200 msmicro-batches that drain within 0.2 seconds the instant live streams arrive. Second, maintain ~35% warm headroom (65%target utilization) and pre-scale on a schedule 5 minutes before:00and:30clock boundaries when scheduled live sessions surge predictably. Third, cut VM and container startup from minutes to ~15–20 seconds by maintaining a small warm pool of pre-initialized GPU nodes and baking container layers plusFP16TensorRT engine weights onto local NVMe disk snapshots (loading weights via pinned-memory DMA straight into VRAM without network downloads). Finally, if an unpredicted spike still outpaces node boot times, shed load gracefully in stages — skip optional interactive fallback first, defer live voice separation second, and enforce per-tenant concurrent-stream quotas (429withRetry-After) so admitted live sessions never violate their< 2 sSLA.
Follow-up questions
- When audio clips arrive with widely different lengths, how can you batch them on GPUs without burning most of your compute on padding zeros?
- How do you prevent clipped words and inconsistent speaker labels at chunk boundaries when splitting long recordings?
- When live traffic surges abruptly, how do you hide or minimize GPU worker cold-start delays while new capacity boots?
Similar questions
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture
- Local Document RAG CLI and Streaming Service with Mistral
- Greenfield Recommendation Engine and Grounded Discovery Assistant