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.
Save first, retry key, careful writes
RejectedWhy 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
One database for notes and the queue
RejectedWhat 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
Signed notes are frozen in the database
RejectedWhat 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
Row-level security and fallbacks
ShippedWhat 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.
Draft, job and queue entry are saved together, before any AI work.
Each “Generate” has a unique key. Repeats get the existing job back.
A worker gets a fresh token when it claims a job. Writes without the current token are thrown away.
If the doctor edited during the AI run, the AI result becomes a suggestion.
The database itself refuses edits to signed notes. Fixes go in an addendum.
Leases, retries, unused drafts and raw audio all have time limits.
The browser can leave and come back. Work and data never depend on it.
Request flow
The normal path, from mic to signed note.
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
Data model
One document table covers admission notes, discharge summaries and future types. Every row carries a hospital ID.
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 thingWhat if doctor taps Generate twice, or the network retries?
✓ Same key, so the second call returns the first job.
Rule: Same key, same jobWhat if aPI crashes before the transaction commits?
✓ Nothing was saved. The app retries with the same key.
Rule: Save firstWhat if aPI crashes right after saving?
✓ Draft and job are both saved, so a worker still picks it up.
Rule: Save firstWhat if live updates (SSE) drop?
✓ The 10s backup poll still finds the result.
Rule: Timeouts are only a screen thingWhat if a worker dies mid-job?
✓ Its lease runs out. Cleanup re-queues the job with a new token.
Rule: Everything expiresWhat 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 timeWhat if the same job is picked up twice?
✓ SKIP LOCKED lets only one worker claim it.
Rule: One owner at a timeWhat if cleanup and a worker act at the same moment?
✓ Both use conditional updates. Only one wins.
Rule: One owner at a timeWhat if server clocks disagree?
✓ Every lease time uses the database clock, now().
Rule: Everything expiresWhat if corrupt audio fails every time?
✓ After 3 tries the job is FAILED and the team is alerted.
Rule: Everything expiresWhat if whisper worked but GPT failed?
✓ Retry reuses the saved transcript. Whisper is not paid twice.
Rule: Checkpoints in the workerWhat if gPT returns broken or missing fields?
✓ Schema check fails, it retries. Then it fails and shows the transcript.
Rule: Everything expiresWhat if openAI is down or rate-limited?
✓ Jobs back off and wait. Doctor sees “AI delayed”.
Rule: Timeouts are only a screen thingWhat if doctor types in the note while AI is running?
✓ Version changed, so the AI result becomes a suggestion.
Rule: AI never overwrites a doctorWhat if doctor signs at the exact moment AI writes?
✓ AI write needs status DRAFT. The database lock blocks signed edits.
Rule: Signed means frozenWhat if two tabs edit the same draft?
✓ Saves need a matching version. The second tab is told to reload.
Rule: AI never overwrites a doctorWhat if doctor cancels the generation?
✓ Job is CANCELLED. Worker stops at the next step. Late writes fail.
Rule: One owner at a timeWhat if a user from hospital A asks for hospital B’s note?
✓ Row-level security returns nothing.
Rule: Row-level securityWhat if audio was uploaded but Start was never called?
✓ Storage deletes untagged audio after 24h.
Rule: Everything expiresWhat 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 timeKey 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
| Part | Pick | Why |
|---|---|---|
| Frontend | Next.js + tRPC | What you already have |
| Live updates | SSE, polling every 10s as backup | Instant when it works, still correct when it drops |
| Database | Postgres via Prisma, row-level security | One place for data and queue, so one transaction |
| Queue | The jobs table with SKIP LOCKED | No extra system, no dual-write gap |
| Wake workers | Postgres LISTEN / NOTIFY | No busy polling of the table |
| Audio | S3-compatible bucket, signed upload links | Big files skip the API; storage deletes stray audio after 24h |
| AI | Whisper + GPT structured outputs | Schema-shaped JSON, then checked again with Zod |
| AI hosting | Zero data retention, or an India-region deployment | Patient data rules (DPDP Act) |
| Scaling | More workers, each with a concurrency limit | Stays under AI rate limits |
| Monitoring | OpenTelemetry traces tagged with jobId | Follow 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.
Doctor must review and sign. Show the transcript beside the fields and mark which fields AI filled.
Nothing saves. Use point-in-time backups and a standby replica.
Jobs may run twice. The design makes running twice harmless instead.
Jobs wait and retry. The doctor sees “AI delayed” and can type the note by hand.
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.