HIPAA-Compliant Clinical Audio Transcription Pipeline
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect the cloud backend for a clinical documentation platform that captures, transcribes, and serves audio from doctor-patient encounters. Clinicians record visits on a mobile companion app over unreliable hospital Wi-Fi and cellular networks (for instance, Dr. Lin uploading a 20-minute 9.6 MB cardiology consultation while walking between exam rooms and elevators). Each uploaded recording is processed through an external Speech-to-Text (STT) provider and stored so authorized care-team members can review the resulting clinical transcript.
Your design must satisfy four core system guarantees on standard public cloud infrastructure (such as AWS or GCP):
- Regulatory Security (HIPAA): Protect all Protected Health Information (PHI) with encryption in transit and at rest, strict per-tenant and role-based authorization, PHI isolation from operational telemetry, and immutable audit trails.
- High Ingestion Concurrency: Sustain up to
5,000simultaneous mobile uploads during peak daytime clinic traffic. - Fault-Tolerant Processing: Absorb transient outages, rate limits, or failures from the third-party STT provider via durable retries with zero lost recordings.
- Split Retention Lifecycle: Permanently erase raw audio once a configurable retention window expires, while preserving clinical transcripts indefinitely.
Scope & Expectations
- End-to-End Ingestion & Data Flow: Trace how recorded audio travels reliably from a mobile device with intermittent connectivity into durable storage, through external transcription, and back to clinical reviewers.
- Core API & State Model: Define REST endpoints, idempotency semantics, and lifecycle states for resumable uploads, progress checks, playback, and transcript retrieval.
- Asynchronous Job Orchestration: Show how background queues, workers, and reconciliation decouple slow external STT jobs from user-facing APIs without dropping work.
- HIPAA Security & Lifecycle Controls: Detail key management, access enforcement, PHI-free logging/metrics, audit retention, and safe automated audio deletion.
Step-by-step walkthrough
Clarify requirements and scope
Three constraints make this problem much more interesting than a generic file-upload pipeline: 1. Every recording and transcript is PHI (Protected Health Information) — identifiable patient medical data regulated under HIPAA (the US federal law governing healthcare data security, access control, and auditability). 2. Uploads originate from physicians' phones moving between exam rooms, elevators, and garages with flaky cellular and Wi-Fi links. 3. The slowest, least predictable component is an external third-party Speech-to-Text (STT) vendor that we do not control.
Functional requirements
- Clinicians capture encounter audio on mobile devices and upload recordings reliably, resuming seamlessly across dropped connections.
- The backend asynchronously processes each uploaded recording through an external STT vendor and persists the structured transcript.
- Authorized care-team members inspect job progress, review transcripts, and (prior to purge) stream source audio for verification.
- Source audio files are automatically erased once their configured retention window elapses, while generated clinical transcripts remain archived permanently.
- Clinicians can trigger a fresh transcription pass when a draft mishears medical terminology, provided the source recording is still within its retention window.
Non-functional requirements
- HIPAA compliance: TLS encryption in transit, encryption at rest, least-privilege access control, and a tamper-evident audit trail for every PHI touch. Every vendor handling PHI (cloud host and STT provider) must sign a BAA (Business Associate Agreement) — a legally binding HIPAA contract forbidding unauthorized access, retention, or model training on patient data.
- Concurrency target: handle 5,000 simultaneous active uploads during busy daytime clinic windows.
- Zero data loss: never drop an encounter recording, even if an API pod crashes mid-request or the external STT provider suffers a multi-hour outage.
- Turnaround SLA (assumed): transcript ready within 5 minutes (
p95) of upload completion when the STT vendor is healthy. - Zero PHI leakage: patient names, audio URLs, and transcript text must never appear in application logs, metrics, traces, queue payloads, or push notifications.
Explicit assumptions
Parameter Assumption used below Consultation length 15 minutes average (up to 60 minutes max) Mobile audio encoding Mono AAC at 64 kbps ( 8,000 bytes/s), compressed on the phoneDaily volume 200,000 consultations/day across health-system tenants ( org_id); peak hour carries 15% (30,000visits)Audio retention 30 days (configurable per org_id), never purged before a valid transcript is savedCloud mapping AWS service names shown below (S3, SQS, KMS, RDS Postgres); GCP equivalents map 1-to-1 (GCS, Cloud Tasks/PubSub, Cloud KMS, Cloud SQL) Back-of-the-envelope numbers
Running the numbers first shows why connection concurrency and vendor job quota — not raw network bandwidth or database TPS — drive the architecture.
1. File sizes 15-min visit (average) 8,000 B/s x 900 s = 7.2 MB 60-min visit (maximum) 8,000 B/s x 3,600 s = 28.8 MB 2. Peak upload traffic and Little's Law Peak-hour completions 15% x 200,000 = 30,000 uploads/hour Peak arrival rate (lambda) 30,000 / 3,600 s = ~8.33 completed uploads/s Concurrent sessions (L) 5,000 concurrent uploads (given) By Little's Law (L = lambda x W, where W is average session duration): W = 5,000 / 8.33/s = ~600 s (~10 minutes per upload session!) Peak ingress bandwidth 8.33/s x 7.2 MB = ~60 MB/s (~480 Mbps) 3. Storage footprint Daily raw audio 200,000 x 7.2 MB = 1.44 TB/day 30-day retained audio 1.44 TB/day x 30 days = ~43.2 TB live (vs. ~526 TB/yr without purge) Transcript JSON ~2,000 words + word timestamps/confidence = ~150 KB raw per visit Transcript growth 200,000 x 150 KB = 30 GB/day = ~11 TB/year raw (~2.5 TB/year compressed) 4. Third-party STT workload Daily audio hours 200,000 x 0.25 hours = 50,000 audio-hours/day Suppose 15 min of audio takes ~120 s for the STT vendor to process: In-flight STT jobs at peak 8.33 jobs/s x 120 s = ~1,000 concurrent vendor jobsThree concrete lessons jump out from this math: - Offload bytes from app servers: 480 Mbps is modest bandwidth, but holding 5,000 slow, stalled mobile sockets open for 10 minutes each wastes application server memory and file descriptors. Clients should upload directly to object storage via pre-signed URLs. - Size vendor quota + queue buffer together: if our STT vendor contract caps us at 500 concurrent jobs (
500 / 120 s = 4.17 jobs/s), the peak hour builds a(8.33 - 4.17) x 3,600 = 15,000-jobbacklog that takes an extra hour to drain — blowing our 5-minute SLA. Meetingp95 < 5 minrequires negotiating>= 1,200concurrent vendor slots (or load-sharing across two BAA vendors) while keeping a durable queue for bursts and outages. - Keep transcript bodies out of Postgres:~8.3metadata writes/s is tiny for one primary + replica Postgres instance, whereas storing~11 TB/yearof JSON blobs forever belongs in object storage, with Postgres storing only compact metadata pointers.API design
Every client call runs over TLS 1.3 with an OIDC (OpenID Connect) bearer token issued via the hospital's identity provider. Resource IDs are random UUIDv4 values containing zero patient information. Write endpoints accept an
Idempotency-Key(a UUID generated on the phone when recording starts) so retrying a dropped request returns the existing record rather than creating duplicates.1. Initiate resumable multipart upload POST /v1/recordings Headers: Authorization: Bearer <jwt>, Idempotency-Key: <client_recording_uuid> Body: { "encounter_id": "enc_44b2...", "duration_s": 1200, "size_bytes": 9600000, "content_type": "audio/mp4", "sha256_base64": "..." } -> 201 Created { "recording_id": "rec_8d2a...", "upload": { "part_size_bytes": 5242880, "parts": [ { "part_number": 1, "put_url": "https://...", "expires_at": "..." }, { "part_number": 2, "put_url": "https://...", "expires_at": "..." } ] } } 2. Check received parts & mint fresh pre-signed URLs after a connection drop GET /v1/recordings/{id}/upload -> 200 { "received_parts": [1], "missing_parts": [2] } POST /v1/recordings/{id}/upload/part-urls Body: { "part_numbers": [2] } -> 200 { "parts": [ { "part_number": 2, "put_url": "..." } ] } 3. Complete upload and enqueue transcription (idempotent) POST /v1/recordings/{id}/upload/complete Body: { "parts": [ { "part_number": 1, "etag": "...", "sha256_base64": "..." }, { "part_number": 2, "etag": "...", "sha256_base64": "..." } ] } -> 202 Accepted { "recording_id": "rec_8d2a...", "status": "UPLOADED" } 4. Status checking, clinical retrieval (audited), and re-processing GET /v1/recordings/{id} -> 200 { "status": "TRANSCRIBED", "current_transcript_version": 1, "updated_at": "..." } GET /v1/recordings/{id}/transcript?version=1 -> 200 { "version": 1, "source": "machine", "quality": { "mean_confidence": 0.94, "low_confidence_ratio": 0.03 }, "segments": [ { "start_ms": 0, "end_ms": 4210, "speaker": "S1", "text": "...", "confidence": 0.95 } ] } GET /v1/recordings/{id}/audio-url -> 200 { "play_url": "https://...", "expires_in_s": 300 } (returns 410 Gone after 30-day purge) POST /v1/recordings/{id}/transcriptions Body: { "reason": "low_accuracy_medical_terms" } -> 202 Accepted { "job_id": "job_..." } 5. Internal vendor webhook (authenticated via HMAC signature + mutual TLS / IP allowlist) POST /internal/stt/{vendor}/webhook -> 202 Accepted (enqueues job_id only; never blocks)When transcription finishes, the backend sends a PHI-free push notification (
"A clinical transcript is ready for review") so the mobile app wakes up and fetches the transcript without aggressive background polling, keepingGET /v1/recordings/{id}as a clean fallback.Data model and recording state machine
Postgres stores operational state, authorization keys, and pointers, while encrypted audio and transcript blobs live in private S3 buckets.
recordings recording_id UUID PK org_id UUID, physician_id UUID, encounter_id UUID client_recording_id UUID UNIQUE (org_id, physician_id, client_recording_id) audio_key TEXT "audio/<org_uuid>/<recording_uuid>.m4a" (opaque UUIDs only!) s3_upload_id TEXT, size_bytes BIGINT, sha256 BYTEA, duration_s INT status TEXT CREATED | UPLOADING | UPLOADED | QUEUED | TRANSCRIBING | TRANSCRIBED | FAILED | AUDIO_PURGED current_transcript_version INT NULL, legal_hold BOOL DEFAULT FALSE created_at, uploaded_at, transcribed_at, audio_purge_after, audio_purged_at transcription_jobs job_id UUID PK, recording_id UUID FK, attempt INT, priority TEXT (HIGH | LOW) vendor TEXT, vendor_job_id TEXT, UNIQUE (vendor, vendor_job_id) status TEXT QUEUED | SUBMITTED | COMPLETED | FAILED_RETRYABLE | FAILED_PERMANENT next_attempt_at TIMESTAMP, error_code TEXT (strict enum, never raw vendor error strings!) requested_by UUID, reason TEXT, created_at, completed_at transcripts (recording_id, version) PK job_id UUID FK, source TEXT (MACHINE | PHYSICIAN_EDIT) body_key TEXT "transcripts/<org_uuid>/<recording_uuid>/v<version>.json.zst.enc" mean_confidence FLOAT, low_conf_ratio FLOAT, words_per_min FLOAT, coverage_ratio FLOAT created_by UUID, created_at TIMESTAMP outbox(outbox_id BIGSERIAL PK, queue_name TEXT, payload_json JSONB, created_at, published_at) audit_events(event_id UUID PK, ts TIMESTAMP, org_id UUID, actor_id UUID, actor_role TEXT, action TEXT, resource_type TEXT, resource_id UUID, result TEXT, source_ip INET, req_id UUID)Recording lifecycle state machine
CREATED --> UPLOADING --> UPLOADED --> QUEUED --> TRANSCRIBING --> TRANSCRIBED --> (30d) AUDIO_PURGED ^ | +-- backoff --+ (transient 429 / 5xx / timeout) | +--> FAILED (corrupt audio or >10 attempts; audio purge stays blocked!)Every status change uses a compare-and-set update (
UPDATE recordings SET status = 'TRANSCRIBING' WHERE recording_id = $1 AND status = 'QUEUED'), guaranteeing that duplicate queue deliveries or retried webhooks become harmless no-ops. Transcripts are append-only by version (v1,v2, ...) so re-processing or physician edits never overwrite clinical history.High-level architecture and end-to-end data flow
All components touching PHI run inside a dedicated, network-isolated PHI cloud account and private VPC, strictly separated from the Non-PHI observability stack.
[Physician Mobile App] PHI Zone (Dedicated Cloud Account / Private VPC) (Keychain-encrypted local file) +------------------------------------------------------------------+ | | | | 1. POST /recordings (OIDC) | [API Gateway + WAF] ---> [Stateless Recording API] | |-----------------------------------+-------------------------> | 1. Authz + mint part URLs | | 2. PUT 5 MiB parts (HTTPS) | | 3. Complete + atomic DB tx: | |-----------------------------------+--> [Audio S3 Bucket] | (status=UPLOADED + outbox row) | | | (SSE-KMS per org_id) v | | | [RDS Postgres (RLS enabled)] | | | | 4. Outbox relay | | | v | | | [SQS: transcribe-high / low] ---> [DLQ] | | | | | | | v | | | [Dispatcher Workers] | | | 5. Verify whole-file SHA-256, | | | check quota & circuit breaker, | | | stream audio over TLS 1.3 -----------+ | | | | | | | [Result Workers] <-- [SQS: stt-results] <-- [Webhook API] <--+-+--> [STT Vendor] | | 7. Fetch, score, compress + envelope-encrypt, | (Signed BAA, | 8. PHI-free push -> GET transcript| save to [Transcript S3 Bucket], call vendor DELETE | zero-retain) |<----------------------------------+ | | [5-min Reconciler] [Daily Safe Audio Purger] [WORM Audit S3] | +------------------------------------------------------------------+ | (scrubbed structured metrics & allowlist logs only) v Non-PHI Zone: Prometheus / Grafana / PagerDuty / Scrubbed LogsNotice step 5: rather than handing the external STT vendor a pre-signed URL into our PHI S3 bucket, dispatcher workers stream the 7.2 MB object inside the VPC once to verify its assembled SHA-256 against the phone's original hash and stream those bytes directly over TLS 1.3 to the vendor (
60 MB/saggregate across the worker pool is trivial), keeping our S3 bucket completely unreachable from third-party networks.Deep dive 1: Resumable uploads from flaky phones at 5,000 concurrency
Why pre-signed multipart uploads solve both scale and intermittent connectivity A pre-signed URL is a short-lived URL signed by our backend's IAM credentials granting temporary permission (5 minutes) to upload one specific part of one specific S3 object key. Combined with S3 Multipart Upload (splitting a file into independent parts uploaded in any order and stitched together by S3 at the end): - Chunk math: S3's minimum multipart chunk size (except the final chunk) is
5 MiB(5,242,880 B, or~5.24 MB). An average7.2 MBvisit splits into 2 parts (5.24 MB + 1.96 MB), Dr. Lin's 20-minute9.6 MBcardiology visit (rec_8d2a) splits into 2 parts (5.24 MB + 4.36 MB), and a maximum 60-minute28.8 MBconsultation splits into 6 parts (5 x 5.24 MB + 2.60 MB). - Cheap resume after Wi-Fi drops: eachPUTincludes anx-amz-checksum-sha256header verified by S3 on arrival. If an elevator cuts cellular mid-way through Part 2, Part 1 remains safely stored in S3. When signal returns, the app callsGET /v1/recordings/{id}/upload, seesreceived_parts: [1], fetches a fresh 5-minute URL for Part 2, and uploads only the remaining4.36 MB. - Orphan cleanup: an S3 lifecycle rule automatically aborts incomplete multipart uploads older than 7 days so abandoned PHI fragments never accumulate silently.Mobile client durability rules - Write audio on the phone directly into an encrypted file protected by iOS Data Protection / Android Keystore. - Schedule uploads through OS-managed background transfer daemons (iOS background
URLSession, AndroidWorkManager) so transfers survive app backgrounding and network switches. - Never delete the phone's local copy on202 Acceptedalone: delete it only onceGET /v1/recordings/{id}advances toTRANSCRIBINGorTRANSCRIBED, proving the dispatcher verified the assembled S3 object's whole-file SHA-256.Deep dive 2: Asynchronous transcription, transactional outbox, and vendor resilience
Zero blocked worker threads: a dispatcher worker never sits idle waiting 2 minutes for transcription. It streams the audio, stores
vendor_job_id, marksTRANSCRIBING, and immediately moves to the next message. Completion arrives asynchronously via the vendor's HMAC-signed webhook (which immediately pushes{vendor, vendor_job_id}ontostt-resultsSQS and returns202in< 20 ms).Closing the crash gap between Postgres and SQS (Transactional Outbox)
Without outbox (BUG): 1. Commit status=UPLOADED in DB --[API crashes here!]--> 2. Never sent to SQS! With outbox (SAFE): 1. Single DB transaction commits BOTH status=UPLOADED AND row in outbox table 2. Outbox relay reads unpublished rows -> pushes {recording_id, job_id} to SQS -> marks published_at (safe if sent twice due to CAS state transitions!)Postgres as authority + 5-minute Reconciler: queues can delay messages and webhooks can get lost across the internet. Every 5 minutes, a background reconciler queries Postgres for stuck states: -
UPLOADINGwhere S3HeadObjectshows the completed file already exists (API crashed right afterCompleteMultipartUploadbefore DB commit) -> advance toUPLOADED+ enqueue. -UPLOADEDfor> 5 min-> re-publish to SQS. -TRANSCRIBINGfor> 6 min(3x normal 2-min runtime) -> poll the vendor'sGET /jobs/{vendor_job_id}endpoint directly in case their webhook dropped.Retries, idempotency, and outage protection - Vendor idempotency: send
Idempotency-Key: <job_id>:<attempt>on submission, and persistvendor_job_idbefore deleting the SQS message so retries never double-bill or emit duplicate transcripts. - Error classification:429 Too Many Requests,5xx, and network timeouts trigger exponential backoff with jitter (30 s, 1 m, 2 m, ..., capped at 30 m). Corrupt or 0-second audio is markedFAILED_PERMANENTimmediately. After 10 failed attempts, route to a DLQ (dead-letter queue), page on-call, and keepaudio_purge_afterlocked so raw audio is never deleted before recovery. - Quota semaphore + circuit breaker: cap in-flight vendor jobs at our contracted concurrency via a shared semaphore so clinic rushes wait cleanly in SQS instead of triggering429storms. If> 50%of submissions fail over a 60-second window, trip a circuit breaker (pausing dispatches for 30-second health probes). Crucially, jobs paused behind an open circuit do not incrementattempt, so a 4-hour vendor outage delays transcripts without exhausting the 10-retry cap! Optional failover routes newHIGH-priority clinic uploads to a secondary BAA STT vendor if the circuit stays open> 15 minutes, whileLOW-priority re-transcriptions wait off-peak.Deep dive 3: Security architecture, PHI segregation, log hygiene, and lifecycle
Layered encryption and crypto-shredding - In transit: TLS 1.3 on all external edges (
aws:SecureTransport = false -> Denyon all S3 buckets), mutual TLS inside the VPC, and private VPC endpoints for S3, SQS, and KMS so internal traffic never traverses the public internet. - At rest (per-tenant KMS + envelope encryption): - Audio bucket uses SSE-KMS with a dedicated customer-managed KMS (Key Management Service) key per health-system tenant (org_id), with S3 Bucket Keys enabled to cut KMS API volume by ~99%. - Result workers compress each transcript (zstd/gzipfirst, since encrypted bytes look random and cannot compress) and apply envelope encryption (encrypting the compressed JSON with a unique 256-bit data key, then encrypting that data key under the tenant's KMS key). Even a leaked S3 backup or rogue storage admin sees only ciphertext. - Per-tenant KMS keys unlock crypto-shredding: if a hospital terminates its contract, scheduling deletion of its KMS key renders every historical backup and DR replica of its audio and transcripts mathematically unreadable.Identity, object-level authorization, and the S3 VPC-endpoint trap - Every API request verifies
token.org_id == recording.org_idAND checks clinical relationship (authoring physician, care-team member onencounter_id, or authorized supervisor), backed by Postgres row-level security (RLS) (CREATE POLICY tenant_isolation ON recordings USING (org_id = current_setting('app.org_id')::uuid)) so a missingWHEREclause cannot leak cross-tenant rows. - Crucial S3 bucket policy detail: a common mistake is putting a blanketDeny if aws:sourceVpce != vpce-xxxpolicy on the audio bucket — which breaks every mobile upload, because pre-signedPUTrequests arrive directly from clinic Wi-Fi/cellular over the public internet! Instead, split IAM roles: 1.WorkerRole(dispatchers/purger): allowedGetObject/DeleteObjectonly whenaws:sourceVpce == vpce-xxx. 2.PresignedSignerRole(Recording API): permitted onlyPutObject/UploadPartonaudio/*andGetObjectfor playback over TLS (aws:SecureTransport == true), neverListBucketorDeleteObject.Keeping telemetry and logs 100% free of patient data - Opaque keys everywhere: S3 keys (
audio/<org_uuid>/<rec_uuid>.m4a), URLs, and SQS payloads ({recording_id, job_id}) contain zero patient names, MRNs, or dates of birth. - Strict allowlist structured logging: application loggers serialize only explicitly allowlisted keys (recording_id,job_id,org_id,status,duration_ms,error_code), stripping HTTP query strings at the load balancer/gateway so pre-signed URL signatures are never written to access logs, and mapping raw STT vendor error messages into fixed internal enums (VENDOR_TIMEOUT,UNSUPPORTED_CODEC). - Low-cardinality metrics & scrubbed mobile telemetry: Prometheus metrics label only by(vendor, status, org_tier), never patient or encounter IDs; mobile crash SDKs strip payloads and sit under a BAA; a streaming DLP regex/NER scanner watches log pipelines as defense-in-depth.Data lifecycle: 6-year audit, 30-day audio purge, forever transcripts - Immutable HIPAA audit log: every transcript read, audio playback URL mint, re-transcription, and purge writes who, what, purpose, IP, and timestamp to an append-only table mirrored to S3 Object Lock (WORM) retained for 6 years (matching HIPAA's 6-year documentation rule). - Safe daily audio purge: a daily job queries
audio_purge_after < now() AND status = 'TRANSCRIBED' AND NOT legal_hold, deletes the S3 object, recordsAUDIO_PURGED, and audits the deletion. Because the bucket is versioned against accidental overwrites, configure aNoncurrentVersionExpiration(e.g., 1 day) rule on both primary and DR buckets so deleted audio bytes are truly erased rather than lingering forever behind delete markers! - Vendor zero-retention: require zero-data-retention and no-model-training in the STT vendor's BAA, and explicitly call the vendor'sDELETE /jobs/{vendor_job_id}endpoint inside the result worker as soon as the transcript is saved.Bottlenecks, failure handling, and summary of trade-offs
Scaling & bottleneck summary
Component Peak load Scaling & bottleneck strategy Recording API ~8.3 creates/s, ~8.3 completes/s Stateless containers; CPU-light because bytes bypass it via pre-signed URLs S3 Audio & Transcript buckets 5,000 open uploads ( 60 MB/s);+2.5 TB/yrcompressed transcriptsS3 scales horizontally across UUID prefixes without pre-provisioning RDS Postgres ~50 writes/s, ~300 reads/s Single primary + read replica + monthly partitioning on audit_eventsThird-party STT vendor ~1,000 concurrent jobs ( 50K audio-hrs/day)Primary bottleneck: contract >= 1,200concurrency, semaphore-gate dispatches, add secondary BAA vendor failoverFailure modes and recovery
Failure scenario System response Data lost? Clinic Wi-Fi drops mid-upload Phone keeps encrypted local copy, queries /upload, uploads only missing 5 MiB partsNone API crashes right after S3 multipart complete before DB commit Outbox + status weren't committed together; retry or 5-min reconciler spots object in S3 and advances to UPLOADEDNone STT vendor suffers 3-hour outage Circuit breaker opens without burning retry attempts; SQS buffers backlog; optional failover to Vendor B after 15 min None (delayed only) Vendor webhook lost in transit 5-min reconciler polls vendor API for jobs stuck in TRANSCRIBING > 6 minNone Duplicate SQS message or webhook WHERE status = <expected>CAS update +UNIQUE (vendor, vendor_job_id)turn duplicates into no-opsNone Core trade-offs - Pre-signed multipart S3 uploads vs. API proxying: offloads 5,000 ten-minute mobile sockets from app servers and gives cheap chunk resume, requiring short-lived (5-min) scoped URLs and query-string stripping in access logs. - Webhook-driven async queue + transactional outbox vs. synchronous STT: eliminates blocked worker threads and survives multi-hour vendor outages with zero lost visits, adding state-machine and reconciler machinery. - Envelope-encrypted transcripts in S3 vs. Postgres text columns: keeps Postgres tiny and unlocks per-tenant crypto-shredding, trading away native SQL
LIKE/full-text search over transcripts. - 30-day gated audio purge vs. indefinite audio storage: shrinks live PHI footprint from~526 TB/yrgrowth to a flat~43 TBcap, trading away the ability to re-transcribe visits older than 30 days.
Intuition & how it works
Think of a hospital dictation drop-off center built for 5,000 busy doctors walking through exam rooms and elevators with spotty reception. If every doctor had to stand at one receptionist's window slowly reading a 15-minute tape aloud while that receptionist stayed on hold with an outside typing agency, the lobby would jam instantly and every dropped phone call would force the doctor to start over. Instead, the receptionist checks the doctor's badge in milliseconds and hands back temporary 5-minute locker passes (pre-signed URLs — short-lived, cryptographically signed links granting upload access to one exact storage path) so the phone slides 5 MiB tape chunks directly into a locked vault (object storage). Once all chunks arrive, an internal clerk drops a ticket containing only a random locker UUID (zero patient names) into a durable work bin (message queue), and background couriers stream recordings to the typing agency (Speech-to-Text / STT vendor), retrying patiently if the agency goes offline.
A naive synchronous design — POST /upload streaming raw audio through application servers and awaiting the STT response in the same HTTP request — breaks every requirement at once. By Little's Law (concurrent_uploads = arrival_rate x average_duration), 8.33 uploads/s taking ~10 minutes on flaky clinic networks holds 5,000 concurrent sockets open on app servers, and any connection drop wastes the entire upload. Calling a 2-minute external STT job synchronously pins thousands of worker threads and loses PHI (Protected Health Information — identifiable patient medical data regulated by HIPAA) whenever the vendor returns 503. Finally, logging default HTTP URLs, request bodies, or raw vendor errors leaks patient details into developer dashboards.
Trace Dr. Lin's 20-minute (9.6 MB) cardiology consultation rec_8d2a across an elevator Wi-Fi drop and a brief STT vendor brownout:
1. Chunk upload: Phone calls POST /v1/recordings -> gets 2 pre-signed part URLs (5.24 MB + 4.36 MB).
Part 1 succeeds; Wi-Fi drops in the elevator during Part 2; phone resumes ONLY Part 2.
2. Atomic enqueue: Phone calls /complete -> API finishes S3 multipart upload and, in ONE Postgres transaction,
writes status=UPLOADED + an outbox row. Relay pushes {rec_8d2a, job_1} (no PHI) to SQS.
3. Resilient STT: Dispatcher verifies whole-file SHA-256 and streams audio to STT vendor -> gets 503 ->
backs off 30 s -> Attempt 2 succeeds -> vendor calls signed webhook -> Transcript v1 saved
compressed + envelope-encrypted in S3, and vendor's copy is deleted immediately.
4. Lifecycle: Phone sees status=TRANSCRIBED and deletes its local copy; at Day 30 (with no legal hold),
the daily purger erases the raw audio + S3 version while keeping Transcript v1 forever.
Key trade-offs
- Direct-to-storage pre-signed multipart uploads vs. proxying bytes through the API. Pre-signed S3 multipart uploads keep 5,000 slow, 10-minute mobile connections (
~60 MB/s) off our API fleet and let phones resume failed 5 MiB chunks cleanly. Because a pre-signed URL acts as a temporary bearer token, we trade away central byte inspection during upload: we must authorize the user before minting the URL, cap expiry to 5 minutes, strip query strings from access logs, and verify the whole-file SHA-256 in the dispatcher worker before transcription. - Webhook-driven asynchronous queue vs. synchronous transcription. Submitting a job and releasing the worker immediately means 2-minute STT runtimes never tie up threads, and multi-hour vendor outages simply buffer in SQS rather than failing physicians' uploads. The trade-off is eventual delivery (minutes instead of one HTTP response), requiring a compare-and-set state machine, push notifications, and a 5-minute background reconciler (a periodic sweep repairing dropped webhooks or stalled jobs).
- Database + transactional outbox vs. publishing directly to SQS. Writing
status = UPLOADEDand anoutboxrow inside one ACID transaction (an all-or-nothing database commit) before relaying to SQS adds a small relay loop, but eliminates the classic dual-write crash gap where a recording is marked uploaded in Postgres yet never reaches the queue. - Compressed, envelope-encrypted transcripts in S3 vs. Postgres text columns. Storing
~30 GB/day(~11 TB/yearraw,~2.5 TB/yearcompressed) of JSON transcripts in S3 keeps Postgres fast and tiny, while envelope encryption (encrypting each compressed transcript with a unique data key wrapped by that hospital's KMS — Key Management Service key) protects against leaked backups and enables crypto-shredding (rendering all backups for a departing customer unreadable by deleting one KMS key). The trade-off is two stores to coordinate (always write S3 blob before committing the Postgres version row) and no native SQL full-text search. - 30-day gated audio deletion vs. retaining audio forever. Purging raw audio after 30 days caps live audio storage at
~43 TBinstead of growing by~526 TB/yearand removes high-risk voice biometrics, at the cost of making re-transcription impossible after Day 30. Gating purge onstatus = TRANSCRIBED AND NOT legal_holdensures slow vendor recovery never loses un-transcribed audio. - Single STT vendor vs. dual-vendor failover. Adding a second STT provider under a BAA (Business Associate Agreement — HIPAA's mandatory privacy contract for vendors) protects clinic SLA during major vendor outages and doubles peak quota, in exchange for maintaining two integrations and normalizing confidence scores across two speech models.
Common mistakes
- Streaming 5,000 mobile uploads through API servers, exhausting connection pools and forcing doctors to re-upload entire 28 MB files when cellular signal flickers.
- Dual-writing to Postgres and SQS without a transactional outbox, leaving recordings permanently stuck in
UPLOADEDif the API process crashes between the database commit andsqs.send_message(). - Burning retry attempts during a full vendor outage. Retrying without exponential backoff with jitter (doubling wait times plus random spread) triggers
429retry storms, and failing to pause attempt counters behind an open circuit breaker (an automated shutoff switch during high error rates) pushes thousands of healthy recordings intoFAILEDduring a 3-hour vendor outage. - Leaking PHI into observability pipelines: putting patient names or MRNs inside S3 keys (
audio/john-doe.m4a), logging query strings containing pre-signed URLs, logging raw vendor error strings that echo audio snippets, or using patient/encounter IDs as Prometheus metric labels. - Writing a blanket
aws:sourceVpceDeny policy on the S3 bucket, accidentally blocking every physician's phone because pre-signed mobile uploads arrive from public clinic Wi-Fi/cellular rather than inside the backend VPC endpoint (instead, requiresourceVpceonWorkerRolewhile scopingPresignedSignerRoleto short-lived TLS object actions). - Soft-deleting versioned S3 audio without
NoncurrentVersionExpiration, or forgetting to delete the STT vendor's copy — leaving "deleted" PHI alive indefinitely as noncurrent S3 versions, DR replicas, or vendor cache entries.
Follow-up questions
- How should the pipeline support clinician-triggered re-transcription when an initial draft contains medical terminology errors? Expose
POST /v1/recordings/{id}/transcriptions(authorized, rate-limited, and audited), which enqueues a newtranscription_jobsrow onto a separateLOW-priority queue (optionally specifying an updated medical specialty vocabulary or secondary STT model) so bulk re-runs never delay live clinic visits. Rather than overwritingv1, store the output as a new immutable version (v2) intranscripts, preserve any manual physician edits as their own version so the UI can show a clean diff, and switchcurrent_transcript_versiononly afterv2passes quality checks. Holdaudio_purge_afterwhile an encounter remains unsigned or has an active job, and return410 Goneonce the 30-day audio purge has completed. - What defense-in-depth controls stop an attacker or unauthorized staff member from retrieving recordings by guessing or enumerating resource identifiers? First, use random 128-bit UUIDs rather than sequential integers, but never rely on unguessable IDs as security — prevent BOLA (Broken Object Level Authorization — missing per-record permission checks) by verifying on every API call that the caller's OIDC token matches
recording.org_idand that the caller is the recording physician, on the encounter's care team, or holds an explicit supervisor role, backed by Postgres row-level security (RLS) as a second safeguard. Keep the S3 bucket completely private (BlockPublicAccess), mint single-object pre-signed playback URLs valid for only 5 minutes after authorization succeeds, and encrypt objects with per-tenant KMS keys usable only by backend IAM roles. Finally, return identical404 Not Foundresponses for both nonexistent and unauthorized IDs (preventing ID enumeration), rate-limit lookups per user, and alert security on spikes of404responses or mass transcript downloads. - How can you detect silent transcription quality regressions—such as degraded word confidence or truncated output—when the vendor still returns HTTP 200? Compute PHI-free quality metrics inside the result worker on every completed transcript: mean word confidence, fraction of words below
0.70confidence, words per minute (wpm), audio coverage (last_word_end_ms / duration_ms), and unexpected empty output (e.g.,< 50words on a 15-minute visit). Automatically flag anomalous transcripts (such ascoverage < 0.80ormean_confidence < 0.75) for UI warning badges or automatic retry on a fallback model, and alert when sliding-window distributions drift from their 7-day baseline sliced by(vendor, stt_model_version, mobile_app_version, device_os)— which immediately catches broken vendor model rollouts or muted phone microphone bugs. Pair passive distribution tracking with an active synthetic canary every 15 minutes (submitting synthetic, PHI-free clinical audio with known ground truth to measure live word error rate / WER) and track physician edit distance before sign-off as a lagging quality signal.
Follow-up questions
- How should the pipeline support clinician-triggered re-transcription when an initial draft contains medical terminology errors?
- What defense-in-depth controls stop an attacker or unauthorized staff member from retrieving recordings by guessing or enumerating resource identifiers?
- How can you detect silent transcription quality regressions—such as degraded word confidence or truncated output—when the vendor still returns HTTP 200?
Similar questions
- Nested Bracket-Count String Decoder
- In-Place Run-Length Encoding of Character Arrays
- Sum of 3, 5, and 7 Multiples Within [1, n]
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform