Design a Secure Medical Voice Recording & Transcription Pipeline
System DesignModel answerLast updated
Design a scalable, HIPAA-compliant system for uploading, transcribing, and retaining audio consults using asynchronous workflows and strict security controls.
Problem Context
You are designing the architecture for a clinical note-taking application used by healthcare providers. Doctors record audio during patient encounters using a mobile device. The application must upload these recordings, convert them into text transcripts via an external Speech-to-Text (STT) provider, and display the final transcripts to authorized clinical staff for review and documentation.
Requirements
- Security & Compliance: Must comply with HIPAA and privacy standards. All data (audio and text) must be encrypted both in transit and at rest. Strict access control, PHI segregation, and comprehensive audit trails are mandatory.
- Scalability: Support a peak load of 5,000 active concurrent audio uploads without system degradation or dropped connections.
- Resilience & Asynchrony: Audio files must be processed asynchronously. Failures or rate limits from external transcription services must be handled cleanly via automated retries, without losing audio files or creating duplicate transcripts.
- Data Retention & Lifecycle: Raw audio must be deleted after a configurable retention window (e.g., 30 days), while final clinical transcripts must be preserved indefinitely (unless explicit legal hold or deletion policies state otherwise).
Your Task
Provide a high-level architectural design addressing the following key operational components:
- Capacity Estimation & Bottlenecks: Estimate network and storage throughput, identifying critical constraints.
- Data Flow & Storage: Trace an audio recording from mobile capture through object storage, queue processing, vendor STT integration, and final database persistence.
- Security & Authorization: Detail encryption strategies, IAM access rules, zero-PHI logging practices, and audit event tracking.
- Resilience Strategy: Explain your queue design, worker state management, idempotency mechanisms, and handling of external service outages.
- API Interface: Define the main REST endpoints for client upload initialization, upload confirmation, processing status checks, and transcript retrieval.
Hints
Hint 1
Avoid proxying large file bytes through application servers; leverage direct-to-object-storage uploads with short-lived pre-signed URLs.
Hint 2
Consider how network instability on mobile devices affects file transfers—chunked or multipart uploads allow resuming interrupted transfers.
Hint 3
Ensure audit logging is decoupled from core database operations using WORM (Write Once, Read Many) storage to maintain regulatory compliance.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Capacity Estimation and System Sizing
Input Assumptions
- Average Consultation: 15 minutes.
- Audio Encoding: Compressed mono voice (Opus/AAC at 32 kbps to 64 kbps) $\approx 0.25 \text{ to } 0.5 \text{ MB per minute}$.
- File Size: $\sim 5 \text{ MB to } 10 \text{ MB}$ per consultation file.
- Peak Concurrency: 5,000 active concurrent uploads.
- Daily Volume: 25,000 clinicians $\times$ 15 consults/day $= 375,000 \text{ recordings/day}$.
Throughput & Storage Calculations
- Ingest Data Volume: $375,000 \text{ files/day} \times 8 \text{ MB/file} \approx 3 \text{ TB audio/day}$.
- Transcript Storage: Transcripts average $2,000 \text{ words} \approx 15 \text{ KB}$ JSON metadata. $375,000 \times 15 \text{ KB} \approx 5.6 \text{ GB transcript data/day}$.
- Peak Network Ingress: 5,000 uploads across mobile links (assuming average upload speed of $2 \text{ Mbps} = 250 \text{ KB/s}$ per stream) results in $5,000 \times 250 \text{ KB/s} = 1.25 \text{ GB/s} \quad (10 \text{ Gbps})$ network bandwidth at peak.
Architectural Bottlenecks
- Application Server Bandwidth: Routing audio data through standard API microservices would saturate application networking and scale infrastructure costs unnecessarily. Audio payload streaming must bypass backend application containers via direct-to-S3 uploads.
- Third-Party STT Quotas: External speech recognition APIs enforce strict concurrent job limits (e.g., 200–500 concurrent jobs). The ingestion layer must queue requests effectively to buffer against vendor rate limits.
2. High-Level Architecture & Component Flow
[Mobile App]
│ 1. Request Presigned Upload
▼
[API Gateway / Ingestion Service] ──► [PostgreSQL Metadata DB]
│ 2. Return Presigned S3 Multipart URLs
▼
[AWS S3 / Storage (Raw Audio)]
│ 3. S3 Event / Outbox Relay
▼
[Message Queue (SQS)]
│ 4. Poll Jobs
▼
[Transcription Worker Pool] ──► [Third-Party STT Vendor]
│ 5. Save Transcript
▼
[PostgreSQL DB] & [Encrypted S3 (Transcripts)]
Core Workflow Steps
- Client Audio Capture: The mobile app records audio locally to an encrypted container (iOS Data Protection / Android EncryptedFile). Upon completion, it computes a local SHA-256 hash of the file.
- Upload Ticket Generation: The app sends metadata (
encounter_id,duration,sha256,file_size) toPOST /v1/recordings. The API server creates a record in the database with statusPENDING_UPLOADand returns an array of pre-signed S3 multipart upload URLs. - Direct Storage Upload: The mobile client uploads 5 MB chunks directly to S3. If network connection drops, the app queries the backend for missing chunk index numbers and resumes without restarting the entire file upload.
- Completion Signaling: The client calls
POST /v1/recordings/{id}/completewith part tags. The API service validates file existence and hash integrity in S3, updating the record status toUPLOADED. - Asynchronous Job Dispatch: An Outbox Relay pattern reads from the database and posts a
StartTranscriptionmessage to Amazon SQS. - Processing Worker: An auto-scaling pool of processing containers consumes messages from SQS, generates a short-lived read URL for the raw audio, and submits the job to the STT provider.
- Result Persistence: Upon receipt of vendor webhook (or completion of worker polling), the normalized transcript is written to an encrypted S3 bucket for raw responses, while structured text metadata is saved into the transactional relational database. Status is updated to
TRANSCRIBED.
3. API Design
Init Recording Upload
- HTTP:
POST /v1/recordings - Request Body:
{ "client_recording_id": "uuid-v4-string", "encounter_id": "enc_89123", "file_size_bytes": 8388608, "sha256_checksum": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "mime_type": "audio/opus" } - Response (201 Created):
{ "recording_id": "rec_01H9X...", "upload_id": "s3_upload_id_string", "part_size": 5242880, "parts": [ {"part_number": 1, "upload_url": "https://s3.amazonaws.com/bucket/path?signature=..."}, {"part_number": 2, "upload_url": "https://s3.amazonaws.com/bucket/path?signature=..."} ] }
Finalize Upload
- HTTP:
POST /v1/recordings/{recording_id}/complete - Request Body:
{ "parts": [ {"part_number": 1, "etag": "\"etag_part_1\""}, {"part_number": 2, "etag": "\"etag_part_2\""} ] } - Response (200 OK):
{"status": "UPLOADED"}
Retrieve Transcript Status and Content
- HTTP:
GET /v1/recordings/{recording_id}/transcript - Response (200 OK):
{ "recording_id": "rec_01H9X...", "status": "TRANSCRIBED", "version": 1, "transcript_text": "Patient presents with persistent cough...", "confidence": 0.96, "created_at": "2026-03-30T10:15:00Z" }
4. Security Architecture & Compliance Controls
Encryption Policies
- Data in Transit: TLS 1.3 enforced externally and internally. Service-to-service communication within the Kubernetes cloud cluster utilizes mutual TLS (mTLS) via an Istio/Linkerd service mesh.
- Data at Rest:
- Cloud Object Storage (S3) uses Server-Side Encryption with Customer-Managed Keys (AWS KMS Envelope Encryption with KMS CMKs). Keys are rotated annually.
- Relational DBs (PostgreSQL) use disk-level AES-256 encryption alongside column-level encryption for sensitive text fields.
Access Control & Identity
- Authentication: OAuth 2.0 / OIDC using JWT bearer tokens supplied by an identity provider (e.g., Okta/Auth0) integrated with healthcare SSO.
- Authorization: Context-aware Attribute-Based Access Control (ABAC). Access to a transcript requires:
- Role check:
ProviderorScribe. - Patient-Care Team Assignment: Requesting user ID must belong to the active care team associated with the recording's
encounter_id.
- Role check:
PHI Segregation & Sanitization
- De-identified Object Key Structure: Object keys in S3 follow pseudo-random UUID formats (
s3://prod-medical-audio-bucket/v1/a8f3/90b2/uuid.opus). Keys must never contain dates, patient names, or Medical Record Numbers (MRNs). - Zero-PHI Logging: Application logs enforce standard structural enforcement schemas. Standard logging wrappers drop non-whitelisted attributes. System metrics report operational metadata only (e.g.,
http_response_code,processing_duration_ms).
Auditing & Compliance Tracking
Every access event to audio objects or transcript records creates an immutable event entry inside an append-only audit database table:
audit_log (
audit_id BIGSERIAL PRIMARY KEY,
actor_id UUID NOT NULL,
action VARCHAR(50) NOT NULL, -- e.g., READ_TRANSCRIPT, UPLOAD_AUDIO
resource_id UUID NOT NULL,
encounter_id UUID NOT NULL,
ip_address INET NOT NULL,
timestamp TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
)
Cloud Audit logs (e.g., AWS CloudTrail Data Events) are configured to automatically stream object-level access events into a WORM (Write-Once-Read-Many) bucket configured with S3 Object Lock in Compliance Mode to satisfy regulatory tamper-proof audit trail mandates.
5. Resilient Asynchronous Processing & Failure Management
Message Queue and State Machine
State transitions follow explicit status rules:
$$\text{PENDING_UPLOAD} \rightarrow \text{UPLOADED} \rightarrow \text{PROCESSING} \rightarrow \text{TRANSCRIBED}$$
┌────────────────┐
│ PENDING_UPLOAD │
└───────┬────────┘
│ Complete Upload
▼
┌──────────────┐
│ UPLOADED │
└───────┬──────┘
│ Picked up by Worker
▼
┌────────────────┐
│ PROCESSING │
└───────┬────────┘
┌─────────────┴─────────────┐
│ Success │ Failure (Max Retries)
▼ ▼
┌──────────────┐ ┌──────────────┐
│ TRANSCRIBED │ │ FAILED_NEEDS │
└──────────────┘ │ _ATTENTION │
└──────────────┘
Idempotent Processing
Workers can crash mid-execution, causing SQS messages to return to the queue. To avoid redundant third-party API processing costs and duplicate DB entries:
- When a worker receives a message, it uses a database transactional lock (
SELECT ... FOR UPDATE) to check if the job is already markedPROCESSINGorTRANSCRIBED. - STT request submissions supply an Idempotency Key calculated from
MD5(recording_id + attempt_count)to the vendor API. If the vendor receives a duplicated call, it returns the existing job ID rather than spawning a new process.
Retry Handling Strategy
- Transient STT Errors (Rate Limits / 5xx HTTP): Retried using exponential backoff with randomized jitter ($t_{wait} = 2^{attempt} + \text{rand}(0, 1) \text{ seconds}$). Message visibility timeouts are extended incrementally.
- Poison Messages: If a message reaches a maximum attempt limit (e.g., 5 failures), it is moved to a Dead-Letter Queue (DLQ). The recording record updates to status
FAILED_NEEDS_ATTENTION, triggering an operational alert for manual review.
6. Storage Lifecycle & Retention Management
Audio Uploaded ──► [S3 Standard / KMS Encryption]
│
│ S3 Lifecycle Rule (30 Days)
▼
[Audio Deleted] (Permanent)
- Automated Audio Purge: S3 Bucket Lifecycle policies automatically execute a hard delete rule on all files matching the prefix
/audio/after 30 days. - Reconciliation Job: A scheduled batch job runs daily, querying the database for recordings whose audio should have been deleted by the lifecycle policy. It confirms object absence via S3 metadata calls and flags the database record as
audio_purged = TRUE. - Legal Hold Override: If a recording is flagged with an active
legal_holdtag, the reconciliation job attaches an S3 Legal Hold attribute to the object, preventing S3 Lifecycle policies from deleting the raw audio file until the hold is lifted by compliance officers. - Permanent Transcript Retention: Database rows containing normalized transcripts and their operational execution history are excluded from automated purge workflows and stored permanently.