Skip to content
Shantanu Jumde
HomeWritingX-Counter

© 2026 Shantanu Jumde · Bengaluru

shantanu.contactme@gmail.com
All writing

Voice to admission note, without dirty data

The complete architecture for the doctor-dictation app. I stress-tested it over four design iterations until no new data holes turned up.

Healthcare AI Nov 2026 12 min read
How I tested itBig picture7 rulesRequest flowInside the workerStatesData modelWhat if…Key codeTech picksNot 100%
Before: the browser gives up at 30 seconds and the AI writes an orphan row at 45 seconds. After: the note is saved first, the browser can reconnect, and the AI fills the saved note.BeforeBrowser waitsgives upAI workingwrites a row nobodyis waiting forAfterEmpty draft + job saved firstreconnectsfills that same note0s15s30s45s60sThe fix in one line: save the note before the AI starts, and let the AI only fill it in.

How I tested it

Each version had to survive real failure cases: crashed workers, double clicks, doctors typing while the AI writes. Three versions didn’t, and I rejected them for the reasons below.

  1. v1

    Save first, retry key, careful writes

    Rejected

    Why I rejected it

    • The note saves, but adding it to the queue can fail
    • A frozen worker can wake up and write late
    • A retry pays for Whisper again
    • Big audio sent through the API times out and is lost
    • The model can send broken JSON
    • An AI result can wipe out what the doctor typed
  2. v2

    One database for notes and the queue

    Rejected

    What I changed

    • The queue lives in the same database
    • A fresh owner token for every claim
    • The transcript is saved as a checkpoint
    • Audio uploads go straight to storage
    • Strict schema plus validation
    • A late AI result becomes a suggestion

    Why I rejected it

    • A doctor can sign at the same moment the AI writes
    • Two tabs can edit the same draft
    • The cleanup job and a worker can race
    • Server clocks can disagree
    • Audio can be uploaded with no job ever started
    • Bad audio retries forever
  3. v3

    Signed notes are frozen in the database

    Rejected

    What I changed

    • The database blocks edits to signed notes
    • A version number on every save
    • Cleanup uses the same safe writes
    • Only the database clock is used
    • Storage auto-deletes stray audio
    • Max 3 tries, then fail loudly

    Why I rejected it

    • Hospital A could read hospital B’s data
    • A patient record can be merged mid-job
    • Live updates can drop, or OpenAI can be down
  4. v4

    Row-level security and fallbacks

    Shipped

    What I changed

    • Row-level security per hospital
    • Writes re-check that the note still exists
    • Polling fallback and a clear “AI delayed” state

    I ran all 21 “what if” cases below against v4. Every one ends with clean data. What’s left is in “Not 100%”.

Big picture

Numbers show the order things happen.

Why no Redis queue? The jobs table is the queue. Saving the note and queuing the job happen in one database transaction, so “saved but never queued” can’t happen. If you move to Redis or SQS later, add an outbox table to keep this guarantee.

The 7 rules

The failure cases below map back to these.

Save first

Draft, job and queue entry are saved together, before any AI work.

Same key, same job

Each “Generate” has a unique key. Repeats get the existing job back.

One owner at a time

A worker gets a fresh token when it claims a job. Writes without the current token are thrown away.

AI never overwrites a doctor

If the doctor edited during the AI run, the AI result becomes a suggestion.

Signed means frozen

The database itself refuses edits to signed notes. Fixes go in an addendum.

Everything expires

Leases, retries, unused drafts and raw audio all have time limits.

Timeouts are only a screen thing

The browser can leave and come back. Work and data never depend on it.

Request flow

The normal path, from mic to signed note.

Steps 8 to 12 keep running even if the doctor closes the tab. Reopening the note picks up where it is.

Inside the worker

Each step saves its result, so a retry skips work already done. A heartbeat extends the lease every 30s.

States

Two separate lifecycles. The job is the AI’s work. The note belongs to the doctor.

Job

Note

Only drafts are ever deleted. Signed notes are legal records and are kept.

Data model

One document table covers admission notes, discharge summaries and future types. Every row carries a hospital ID.

AI output is kept separately from the note. You can always see what the AI said versus what the doctor signed.

What if…

The 21 cases the final review checked. Tap one to see what happens.

What if the browser times out or the tab closes?

✓ Job keeps running. Reopening the note shows its current state.

Rule: Timeouts are only a screen thing
What if doctor taps Generate twice, or the network retries?

✓ Same key, so the second call returns the first job.

Rule: Same key, same job
What if aPI crashes before the transaction commits?

✓ Nothing was saved. The app retries with the same key.

Rule: Save first
What if aPI crashes right after saving?

✓ Draft and job are both saved, so a worker still picks it up.

Rule: Save first
What if live updates (SSE) drop?

✓ The 10s backup poll still finds the result.

Rule: Timeouts are only a screen thing
What if a worker dies mid-job?

✓ Its lease runs out. Cleanup re-queues the job with a new token.

Rule: Everything expires
What if a frozen worker wakes up after its job was handed to another?

✓ Its token is old, so its write changes 0 rows and is dropped.

Rule: One owner at a time
What if the same job is picked up twice?

✓ SKIP LOCKED lets only one worker claim it.

Rule: One owner at a time
What if cleanup and a worker act at the same moment?

✓ Both use conditional updates. Only one wins.

Rule: One owner at a time
What if server clocks disagree?

✓ Every lease time uses the database clock, now().

Rule: Everything expires
What if corrupt audio fails every time?

✓ After 3 tries the job is FAILED and the team is alerted.

Rule: Everything expires
What if whisper worked but GPT failed?

✓ Retry reuses the saved transcript. Whisper is not paid twice.

Rule: Checkpoints in the worker
What if gPT returns broken or missing fields?

✓ Schema check fails, it retries. Then it fails and shows the transcript.

Rule: Everything expires
What if openAI is down or rate-limited?

✓ Jobs back off and wait. Doctor sees “AI delayed”.

Rule: Timeouts are only a screen thing
What if doctor types in the note while AI is running?

✓ Version changed, so the AI result becomes a suggestion.

Rule: AI never overwrites a doctor
What if doctor signs at the exact moment AI writes?

✓ AI write needs status DRAFT. The database lock blocks signed edits.

Rule: Signed means frozen
What if two tabs edit the same draft?

✓ Saves need a matching version. The second tab is told to reload.

Rule: AI never overwrites a doctor
What if doctor cancels the generation?

✓ Job is CANCELLED. Worker stops at the next step. Late writes fail.

Rule: One owner at a time
What if a user from hospital A asks for hospital B’s note?

✓ Row-level security returns nothing.

Rule: Row-level security
What if audio was uploaded but Start was never called?

✓ Storage deletes untagged audio after 24h.

Rule: Everything expires
What if patient is merged or the draft is deleted mid-job?

✓ The final write finds no draft. 0 rows change and the result is dropped.

Rule: One owner at a time

Key code

The four pieces that make the rules real. Prisma and Postgres.

1. Start: save first, same key returns same job

// tRPC mutation
try {
  return await db.$transaction(async (tx) => {
    const doc = await tx.clinicalDoc.create({
      data: { hospitalId, patientId, doctorId, docType: "ADMISSION", status: "DRAFT", version: 0 },
    });
    return tx.generationJob.create({
      data: { idempotencyKey: input.key, docId: doc.id, audioKey: input.audioKey,
              baseVersion: 0, status: "QUEUED" },
    }); // the job row IS the queue entry
  });
} catch (e) {
  // unique key clash = this is a retry; the whole losing transaction rolled back
  if (isUniqueViolation(e)) return db.generationJob.findUniqueOrThrow({ where: { idempotencyKey: input.key } });
  throw e;
}

2. Claim: one worker per job, fresh token

UPDATE generation_job
SET status = 'RUNNING', attempt = attempt + 1,
    lease_token = gen_random_uuid(), lease_until = now() + interval '2 minutes'
WHERE id = (
  SELECT id FROM generation_job
  WHERE status = 'QUEUED' AND run_after <= now()
  ORDER BY created_at
  FOR UPDATE SKIP LOCKED   -- two workers never grab the same job
  LIMIT 1)
RETURNING id, lease_token;

3. Finish: the fenced write

await db.$transaction(async (tx) => {
  const won = await tx.generationJob.updateMany({
    where: { id: jobId, leaseToken: myToken, status: "RUNNING" },
    data: { status: "SUCCEEDED" },
  });
  if (won.count === 0) return;  // lost the lease or cancelled: drop result

  const applied = await tx.clinicalDoc.updateMany({
    where: { id: docId, status: "DRAFT", version: baseVersion }, // untouched draft only
    data: { content: fields, version: { increment: 1 } },
  });
  await tx.aiResult.create({ data: { jobId, fields, model, tokens, applied: applied.count === 1 } });
  // applied = false means the doctor edited first: show as a suggestion
});

4. Cleanup and the signed-note lock

-- every minute: rescue jobs whose worker died
UPDATE generation_job
SET status = CASE WHEN attempt >= 3 THEN 'FAILED' ELSE 'QUEUED' END,
    lease_token = NULL, run_after = now() + attempt * interval '30 seconds'
WHERE status = 'RUNNING' AND lease_until < now();

-- the database refuses any change to a signed note
CREATE FUNCTION block_signed() RETURNS trigger AS $$
BEGIN
  IF OLD.status = 'SIGNED' THEN RAISE EXCEPTION 'signed notes are read-only'; END IF;
  RETURN COALESCE(NEW, OLD);
END $$ LANGUAGE plpgsql;

CREATE TRIGGER signed_lock BEFORE UPDATE OR DELETE ON clinical_doc
FOR EACH ROW EXECUTE FUNCTION block_signed();

Tech picks

PartPickWhy
FrontendNext.js + tRPCWhat you already have
Live updatesSSE, polling every 10s as backupInstant when it works, still correct when it drops
DatabasePostgres via Prisma, row-level securityOne place for data and queue, so one transaction
QueueThe jobs table with SKIP LOCKEDNo extra system, no dual-write gap
Wake workersPostgres LISTEN / NOTIFYNo busy polling of the table
AudioS3-compatible bucket, signed upload linksBig files skip the API; storage deletes stray audio after 24h
AIWhisper + GPT structured outputsSchema-shaped JSON, then checked again with Zod
AI hostingZero data retention, or an India-region deploymentPatient data rules (DPDP Act)
ScalingMore workers, each with a concurrency limitStays under AI rate limits
MonitoringOpenTelemetry traces tagged with jobIdFollow one note end to end; no patient text in logs

Not 100%: what’s left

No system is perfectly safe. These are outside what code can fix, so each has a plan.

The AI can be wrong

Doctor must review and sign. Show the transcript beside the fields and mark which fields AI filled.

Database goes down

Nothing saves. Use point-in-time backups and a standby replica.

“Exactly once” is impossible

Jobs may run twice. The design makes running twice harmless instead.

AI provider outage

Jobs wait and retry. The doctor sees “AI delayed” and can type the note by hand.

Legal and data rules

Needs a data agreement with the AI provider and patient consent handling. Check with your compliance team.

Built from the original whiteboard: FE, BE, Whisper, OpenAI, queue, worker, Postgres. Same parts, safer order.