A pharmaceutical medical-information team answers clinicians’ unsolicited questions using approved literature and internal evidence. Design a full-stack system that finds evidence, drafts a response with sentence-level citations, supports a six-stage human workflow, and produces an audit-ready final document. Quality matters more than raw latency.
The Citation Is the Product
Design an evidence-grounded medical response authoring system whose drafts, human edits, citations, evaluations, and release decisions survive regulatory scrutiny.
Opening prompt
The interviewer gives a deliberately broad application problem. The candidate creates structure before drawing boxes.
I’ll treat this as regulated decision support, not autonomous medical advice. Before architecture I need to identify the authorized corpus, author/reviewer roles, document classes, validation boundary, and cost of omission versus extra content. My invariant is: a factual sentence cannot reach approval without a stable pointer to visible source evidence and the exact artifact versions that produced it.
I’ll separate the immutable AI draft from human-edited versions so we can measure the model honestly. Humans remain final authorities; the system may abstain, flag gaps, and re-draft, but never invent a source or silently rewrite an approved response.
Scope the contract
Actors, boundaries, correctness, latency, and what deliberately waits for a later phase.
State your assumptions, users, required capabilities, nonfunctional goals, and what is out of scope.
Actors are request coordinators, medical writers, literature-search specialists, medical/legal/regulatory reviewers, approvers, corpus curators, validation engineers, tenant administrators, and auditors. Required flow: classify the question; freeze a search protocol; ingest approved PDFs; retrieve evidence with page regions; create an outline and draft; verify every sentence; preserve pre-edit and post-edit snapshots; route stage approvals; export to the customer’s document system; and assemble a reproducibility package.
Mock goals: 99.9% authoring-plane availability, RPO under 5 minutes and RTO under 2 hours; interactive edits p95 under 300 ms; literature retrieval p95 under 3 seconds; first draft under 10 minutes; seven-year retention; tenant and therapeutic-area isolation. Out of scope: diagnosing patients, choosing treatment, replacing the source-of-record document system, and training a foundation model. We integrate with those boundaries.
Writers, search specialists, medical/legal/regulatory reviewers, approvers, corpus curators, auditors, and tenant admins.
Question intake, versioned corpus, evidence retrieval, atomic-claim drafting, citations, six human stages, export, impact analysis.
No unsupported approved claim; visible source provenance; immutable pre-edit draft; explicit final human authority.
99.9% authoring plane, p95 edits <300 ms, draft <10 min, RPO <5 min, RTO <2 h, seven-year audit.
PHI/PII minimization, therapeutic-area ABAC, regional storage, tenant keys, approved model endpoints, break-glass audit.
Diagnosis, treatment selection, foundation-model training, source DMS replacement, automatic regulatory approval.
Back-of-the-envelope math
These numbers are supplied mock constraints. Change them to see where the design bends.
Use these mock constraints: 2,000 response requests/day, 20 source PDFs/request, 15 pages/PDF, 100 KB/page, 50 factual sentences/response, two citations/sentence, and a 12× ingestion burst. For a conservative upper bound, assume every referenced PDF is new until content-digest deduplication proves otherwise. Do the math.
That worst case is 600,000 pages/day, 6.94 pages/s average and about 83 pages/s at peak. At two CPU-seconds per page, peak OCR/layout work consumes 167 cores continuously; with 30% headroom I provision about 217 cores or an equivalent autoscaling queue. We create 100,000 factual sentences and 200,000 citation edges/day.
Raw sources are about 60 GB/day or 153 TB over seven years before replicas. Content-addressed intake avoids re-OCR and duplicate storage when requests reuse the same authorized source, so I would measure the unique-digest ratio and plan both the upper bound and observed case. If an append-only decision record averages 3 MB/response, that adds 6 GB/day or 15.3 TB. Search vectors are derived and rebuildable; raw bytes, page coordinates, snapshots, approvals, and manifests are authoritative. The architecture changes with page volume, uniqueness, and retention—not API QPS.
Corpus, citations, and OCR capacity
Data, keys, and APIs
Names turn ambiguous boxes into durable contracts. The primary keys below are part of the answer.
Give me concrete records, keys, and APIs. How do you prevent a mutable citation from pointing somewhere else later?
Every object is tenant-scoped and content-addressed. A source version has a SHA-256 digest; a page render has source digest, page number, renderer version, and render digest. An evidence span stores normalized text plus page polygon and crop digest. A sentence version cites evidence-span IDs, never “the latest PDF.”
The response is an append-only version DAG. AI_DRAFT, HUMAN_EDIT, and APPROVED are distinct snapshots; a materialized head only accelerates reads. A workflow transition uses an expected-version precondition and idempotency key. Corpus publication and response approval are separate authorities.
Records and access paths
| Record | Primary / idempotency key | Important immutable fields | Main access path |
|---|---|---|---|
SourceVersion | (tenant_id, source_digest) | bytes hash, publication metadata, authorization, retraction/effective time | digest lookup; corpus membership |
EvidenceSpan | (tenant_id, span_id) | source digest, page, polygon, crop hash, channel, parser version | by source/page; lexical/vector retrieval |
CorpusRelease | (tenant_id, corpus_release_id) | ordered source digests, policy digest, signature, published_at | active release per therapeutic area |
ResponseVersion | (tenant_id, response_id, version_no) | parent, kind, content hash, corpus/model/prompt manifest | version DAG; current materialized head |
ClaimCitation | (sentence_version_id, claim_no, span_id) | entailment state, verifier/calibrator versions, rationale | reverse impact by source; coverage by response |
StageDecision | (response_version_id, stage, decision_id) | actor, role, expected version, reason, timestamp | stage history; audit export |
JudgeEvaluation | (candidate_digest, rubric_version, evaluator_id) | score vector, calibration set, drift cohort | release comparison by slice |
External contract
POST /v1/tenants/{t}/requests Idempotency-Key: external_request_id
POST /v1/corpora/{id}/sources returns source_digest + processing job
POST /v1/corpora/{id}/releases If-Match: corpus_version
POST /v1/responses/{id}/drafts corpus_release_id, model_route_id
PATCH /v1/responses/{id}/versions/{n} If-Match: content_digest
POST /v1/responses/{id}/stage-decisions Idempotency-Key: decision_id
GET /v1/evidence/{span_id}/crop short-lived authorized image
GET /v1/responses/{id}/audit-bundle original bytes + manifests + approvals
POST /v1/sources/{digest}/retractions effective_at, severity, reasonEnd-to-end architecture
Control truth stays authoritative; expensive or probabilistic work is asynchronous, bounded, and replayable.
Walk me through the architecture and one request end to end.
The control plane stores tenant policy, corpus releases, workflow state, permissions, and version manifests in a transactional database with an outbox. Source bytes and immutable snapshots go to encrypted object storage. Async workers render/OCR, detect layout, chunk evidence, and populate lexical plus vector indexes scoped to a published corpus release.
A request freezes a query protocol and corpus digest. The retrieval planner produces auditable searches; a drafting worker receives only authorized evidence and an output schema. The citation verifier performs entailment and deterministic page-span checks sentence by sentence. Unsupported text is rejected or routed to the writer as a gap. Humans edit in a collaborative UI, but each stage approval snapshots content. Export uses a receiver idempotency key; the audit service composes bytes, versions, decisions, and approvals from immutable IDs.
Ground every atomic claim
A citation is a versioned relationship to visible evidence—not a decorative reference at paragraph end.
Deep dive on grounding. A paragraph mixes three claims, one citation is only partially supportive, and the PDF has an OCR layer different from the visible scan.
I split claims into atomic propositions before validation. Each proposition needs one or more source spans that jointly entail it; citation coverage and source authority are separate signals. The UI highlights exactly which phrase is supported by which page region and shows conflicts. An unsupported clause cannot borrow credibility from a supported neighbor.
Visible rendered content is authoritative. Native text helps locate candidates, but we compare its geometry with rendered pixels and OCR; hidden, off-crop, or contradictory text is quarantined. The verifier records SUPPORTED, PARTIAL, CONFLICTED, or UNSUPPORTED, model/calibrator versions, evidence IDs, and rationale codes. Only supported claims can move to approval; partial claims require edit or explicit sourced qualification.
| State | Meaning | Permitted action |
|---|---|---|
SUPPORTED | All material qualifiers entailed by visible authorized evidence. | May advance to human approval. |
PARTIAL | Core idea supported; qualifier, population, or magnitude is not. | Edit/split/qualify; cannot approve as-is. |
CONFLICTED | Authorized sources materially disagree. | Show conflict and escalate to expert. |
UNSUPPORTED | No admissible source span entails the claim. | Delete, retrieve more evidence, or abstain. |
Measure the machine before the human fixes it
Immutable snapshots, F2, blinded adjudication, slice gates, and judge calibration prevent flattering but meaningless scores.
How do you evaluate drafts? Explain F2, golden sets, immutable pre/post snapshots, and an LLM judge without fooling yourself.
We snapshot the untouched AI output before any human sees it, then snapshot every human stage. Otherwise edits leak into “model quality.” At the content layer I measure evidence recall, unsupported-claim rate, citation correctness, omission severity, and atomic-claim F2: F2 = 5PR / (4P + R), weighting recall four times precision because an omitted safety fact can be worse than a modest extra supported sentence.
The golden set is stratified by therapeutic area, question type, document difficulty, and known failure modes; it is double-reviewed with adjudication and versioned. Two independent rubrics cover factual/evidence quality and tone/regulatory form. An LLM judge may scale scoring only after correlation, disagreement, and calibration against the frozen human set. We blind human reviewers, keep a sentinel set out of prompt development, monitor judge-control charts, and rebaseline quarterly. Human edits are weak labels until adjudicated—they may reflect preference, not truth.
| Gate | Why aggregate is insufficient |
|---|---|
| Zero catastrophic unsupported safety claims | A mean can hide rare, severe harm. |
| Minimum F2 per therapeutic/question slice | Easy common questions dominate a global score. |
| Judge/human disagreement control chart | The scalable evaluator itself drifts. |
| Pre→post edit distance + reasons | Separates factual correction from style preference. |
Failure injection I
The design changes under pressure. The candidate preserves correctness before convenience.
A source paper is retracted after 4,000 approved responses cited it. Search has already indexed the replacement corpus. What changes?
I do not delete or mutate history. Corpus release R17 marks the source retracted with effective time and reason; new authoring excludes it. A reverse citation index finds every claim and approved response pinned to the old source digest. The impact job is idempotent on (retraction_id,response_version_id) and opens risk-ranked remediation cases.
The original response remains reproducible and visibly “superseded/source retracted.” High-severity cases pause distribution and notify owners; lower severity enters review. Corrected responses create new versions and preserve who approved the change. If the index is stale, the authoritative citation table drives a slower complete scan. Retraction propagation has its own SLO and completeness reconciliation.
Failure injection II
Partial failure, stale inputs, duplication, and unknown external outcomes are normal distributed states.
The new model improves aggregate F2 from .88 to .91, but oncology safety omissions double. At the same time the LLM judge score rises. Ship it?
No. Aggregate improvement cannot average away a safety regression. The release gate includes hard catastrophic-error counts and minimum slice thresholds; oncology stays on the old model. The judge/model correlation is suspicious because both may share failure modes. I freeze the rollout, send disagreements to blinded clinicians, inspect retrieval coverage separately from generation, and test whether the judge prompt or corpus shifted.
I can canary the new model only on validated low-risk slices behind a routing manifest, shadow it elsewhere, and log both outputs without showing the candidate draft to reviewers. Recovery is an atomic route-pointer rollback; existing response versions stay pinned to their original model and judge versions.
Security and operations
Tenant isolation, backpressure, observability, evaluation, SLOs, recovery, and cost belong in the core design.
Cover consistency, duplicate jobs, backpressure, security, tenant isolation, observability, and disaster recovery.
Strong consistency applies to corpus publication, workflow transitions, approvals, authorization, and export intent. Search/index freshness is eventual and always displays the indexed corpus digest. Workers consume at least once; stage keys combine tenant, immutable input digest, stage version, and parameters, so retries reuse an output or create one result. A transactional outbox prevents state/event gaps; external export resolves timeouts with receiver lookup rather than blind retry.
Admission control and weighted tenant queues separate live authoring from backfill/evaluation. Poison PDFs have bounded resource sandboxes and DLQs. ABAC checks tenant, therapeutic area, purpose, stage, and break-glass; per-tenant envelope keys and region-pinned storage isolate data; model calls use approved zero-retention endpoints or in-VPC models. Observe queue age, stage latency/error, unsupported claims, citation coverage, reviewer override, F2 by slice, judge drift, export reconciliation, audit completeness, and access anomalies. Multi-region metadata uses warm standby; immutable objects are cross-region replicated and restore is rehearsed.
Request/error/latency/saturation for authoring, queues, OCR, retrieval, model, verifier, export.
Unsupported-claim rate, evidence recall, F2, citation correctness, omissions, reviewer override, judge drift by slice.
Per-stage queues, tenant fairness, live/replay isolation, bounded retries, poison-source DLQ, optional enrichment shedding.
CAS stage transitions; corpus publication transaction; at-least-once idempotent stages; outbox and export reconciliation.
Tenant/area ABAC, envelope keys, region pins, filtered indexes, no raw content in metrics, approved model routes.
Cross-region immutable objects, warm metadata standby, manifest restore, periodic audit-bundle and export reconciliation drills.
Rollout and trade-offs
A credible production answer defines how it earns trust and how it retreats safely.
How do you roll this out, and what trade-off would you call out to an executive?
First shadow retrieval against historical requests; then give writers evidence search only; then draft in reviewer-only mode; then canary a narrow therapeutic area with dual human scoring; then permit assisted authoring while final approval remains human. Every phase has rollback, frozen baselines, and predefined quality/latency/cost gates. We validate the actual signed release artifact in a clean environment, not a developer checkout.
The central trade-off is throughput versus defensible completeness. Atomic claims, page crops, immutable snapshots, and staged approval cost storage and reviewer time, but enable safe iteration and honest evaluation. I would not promise “fully autonomous authoring”; I would promise measured assistance with explicit abstention and traceable human authority.
- Freeze historical benchmark and harmful-error taxonomy.
- Shadow retrieval and verify source recall without showing drafts.
- Release evidence-search assistant to writers; measure search misses.
- Reviewer-only drafts with blinded AI/non-AI quality comparison.
- Canary one low-risk therapeutic/question slice behind a route manifest.
- Expand only after human, citation, F2, latency, cost, and audit gates pass.
- Keep instant route rollback and retraction-impact replay.
- Validate the signed clean deployment artifact end to end.
One-minute spoken recap
Practice this synthesis until it sounds conversational rather than memorized.
Give me the one-minute summary.
I’ll summarize the source of truth, safety boundary, scale path, and rollout.
Reference shelf
Definitions, traps, and the final checklist stay outside the timed mock.
- Atomic claim
- The smallest proposition that can be independently supported or contradicted.
- Bounding box / polygon
- Coordinates identifying the visible region of a rendered source page.
- Corpus release
- An immutable, signed set of authorized source versions for a scope and effective time.
- F2 score
- An F-score that weights recall four times as strongly as precision.
- Golden set
- A frozen, adjudicated sample used to evaluate systems and calibrate scalable evaluators.
- Judge drift
- Change in an automated evaluator’s relationship to human judgment over time or slices.
- Pre-edit snapshot
- The immutable AI output captured before human correction; essential for honest measurement.
- Retraction impact
- Reverse lineage from a withdrawn source to every claim and response that used it.
- RAG
- Retrieval-augmented generation: generation conditioned on retrieved source material.
- Weak label
- A signal such as an edit that may not equal ground truth without adjudication.
- WORM
- Write-once, read-many retention that resists silent mutation.
- Outbox
- A transactionally written event record relayed asynchronously to avoid state/event gaps.
- Keeping only the human-polished draft and then claiming it as model quality.
- Citing a whole paper when only a sentence or qualifier needs support.
- Trusting hidden PDF text over the visible page.
- Using one aggregate F2 while a safety-critical slice regresses.
- Treating an LLM judge as ground truth because it is cheap.
- Training on reviewer edits without separating truth corrections from style.
- Mutating old responses after a source retraction.
- Pointing citations to mutable “latest” documents.
- Allowing the model to approve or export its own answer.
- Mixing tenant corpora in vector indexes or evaluation sets.
- Blindly retrying an external export after a timeout.
- Testing prompts and model separately from the signed release artifact.
- Clarified actors, authority, business harm, and out-of-scope.
- Did correct BOTEC and named the variable that changes the architecture.
- Defined stable IDs, versions, access paths, and idempotency keys.
- Separated authoritative state from derived indexes and model output.
- Explained consistency, retries, backpressure, and unknown outcomes.
- Revised the design after both failure injections.
- Covered tenant isolation, secrets, least privilege, deletion, and audit.
- Named golden signals, domain quality metrics, rollout gates, and rollback.