Scalable Text-to-Speech Platform: Prototype, Review, and Batch Extension

Medium · System Design · Software Engineer · Onsite

Prompt

You are completing an 8–12 hour take-home engineering assignment for a software engineer position on an AI product team, paired with a subsequent live design review. AI coding assistants are permitted, and their complete session transcripts are submitted alongside your repository, automated tests, and written design notes; evaluators assess disciplined agentic engineering practice, pragmatic 0-to-1 scoping, and user/developer experience. Because the live review treats the project as a prototype, every stubbed or deferred capability must be recorded upfront with clear engineering reasoning.

Core task: Architect and build a scalable text-to-speech (TTS) platform around an existing synthesis model or hosted third-party TTS API (confirm this boundary upfront—your focus is the orchestration, API, storage, and playback system surrounding raw waveform generation).

Clarify your product and infrastructure assumptions before building: - Consumers & playback model: API developers, an interactive end-user player, or both—and whether listeners require progressive audio playback while generation is still in flight or only a completed downloadable file. - Synthesis backend: Whether a hosted vendor is specified or chosen by you, and whether GPU instances are available versus external HTTP APIs only. - Input length spectrum: Brief single-sentence prompts up to long-form manuscripts such as multi-chapter books. - Primary scaling goal: High concurrency of short utterances, large daily character throughput, or minimal latency to initial playback. - Audio capabilities: Required voices, languages, and output audio formats.

Structure your work across three stages:

  1. Stage 1 — Prototype scope & implementation: Commit to what ships within 8–12 hours, what is stubbed or deferred, and why. Design an API, persistence schema, and request pipeline that stay responsive across both brief inputs and long-form manuscripts (including text segmentation and seamless audio reassembly), support live progress reporting, worker retries, and idempotent duplicate requests, and show a disciplined spec-first, test-verified AI coding workflow in your submitted logs.
  2. Stage 2 — Prototype critique & scaling limits: Present back-of-the-envelope worker throughput and cost calculations identifying the earliest bottleneck; evaluate trade-offs across segment sizing, live streaming versus finished files, and hosted APIs versus self-hosted GPU workers; and examine unaddressed production needs (uniform voice quality across segments, pronunciation customization, usage quotas) alongside failure and UX/DX gaps (crashed workers, duplicate retries, progress accuracy, and error reporting).
  3. Stage 3 — Bulk narration customer extension: Extend the architecture for a customer uploading large batches of long-form manuscripts via API who needs asynchronous completion callbacks and a single uniform voice across every full narration—detailing batch ingestion and webhook delivery with retry/deduplication guarantees, voice consistency across segments and model upgrades, task-level engineering estimates with risks, and phased roadmap sequencing with success metrics.

Scope & Expectations

  • Pragmatic prototype & seamless audio pipeline: Define an explicit 8–12 hour scope cut, pair low-latency short-input streaming with an asynchronous long-form pipeline (sentence-clean segmentation, crash-safe retries, idempotency, and gapless audio stitching), and demonstrate disciplined AI-assisted development.
  • Unit economics & scaling analysis: Calculate per-worker audio throughput, storage bandwidth, and hosted-vendor versus GPU costs to pinpoint the first bottleneck, while surfacing multi-tenant fairness, pronunciation/prosody gaps, and UX/DX rough edges.
  • Batch orchestration & voice consistency: Design duplicate-safe bulk submission, reliable completion notifications, and acoustic/version pinning so voice identity never drifts across chunks or model rollouts, supported by task estimates and phased milestones.

Step-by-step walkthrough

  1. Clarify requirements and choose the core scaling dimension

    Before writing code, lock down the product assumptions and place them at the top of README.md so every deliberate shortcut in the review traces back to an explicit engineering choice.

    Assumptions confirmed upfront

    • Synthesis engine: We call a hosted Text-to-Speech (TTS) provider behind a clean adapter interface rather than managing GPUs during an 8–12 hour take-home, keeping the door open to swap in self-hosted GPU workers later without changing our public API.
    • Users: Developers integrating a REST API are primary; we also ship a lightweight single-page web audio player so reviewers can immediately hear playback, inspect progress, and see error states.
    • Input size: Anything from a 50-character chat reply up to a 1,000,000-character book (~18.5 hours of spoken audio).
    • Playback modes: Short inputs stream audio bytes back immediately over HTTP; long documents generate asynchronously so listeners can start playing the opening paragraphs within seconds while later chapters finish in the background, then download one stitched MP3 at the end.
    • Voices and formats: Stock English voices from the provider, outputting MP3 for downloads and WAV chunks for browser playback.

    Choose the primary scaling dimension to validate

    "Scalable" could mean 10,000 tiny concurrent requests, billions of characters per day, or sub-second first audio. Trying to prove all three in 10 hours produces a shallow demo. Notice where the real distributed-systems work lives:

    • Many tiny requests mostly test the upstream provider; our service is just a stateless streaming proxy.
    • Long documents test our architecture: sentence-safe splitting, fast first audio, parallel worker coordination, crash recovery without missing or duplicated sentences, and gapless audio stitching.

    Therefore, our prototype proves one crisp property: even for a book-length input, first audio is playable in ~3 seconds, killing workers mid-job still produces a complete glitch-free file, and total throughput is bounded only by the TTS provider's concurrency cap. Everything orthogonal to that proof (OAuth, Stripe billing, multi-region routing) is stubbed and logged in DECISIONS.md.

  2. Scope the 11-hour prototype and structure the AI coding-agent workflow

    Category Component Why this cut makes sense
    Ships POST /v1/narrations async pipeline (submit, progress, playable chunk prefix, final MP3, cancel) + idempotency keys Core proof of reliable long-form synthesis
    Ships Sentence-aware ramped splitter (200 -> 500 -> 1,000 chars) + ffmpeg PCM-to-MP3 stitcher Fast first audio and seamless audio joins
    Ships PostgreSQL chunk queue using timed leases, exponential-backoff retries, and a background reaper Proves crash recovery without operating a separate message broker
    Ships Real provider adapter + deterministic fake provider (configurable latency, HTTP 500s, and HTTP 429 rate limits) + bench.py + worker kill test Proves throughput and crash safety reproducibly at $0 API cost
    Ships POST /v1/speech streaming pass-through + 1-page web player Demonstrates short-text latency and lets the interviewer listen live
    Stubbed Static API keys in config, simple daily character cap, local MinIO (S3-compatible object store) Same interfaces as production at near-zero setup time
    Deferred Webhooks, SSML (Speech Synthesis Markup Language for custom pauses/pronunciation), GPU self-hosting, multi-tenant fair queuing Scoped cleanly for Stages 2 and 3

    Time budget (~11 hours): SPEC.md & DECISIONS.md (1 h) -> FastAPI skeleton & Postgres schema (1.5 h) -> text splitter + property tests (1 h) -> lease worker + reaper + adversarial tests (2 h) -> PCM/MP3 assembler (1 h) -> /v1/speech stream (0.5 h) -> web player (1 h) -> fake provider, bench.py, and kill -9 test (1.5 h) -> final README review (1.5 h).

    Disciplined AI coding-agent workflow (graded via submitted chat logs)

    1. Start every session from SPEC.md: Define API payloads, database tables, state transitions, and invariants upfront so coding agents follow our architecture instead of inventing conflicting schemas across prompts.
    2. Slice into 30–60 minute tasks (TASKS.md): Each task has an explicit pass/fail check (for example: "Splitter never emits >1,500 chars and joining chunks reconstructs all non-whitespace tokens").
    3. Adversarial tests before sign-off: Ask the agent to write tests for race conditions first — expired lease takeovers, duplicate chunk completions, and reused idempotency keys with mutated bodies.
    4. Visible human code review in the logs: Read every diff carefully and push back inside the chat transcript when the agent makes subtle mistakes (such as concatenating separate MP3 files directly or omitting lease tokens on completion).
  3. Estimate single-worker throughput, storage, and synthesis cost

    Before proposing caches or database shards, calculate what a single worker and a single provider API key can push per second. PCM (Pulse-Code Modulation) below means uncompressed raw audio samples, whereas MP3 is lossy compressed audio.

    1. Text-to-audio conversion ratios
       Normal speaking pace     ~150 words/min x ~6 chars/word (with spaces) = ~15 chars per second of audio
       1 hour of speech         15 chars/s x 3,600 s = 54,000 characters
       90,000-word book         ~540,000 characters = ~10 hours of audio
    
    2. Audio byte sizes
       Raw PCM (24 kHz, 16-bit = 2 bytes/sample, mono) -> 48,000 bytes/s (~48 KB/s) = ~173 MB/hour (~1.73 GB/book)
       Compressed MP3 (64 kbps = 8,000 bytes/s)        -> ~8 KB/s                   = ~29 MB/hour  (~288 MB/book)
    
    3. Hosted TTS provider ceiling (ASSUMED — replace with bench.py measurements!)
       Per-call latency         ~0.5 s network/model setup + ~1.0 s per 1,000 chars = ~1.5 s per 1,000-char chunk
       Concurrency limit        50 in-flight HTTP requests per API key
       Throughput (Little's Law: concurrency / latency):
                                50 calls / 1.5 s = ~33.3 chunks/s = ~33,000 chars/s (~2,200x real-time audio!)
       Provider price           $15 per 1,000,000 characters ($0.81 per hour of audio; $8.10 per 10-hr book)
       Max spend on 1 key       33,000 chars/s x 86,400 s/day x ($15 / 1M) = ~$42,800/day
    
    4. Self-hosted GPU comparison (ASSUMED: $2.00/GPU-hr, 50 s of audio per GPU-second with dynamic batching)
       1 GPU throughput         50 s audio/s x 15 chars/s = 750 chars/s = 2.7M chars/GPU-hour
       Unit cost                $2.00 / 2.7M = ~$0.74 / 1M chars at 100% load (~$2.47 / 1M chars at 30% load)
       GPUs to match 1 API key  33,000 / 750 = ~44 GPUs (+ model ops, autoscaling, and idle-capacity waste)
    
    5. Load on our own infrastructure at the 33 chunks/s provider ceiling
       PostgreSQL writes        ~4 row updates/chunk (claim, complete, job counter, usage) x 33/s = ~132 writes/s
       Object storage ingress   33.3 chunks/s x 3.2 MB PCM/chunk = ~106 MB/s (drops to ~50 MB/s with lossless FLAC)
    

    Three architectural takeaways from the math

    1. Workers are network I/O-bound, and the first bottleneck is the provider's 50-request concurrency cap. A single async Python worker easily holds 50 open HTTP streams, and ~132 SQL writes/s barely registers on one PostgreSQL instance.
    2. Self-hosting GPUs saves money only at high, steady utilization. Until volume justifies managing dozens of GPUs 24/7, a hosted API behind an adapter is dramatically simpler.
    3. Time to first audio depends on Chunk 0's character count and queue priority, never on total book length. A 200-character Chunk 0 synthesizes in 0.5 + 0.2 = ~0.7 s so long as it jumps ahead of bulk book chunks in the queue.
  4. Design the REST API for low-latency streaming and async narrations

    Short interactive prompts and 10-hour books need different HTTP patterns: holding a single HTTP connection open for 15 minutes while a book renders will fail behind load-balancer timeouts and force full restarts on any Wi-Fi hiccup.

    1. Synchronous streaming for short text (<= 2,000 chars)
       POST /v1/speech
         { "text": "Hello, your ride has arrived.", "voice_id": "alloy", "format": "mp3" }
         -> 200 OK (Content-Type: audio/mpeg, Transfer-Encoding: chunked) -- bytes stream immediately
         -> 413 Payload Too Large { "code": "TEXT_TOO_LONG", "hint": "Use POST /v1/narrations" }
    
    2. Asynchronous job pipeline for long documents (up to 1,000,000 chars)
       POST /v1/narrations
         Header: Idempotency-Key: <client-generated UUID per logical request>
         { "text": "...", "voice_id": "alloy", "format": "mp3", "paragraph_pause_ms": 600 }
         -> 202 Accepted { "id": "nar_91a", "status": "queued", "status_url": "...", "chunks_url": "..." }
         -> 200 OK       (exact same key + identical request body hash -> returns existing job safely)
         -> 422 Unprocessable Entity (same Idempotency-Key reused with a DIFFERENT body -> client bug)
         -> 429 Too Many Requests    (Retry-After: 30)
    
       GET  /v1/narrations/{id}
         -> 200 { "id": "nar_91a", "status": "running", "chunks_total": 540, "chunks_done": 18,
                  "seconds_ready": 412, "eta_seconds": 190,
                  "error": null, "audio_url": null }
    
       GET  /v1/narrations/{id}/chunks?from=0
         -> 200 { "items": [{ "index": 0, "url": "<signed WAV URL>", "duration_ms": 13200 }, ...],
                  "next_from": 6, "done": false }
    
       GET  /v1/narrations/{id}/audio   -> 302 redirect to signed S3 URL of final stitched MP3
       POST /v1/narrations/{id}/cancel  -> 200 OK (deletes pending chunks in one transaction)
    

    Why two details here matter for beginners

    • Idempotency key: A unique token chosen by the caller before sending a request so that if the network drops and the caller retries, the server recognizes the token and returns the original job instead of charging twice.
    • Contiguous playable prefix (seconds_ready): If Chunks 0, 1, 2 and 4..10 are done while Chunk 3 failed and is retrying, a listener can only play through Chunk 2 before hitting silence! Both seconds_ready and /chunks expose only the unbroken prefix starting at 0, avoiding misleading "90% ready" spinners that stall mid-sentence.
  5. Data model and state machines in PostgreSQL

    narrations
      id                uuid PK
      customer_id       text NOT NULL
      idempotency_key   text NOT NULL, UNIQUE (customer_id, idempotency_key)
      request_hash      bytea NOT NULL          -- SHA-256 of normalized request JSON
      input_key         text NOT NULL           -- S3 object key of raw uploaded text
      input_chars       int NOT NULL
      voice_snapshot    jsonb NOT NULL          -- provider, voice_id, exact model_version, speed, seed
                                                -- (copied at submit time so mid-job upgrades never alter voice!)
      status            text NOT NULL           -- queued | splitting | running | assembling | succeeded | failed | canceled
      chunks_total      int NULL
      chunks_done       int NOT NULL DEFAULT 0
      audio_key         text NULL
      error             jsonb NULL              -- { code, message, chunk_index, char_start, char_end }
      created_at, started_at, finished_at timestamptz
    
    chunks
      narration_id      uuid, idx int, PK (narration_id, idx)
      text              text NOT NULL           -- <= 1,500 chars, immutable once split
      pause_after_ms    int NOT NULL
      priority          smallint NOT NULL       -- 0 for idx = 0 (first audio!), 1 for idx >= 1
      created_at        timestamptz NOT NULL    -- inherited from narration for FIFO ordering
      status            text NOT NULL           -- pending | leased | done | failed
      attempts          int NOT NULL DEFAULT 0
      not_before        timestamptz NOT NULL DEFAULT now()
      lease_token       uuid NULL               -- fencing token proving which worker owns this attempt
      lease_expires_at  timestamptz NULL
      cache_key         bytea NOT NULL
      audio_key         text NULL
      duration_ms       int NULL
      INDEX queue_pop_idx (status, priority, created_at, idx)
    
    audio_cache   (cache_key bytea PK, audio_key text, duration_ms int, bytes int, created_at timestamptz)
    usage_events  (narration_id uuid, chunk_idx int, customer_id text, chars int, cache_hit bool,
                   PK (narration_id, chunk_idx)) -- guarantees retried chunks are billed at most once!
    
    Job lifecycle:    queued --> splitting --> running --> assembling --> succeeded
                                    |             |            |
                                    +-------------+------------+-------> failed   (any active state -> canceled)
    
    Chunk lifecycle:  pending --> leased --> done
                         ^          |
                         +-- retry -+------> failed (on permanent 4xx error or 5 expired/failed attempts)
    

    Storing chunks as rows inside PostgreSQL rather than fire-and-forget messages in an external queue lets a single SQL transaction atomically validate the worker's lease, mark the chunk done, increment chunks_done, and write the billing row.

  6. High-level architecture and end-to-end request flow

      Developer / SDK               Single-Page Web Player
            |                                 |
            v                                 v
      +---------------------------------------------------+
      | Stateless API Servers (FastAPI)                   |  auth, quota check, idempotency
      |  - POST /v1/speech  ------------------------------+--- direct HTTP stream ---> [ Hosted TTS API ]
      |  - POST /v1/narrations                            |                                   ^
      +---------------------------------------------------+                                   |
            | 1. upload text to S3 + INSERT narration                                         |
            v                                                                                 |
      +---------------------------------------------------+                                   |
      | PostgreSQL (narrations, chunks, cache, usage)     | <--- claim / heartbeat / done ----+
      +---------------------------------------------------+      (Redis/DB semaphore <= 50)   |
            ^                         ^                                                       |
            | 2. split -> synthesize  | reaper resets expired leases                          |
            v                         |                                                       |
      +---------------------------------------------------+                                   |
      | Async Worker Pool (split, chunk synth, assemble)  | --- synthesize on cache miss -----+
      +---------------------------------------------------+
            | 3. write raw PCM/FLAC chunks & stitched MP3
            v
      +---------------------------------------------------+
      | Object Storage (S3 / MinIO)                       | ---> pre-signed URLs to client/player
      +---------------------------------------------------+
    
    1. Submit (POST /v1/narrations): API uploads raw text to S3, inserts one queued row in narrations, and returns 202 Accepted in < 50 ms regardless of whether the text is 1 page or 500 pages.
    2. Split: A worker claims the job, splits sentences (committing Chunk 0 at priority = 0 immediately so synthesis can begin right away), writes the remaining chunk rows, and sets status = 'running'.
    3. Synthesize: Workers pop pending chunks ordered by (priority, created_at, idx), check audio_cache, call the TTS provider under a shared 50-slot concurrency semaphore on cache misses, upload raw audio to S3, and complete their lease.
    4. Assemble: The worker completing the final chunk (chunks_done = chunks_total) atomically transitions the job from running to assembling and triggers the stitcher, which streams all chunks through a single loudness-normalized MP3 encode pass.
  7. Deep dive: sentence-aware ramped chunking and gapless audio stitching

    Why naive splitting sounds robotic: Prosody is the natural melody, rhythm, and intonation of human speech across a sentence. Slicing every 1,000 characters blindly cuts words in half and resets pitch mid-thought. On the other hand, making every chunk tiny (~200 chars) creates hundreds of unnatural resets and wastes HTTP overhead, while making every chunk large (~1,000 chars) delays first playback!

    Solution — sentence-aware ramped chunking: Keep Chunk 0 small (200 chars, ~0.7 s to synthesize, ~13 s of playback) so playback starts almost immediately, ramp Chunk 1 to 500 chars, and use 1,000 chars (<= 1,500 hard cap) for Chunk 2 onward:

    Input book ---> [ Chunk 0: ~200 chars ] [ Chunk 1: ~500 chars ] [ Chunk 2: ~1,000 chars ] [ Chunk 3: ~1,000 chars ] ...
                     priority = 0 (jumps     synthesizes during      fewer joins, natural
                     queue -> plays in ~1s)  Chunk 0's 13s audio!    paragraph prosody
    
    import re
    
    SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
    PARAGRAPH_BREAK = re.compile(r"\n\s*\n")
    FIRST_TARGETS = [200, 500]  # small opening chunks minimize time-to-first-audio
    STEADY_TARGET = 1000        # larger steady-state chunks improve prosody and cut API calls
    HARD_MAX = 1500             # strict upper bound below provider per-request character limit
    SENTENCE_PAUSE_MS = 250
    PARAGRAPH_PAUSE_MS = 600
    
    
    def target_for(chunk_index):
        if chunk_index < len(FIRST_TARGETS):
            return FIRST_TARGETS[chunk_index]
        return STEADY_TARGET
    
    
    def split_long_sentence(sentence):
        """Break a run-on sentence exceeding HARD_MAX at the last word space."""
        pieces = []
        while len(sentence) > HARD_MAX:
            cut = sentence.rfind(" ", 0, HARD_MAX)
            if cut <= 0:
                cut = HARD_MAX
            pieces.append(sentence[:cut].strip())
            sentence = sentence[cut:].strip()
        if sentence:
            pieces.append(sentence)
        return pieces
    
    
    def sentences_with_breaks(text):
        """Yield (sentence_text, ends_paragraph) pairs in reading order."""
        normalized = text.replace("\r\n", "\n").strip()
        if not normalized:
            return []
        pairs = []
        for paragraph in PARAGRAPH_BREAK.split(normalized):
            paragraph = paragraph.strip()
            if not paragraph:
                continue
            pieces = []
            for raw_sentence in SENTENCE_END.split(paragraph):
                raw_sentence = raw_sentence.strip()
                if raw_sentence:
                    pieces.extend(split_long_sentence(raw_sentence))
            for idx, piece in enumerate(pieces):
                pairs.append((piece, idx == len(pieces) - 1))
        return pairs
    
    
    def split_text(text):
        """Pack sentences into ramped chunks, returning (chunk_text, pause_after_ms)."""
        chunks = []
        current = ""
        current_ends_paragraph = False
        for sentence, ends_paragraph in sentences_with_breaks(text):
            limit = target_for(len(chunks))
            separator = "\n\n" if current_ends_paragraph else " "
            if current and len(current) + len(separator) + len(sentence) > limit:
                pause = PARAGRAPH_PAUSE_MS if current_ends_paragraph else SENTENCE_PAUSE_MS
                chunks.append((current, pause))
                current = ""
            current = sentence if not current else current + separator + sentence
            current_ends_paragraph = ends_paragraph
        if current:
            chunks.append((current, 0))
        return chunks
    

    Known prototype trade-off: SENTENCE_END also splits after abbreviations like "Dr. Smith", causing at worst a mild pause, never lost words; replacing it with an NLP sentence tokenizer is logged in DECISIONS.md.

    Gapless stitching (why we never concatenate raw MP3 files): Individual MP3 encoders pad the start and end of every file with silent frame samples, leaving audible clicks/gaps if MP3 files are glued byte-for-byte. Instead, workers request headerless 24 kHz, 16-bit mono PCM (compressed losslessly to FLAC at scale to halve storage). During assembly, ffmpeg streams chunks in index order from S3, inserts exact pause_after_ms silence samples, normalizes loudness across chunks, and encodes to a single continuous MP3 stream in constant RAM. For live progressive listening, /chunks wraps each PCM chunk in a 44-byte WAV header and schedules sample-accurate gapless playback via the browser's Web Audio API.

  8. Deep dive: crash-safe leases, error classification, and three-layer deduplication

    A lease is a temporary lock with an expiration timestamp (lease_expires_at) and a unique fencing ID (lease_token), paired with a reaper (a background timer that reclaims expired leases from crashed workers). PostgreSQL's FOR UPDATE SKIP LOCKED lets dozens of workers claim non-overlapping rows without blocking one another:

    -- 1. Worker claims up to 4 ready chunks without blocking peers
    UPDATE chunks
    SET status = 'leased',
        lease_token = gen_random_uuid(),
        lease_expires_at = now() + interval '60 seconds',
        attempts = attempts + 1
    WHERE (narration_id, idx) IN (
        SELECT narration_id, idx FROM chunks
        WHERE status = 'pending' AND not_before <= now()
        ORDER BY priority, created_at, idx
        LIMIT 4
        FOR UPDATE SKIP LOCKED
    )
    RETURNING narration_id, idx, text, cache_key, lease_token;
    
    -- 2. Worker completes a chunk ONLY if its lease_token still owns the row (single transaction!)
    UPDATE chunks
    SET status = 'done', audio_key = :audio_key, duration_ms = :duration_ms
    WHERE narration_id = :nid AND idx = :idx AND status = 'leased' AND lease_token = :token;
    -- If 1 row updated:
    --   INSERT INTO usage_events ... ON CONFLICT (narration_id, chunk_idx) DO NOTHING;
    --   UPDATE narrations SET chunks_done = chunks_done + 1 WHERE id = :nid RETURNING chunks_done, chunks_total;
    --   If chunks_done = chunks_total:
    --     UPDATE narrations SET status = 'assembling' WHERE id = :nid AND status = 'running';
    -- If 0 rows updated: our lease expired and another worker took over -> discard our result!
    
    -- 3. Reaper runs every 10 s: fail poison chunks after 5 attempts, otherwise return to pending
    UPDATE chunks SET status = 'failed', last_error = 'lease expired 5 times'
    WHERE status = 'leased' AND lease_expires_at < now() AND attempts >= 5;
    
    UPDATE chunks
    SET status = 'pending', lease_token = NULL,
        not_before = now() + interval '2 seconds' * power(2, attempts)
    WHERE status = 'leased' AND lease_expires_at < now() AND attempts < 5;
    

    Why every crash window stays corruption-free

    • Worker dies before provider responds: Lease expires in <= 70 s; replacement worker synthesizes cleanly.
    • Worker dies after uploading S3 audio (s3://.../chunks/<cache_key>.pcm), before SQL commit: Replacement worker checks S3 by deterministic cache_key before calling the provider, recovering the audio at $0 extra API cost!
    • Zombie worker stalls for 90 s and tries to commit after takeover: AND lease_token = :token matches 0 rows, preventing double-incrementing chunks_done or double-billing.
    • Error classification: HTTP 429 backs off by Retry-After and dynamically lowers the shared concurrency limit; 5xx/timeouts retry up to 5 times with jittered exponential backoff; 400 bad-input errors fail immediately with exact (chunk_index, char_start, char_end) diagnostics rather than burning 5 retries.
  9. Product review: scaling bottlenecks, fairness, missing features, and UX gaps

    In Stage 2, walk through bottlenecks in the exact order they bite:

    1. Provider concurrency cap (50 in-flight requests / ~33,000 chars/s): Must be enforced across all workers via a shared Redis/Postgres semaphore rather than per-process counters. Scale horizontally by negotiating higher provider quotas, sharding across multiple API keys/providers (keeping each single narration pinned to one provider/model!), or moving steady baseline load to ~44+ self-hosted GPUs once utilization stays high.
    2. Multi-tenant starvation (happens before global saturation!): Strict FIFO (created_at) lets one customer submitting 500 books monopolize all 50 slots so a new user's Chunk 1 stalls behind 250,000 book chunks. Fix with per-customer in-flight caps plus playback-deadline scheduling: schedule chunk i by job_started_at + sum(duration of chunks 0..i-1), so a live listener's Chunk 1 (needed in 13 seconds) naturally runs ahead of a book's Chapter 30 (needed 8 hours from now).
    3. PostgreSQL queue churn (>2,000 updates/s): Frequent row updates eventually stress Postgres VACUUM. When metrics show lock/vacuum pressure, move ephemeral lease dispatch to Redis Streams / SQS while keeping narrations and usage_events in Postgres.
    4. Uncompressed PCM storage (~106 MB/s): Store intermediate chunks as lossless FLAC (~50% smaller, still sample-exact for gapless decoding) and lifecycle-delete raw chunks 7 days after final MP3 assembly.

    Missing customer features & UX gaps to volunteer proactively

    • Missing features: Custom pronunciation lexicons and SSML (acronyms and proper nouns mispronounce today), webhooks, word-level timestamps for karaoke/captions, monthly quota reservations, and cross-chunk prosody context conditioning.
    • UX & DX gaps: A killed worker causes a silent ~70 s pause on that chunk with no UI banner; failed jobs lack a "retry/skip single chunk" button; simple linear ETAs jump during 429 throttling; developers lack typed SDKs, OpenAPI specs, and sandbox test keys.
  10. Bulk customer extension: webhooks first, batch API, voice consistency, and roadmap

    Stage 3 asks how we support a customer uploading large batches of long-form manuscripts via API, receiving asynchronous completion callbacks, and hearing a single uniform voice across every full narration.

    Deliver the smallest integration unblocker before full batch tooling: Because the customer can already submit documents in a loop via POST /v1/narrations with idempotency keys, webhooks + voice consistency checks are the minimum viable unblocker in Week 1; POST /v1/batches and fair queuing follow right behind without breaking their integration.

    POST /v1/webhook-endpoints   { "url": "https://...", "events": ["narration.succeeded", "narration.failed"] }
      -> 201 { "id": "wh_1", "signing_secret": "whsec_..." }
    
    POST /v1/batches             Header: Idempotency-Key: <batch_key>
      { "webhook_endpoint_id": "wh_1",
        "items": [{ "external_id": "book-42-ch1", "text_url": "https://...", "voice_id": "alloy" }, ...] }
      -> 202 { "batch_id": "bat_9", "items": [{ "external_id": "book-42-ch1", "narration_id": "nar_..." }] }
    
    Outbound Webhook POST
      Headers: Webhook-Id: evt_882 | Webhook-Signature: t=1760000123,v1=<HMAC-SHA256(secret, t + "." + body)>
    
    • Reliable webhooks & duplicate protection: Write the terminal job state (succeeded/failed) and an outbox_events row in the same database transaction (transactional outbox pattern — guarantees we never finish a job without queuing its webhook). Delivery workers retry non-2xx responses with exponential backoff for 24 hours before moving to a dead-letter dashboard with one-click replay; customers deduplicate at-least-once deliveries on Webhook-Id and verify HMAC cryptographic signatures. UNIQUE (customer_id, external_id) prevents charging twice if overlapping batches are uploaded.
    • Preserving one consistent voice across chunks and model upgrades:
      1. Across chunks: Every chunk uses the immutable voice_snapshot (exact dated model_version, never "latest", plus fixed seed), sends adjacent sentences as prosody conditioning context where supported, normalizes loudness to -16 LUFS, and runs a lightweight speaker-embedding cosine-similarity check against the voice's reference clip — automatically re-synthesizing any acoustic outlier chunk before stitching!
      2. Across model upgrades: Model upgrades are strictly opt-in per project; in-flight batches and existing audiobooks stay pinned to their snapshot model version, and retiring a deprecated provider model triggers whole-document re-renders rather than mixing two models inside one narration.

    Estimate, roadmap order, and trade-off summary

    Roadmap Phase & Task Engineer-Days Success Metric
    1. Unblock integration: Transactional outbox + HMAC webhooks (3d), speaker-similarity & loudness check (1.5d) 4.5 >99% webhooks delivered <5 s; outlier chunk rate <0.1%
    2. Bulk DX: POST /v1/batches with external_id dedupe & batch status (2d), upfront batch quota reservation (1d) 3.0 0 duplicate billed narrations on batch retries
    3. Multi-tenant isolation: Per-customer concurrency caps + playback-deadline scheduler (2d), 100-book load test & docs (1.5d) 3.5 Interactive users' p95 first-audio stays < 3 s during a 100-book batch
    Total 11 days (~2.5 weeks with review & buffer)
    • Core trade-offs summarized: Proving long-document reliability over trivial short-proxy load; hosted synthesis behind an adapter ($15/1M chars, zero GPU ops) until utilization justifies ~44+ GPUs ($0.74/1M chars); ramped sentence chunks (200 -> 500 -> 1,000) balancing ~0.7 s first audio against smooth prosody; raw PCM/FLAC stitching into one MP3 pass for gapless joins; and PostgreSQL SKIP LOCKED leases + unique usage_events giving at-least-once synthesis with exactly-once progress and billing.

Intuition & how it works

Imagine turning a 300-page novel into an audiobook using a room of voice actors. If you hand the entire 300-page manuscript to one actor over a single continuous phone call, the listener waits hours before hearing the opening sentence, and if the phone line drops on page 299 you lose everything and start from page 1. On the other hand, if you slice the manuscript every 200 characters with scissors regardless of punctuation, words get chopped in half and every actor starts with a jarring change in tone. Instead, a smart studio gives the first 2 sentences (Card 0) to an idle actor immediately so the listener starts hearing Chapter 1 within a second, hands full sentence-aligned paragraphs (Cards 1, 2, 3...) to parallel actors with a 60-second timer per card so any actor who walks out has their card reassigned automatically, and finally normalizes volume and encodes all finished raw recordings in a single pass so the seams are completely invisible.

The naive approach — accepting a book in one synchronous HTTP POST, calling the model once or slicing at fixed character counts, and gluing MP3 snippets together — fails on latency, reliability, and audio quality simultaneously: load balancers drop multi-minute HTTP requests, mid-word splits ruin prosody (the natural rhythm and pitch melody of speech), and concatenating separately encoded MP3 files leaves tiny silent padding glitches at every boundary.

Here is a concrete trace of a 3,200-character chapter excerpt moving through our ramped chunk-and-lease pipeline:

1. Submit (t = 0.0 s): Client POSTs 3,200 chars with Idempotency-Key "ch-14".
   API saves text, snapshots exact voice/model ("tts-2025-06-01", seed 42), returns 202 Accepted.

2. Ramped split (t = 0.1 s): Splitter breaks on sentence boundaries using ramped targets [200, 500, 1000]:
   - Chunk 0:  190 chars (priority = 0 -> jumps to front of queue!)
   - Chunk 1:  490 chars (priority = 1)
   - Chunk 2:  980 chars (priority = 1)
   - Chunk 3:  940 chars (priority = 1)
   - Chunk 4:  600 chars (priority = 1)

3. Fast first audio & parallel work (t = 0.8 s): Worker A synthesizes Chunk 0 in ~0.7 s (~12.6 s of speech).
   Web player immediately streams Chunk 0 while Workers B, C, D synthesize Chunks 1..4 in parallel!

4. Crash & seamless recovery: Worker C crashes mid-call on Chunk 2. Its 60 s lease expires, the reaper
   resets Chunk 2 to pending, and Worker B finishes Chunk 2 before the listener even finishes Chunk 1
   (~45 s of buffered audio). Assembler normalizes raw PCM + pauses into one gapless MP3.

Key trade-offs

  • Proving long-document reliability vs. short-request proxy throughput. Focusing the 10-hour prototype on long documents exercises splitting, priority scheduling, lease recovery, and gapless assembly — whereas benchmarking thousands of tiny requests mostly measures the upstream TTS vendor's proxy. The trade-off is that high-QPS short-text load is sized analytically rather than load-tested in the prototype.
  • Hosted TTS API vs. self-hosted GPU fleet. Calling a hosted API behind an adapter needs zero GPU capacity management and ships immediately, at the cost of a per-key concurrency ceiling (50 in-flight calls -> ~33,000 chars/s) and linear pricing (~$15 per 1M characters). Self-hosting on GPUs drops unit cost to ~$0.74 per 1M characters at 100% utilization, but requires ~44 GPUs to match one hosted API key's burst rate and wastes money when traffic is spiky.
  • Ramped chunk sizes (200 -> 500 -> 1,000 chars) vs. uniform chunks. Tiny chunks everywhere minimize first-byte latency and retry cost but hurt prosody and multiply HTTP overhead; large chunks everywhere sound smooth but delay first playback. Ramping gets ~0.7 s synthesis on Chunk 0 and natural multi-sentence prosody on the rest.
  • Synchronous streaming (/v1/speech) vs. async job queue (/v1/narrations). Streaming delivers the lowest possible latency for short UI prompts, while async jobs survive client disconnects, support retries/caching, and produce downloadable files for articles and books — justifying two clean endpoints chosen by text length.
  • PostgreSQL FOR UPDATE SKIP LOCKED queue vs. dedicated message broker. Keeping chunks as SQL rows lets one transaction verify a worker's lease (a timed ownership token), update chunks_done, and log billing cleanly up to several hundred completions/s. Beyond a few thousand updates/s, row churn favors moving transient queue dispatch to Redis/SQS.
  • At-least-once synthesis with exactly-once state and billing. Because a worker can crash right after the TTS vendor responds, external synthesis cannot be strictly once-only; guarding SQL completion with lease_token and UNIQUE (narration_id, chunk_idx) on usage_events ensures progress counters, stitched audio, and customer charges remain strictly once-only.
  • Raw PCM / lossless FLAC intermediates vs. MP3 chunks. Storing uncompressed PCM (raw audio samples) or lossless FLAC uses more object-storage bandwidth than MP3, but eliminates MP3 frame-padding gaps so the final single-pass MP3 encode is completely seamless.

Common mistakes

  • Keeping a single HTTP connection open while synthesizing an entire book, guaranteeing timeouts at reverse proxies and losing 100% of progress if a mobile client drops offline.
  • Splitting text by fixed character offsets instead of sentence and paragraph boundaries, slicing words in half and creating jarring pitch resets.
  • Using large uniform chunks (1,500 chars) starting from Chunk 0, forcing interactive listeners to stare at a spinner while a whole page synthesizes before hearing word one.
  • Reporting total percentage (chunks_done / chunks_total) as playable audio when Chunk 2 failed and is retrying — listeners can only play the unbroken contiguous prefix from Chunk 0.
  • Byte-concatenating separately encoded MP3 chunks, which introduces ~20–50 ms of silent encoder padding (audible clicks/hiccups) at every seam.
  • Strict FIFO scheduling across jobs, allowing one bulk customer uploading 500 books to starve interactive users' second chunks instead of scheduling by playback deadline and per-tenant caps.
  • Reading the "default" voice or "latest" model dynamically per chunk, causing a voice change halfway through a book if a model upgrade rolls out mid-job.
  • Completing chunks without verifying lease_token, allowing a slow "zombie" worker whose lease expired to double-increment chunks_done or double-bill the customer.
  • Retrying HTTP 400 bad-input errors 5 times or hammering the provider on 429, instead of failing fast with character-offset diagnostics on 400 and backing off concurrency on 429.
  • Caching audio by (text, voice_name) alone, serving stale audio after model upgrades, speed changes, or pronunciation-lexicon edits, or leaking cross-tenant cache hits.

Follow-up questions

  • How can you minimize startup latency before playback begins on a book-length submission? Keep Chunk 0 short (1–2 sentences, ~200 characters -> ~0.7 s synthesis) and assign it priority = 0 so it jumps ahead of bulk chunks from older jobs in the queue. Stream-commit Chunk 0 and Chunk 1 to the database as soon as the splitter parses the opening paragraph rather than waiting to tokenize a 1,000,000-character book first. Finally, maintain warm HTTP/2 keep-alive connections to the TTS provider and stream Chunk 0's audio bytes directly to the waiting web player while Chunks 1..6 synthesize in parallel during Chunk 0's ~13 seconds of playback.
  • Which fields belong in the synthesis cache key so updates never return stale or mismatched audio? Hash a canonical JSON payload containing every input that can alter a single output sample: the normalized text, text-normalizer version, customer pronunciation-lexicon version, provider name, immutable dated model version (never an alias like "latest"), voice ID and version, synthesis parameters (speed, seed, sample_rate, format), hashes of any previous/next sentence prosody context, and customer_id. Including customer_id prevents cross-customer timing side-channels (where an instant cache hit reveals another customer synthesized that confidential sentence) and makes GDPR/account deletion clean, while any model or lexicon bump automatically produces a fresh SHA-256 key without manual cache invalidation.
  • When a newer synthesis model alters voice timbre, how do you deploy it without disrupting multi-chapter projects already in progress? Treat every model release as an immutable versioned artifact (tts-2026-03-15), copy that exact version into voice_snapshot when a narration or multi-document project is created, and let customers pin a model version at the project level. Gate every candidate model offline first using human A/B listening tests, an ASR (Automatic Speech Recognition — speech-to-text) round-trip check to catch skipped/hallucinated words, and speaker-embedding similarity against reference voice clips. Roll the new version out as the default only for newly created projects, keep pinned older versions alive across a published deprecation window (tracking upstream provider retirement dates), and if an old model must eventually retire, offer whole-document re-synthesis rather than ever mixing two model versions inside one audiobook.
  • How should the platform track billable consumption and enforce per-tenant rate and volume caps? Meter billable characters inside the chunk-completion transaction using usage_events with UNIQUE (narration_id, chunk_idx), guaranteeing worker retries and zombie lease completions never double-charge, while tagging cache_hit = true/false so repeated text can be discounted or billed transparently. Enforce limits at two layers: fast rate limits in Redis (token bucket — a counter that refills at a steady rate of characters/minute and caps bursts) plus active-job concurrency caps, and monthly character quotas enforced by reserving input_chars upfront at submission and refunding unused characters if a job fails or is canceled so parallel uploads cannot race past a customer's spending cap. Return HTTP 429 with Retry-After for transient rate limits and a distinct QUOTA_EXCEEDED code when a monthly budget is exhausted.

Follow-up questions

Similar questions

More Luma AI interview questions

All 7 Luma AI questions →