Build diary Day 12

Day 12: Production Readiness, and Cally Finds Its Voice

Built with Giridhar, Venkatakrishna and Preetha

Building the Caladrius PHR with agents Part 12 of 15

16 min read

Hand-drawn sketch of a locked database, encrypted backups, a checklist, a circuit switch and a metrics chart leading to a person speaking into a microphone, with a sound wave

The PHR is built by a small Caladrius team (Giri, Krishna, Preetha and me) working with AI agents; each post ends with what the day meant for each of our areas.

Day 11 ended with a review: twenty-two production-readiness and system-design items, each marked done, partial, missing or “not needed yet”, with the evidence and the gap. Day 12 merged that review’s first items and built the rest. It was the second-busiest day of the project by pull requests, after 9 November: 54 merged on 11 November (51 into dev and three promotions to QA), from 263 commits (128 not counting merges).

Two tracks ran side by side:

  1. Production readiness: encrypted backups with a restore drill, least-privilege database roles, indexes from an EXPLAIN of every statement, idempotency keys, retries with jitter, circuit breakers, metrics and tracing, CI guardrails, and a load test.
  2. Cally Voice: talking to Cally instead of typing, and hearing the answer read aloud.

I’ll take them in that order, then say what changed about how the day’s work was landed.


1. The rule for the readiness track

Every readiness item followed the same rule: one item at a time, approved before it starts, built once in the platform layer when every app needs it. Retries, idempotency and circuit breakers aren’t PHR features; any Caladrius API needs them. So they went into @caladrius/server-core behind ports (no environment reads, no network calls of its own) and were adopted by the PHR API in the same pull request. A future app gets them by importing a package, not by copying a file.

2. Backups you can restore, encrypted before they touch the disk

The review’s finding was blunt: there was no backup with a tested restore. That’s the item I fixed first, because everything else is recoverable and lost patient data is not.

What was built (scripts, tests and a runbook; installing it on a host is a separate, deliberate step):

The lesson that shaped the runbook: a backup of encrypted data without its keys is useless. Personal fields in the PHR are encrypted at rest, so the runbook treats safekeeping of the keys as part of the backup itself, and the drill proves a restore can actually be read. Tests run the whole cycle, including the failures.

3. The API stops running with full database rights

The second finding: the API connected to the database with the same all-powerful account used to set it up. That’s common in early projects, and it quietly undoes other protections. Our audit log is append-only and tamper-evident, and an account with full rights could switch those protections off. A single injection or code bug would have been able to rewrite the very trail meant to catch it.

The fix is least privilege. Setting up the database and running the API now use separate accounts. The API’s account can read and write data but cannot change the schema or the protections around it. The audit trail is tighter still: the API can add to it but not change or remove it, and only the database’s own sealing step can seal it.

The test I like best tries those attacks as the API’s account, and each must be refused by the database itself. And the end-to-end tests now run the API with the same reduced rights, so every NHA test case also proves the API needs nothing more.

4. Indexes from an EXPLAIN of every statement

For “slow queries → indexes” the agent didn’t guess at hot paths. It harvested every static SQL string in the API and the packages through the TypeScript AST (465 statements) and planned each one with EXPLAIN (GENERIC_PLAN) against the migrated schema, with sequential scans disabled. A plan that still scans a whole table has no index it can use. A catalogue query added foreign keys that no index covers. No data was needed, so the method is deterministic and runs in CI.

It found 23 missing indexes. A few were for queries that read whole tables (for example, staff listed from a users table that also holds every patient). Most were foreign keys in the patient-data tree: deleting an account cascades through 34 tables, and without those indexes each cascade step scans its whole child table. That matters for the right to erasure.

It also found a real bug. The console’s audit list selected seq::text AS seq … ORDER BY seq. PostgreSQL resolves an unqualified ORDER BY name to the output column, so the audit log was sorted as text (99 after 100), the page cursor skipped or repeated rows once sequence numbers crossed a power of ten, and the query could never use the primary key. One qualified column name fixed it, and the plan test asserts an index walk with no sort. The agent then scanned all 465 statements for the same alias pattern. It was the only one.

5. Idempotency keys: a double tap is not two consents

On a phone with a poor connection, people tap twice, and clients retry after a timeout. For a consent decision, a link to a hospital, a booking or an ABDM call, a duplicate is a real-world event. The review found idempotency only on inbound ABDM callbacks, not on our own writes.

The middleware, built once in server-core, works like this:

It went onto 31 routes: consent decisions, linking, sharing, subscription approvals, record pulls, locker set-up and uploads, UHI bookings, form responses and staff invitations. The sign-in steps and ABDM callbacks were left out on purpose: they’re already bound to single-use flow ids, or idempotent by design. On the client side, the shared session client sends the header on every idempotent write.

6. Retries with full jitter, and what we refuse to retry

A transient failure (a dropped connection, a 429, a 503) shouldn’t reach the person, and a recovering service shouldn’t be hit by every client at the same moment. withRetry in server-core uses full jitter: attempt n waits a random time in [0, min(cap, base·2ⁿ⁻¹)), inside a total budget, honouring Retry-After only when it fits. The clock, sleep and random source are injected, so tests never wait, and the randomness comes from crypto.randomInt, never Math.random.

The more important half of the design is what is not retried:

Caller Retried Sent once
ABDM every GET, each attempt with a fresh request id, logged before it’s sent every POST/PUT/PATCH/DELETE: an OTP, a link, a consent started twice is the duplicate we’re avoiding
Terminology, identity provider lookups and key sets token requests
UHI the reference lists the signed gateway requests
Model and speech vendors the model list every call that carries a person’s words or audio

That last row is a privacy decision, not a reliability one. Each attempt to send a person’s question or voice to a vendor is one more disclosure of personal data, and it must be audited as one. So those calls make one attempt, and a test asserts it.

The first version had a subtle bug. The classifier cancelled a response body before it knew whether a retry would follow, so the final 503 came back with an unreadable body. The fix was an explicit discard hook that runs only when a retry really happens, with a test that the last answer’s body can still be read.

7. Circuit breakers, metrics, tracing and alerts

Circuit breakers sit inside the retry and the timeout, one per outside dependency: ABDM, the UHI gateway, the model provider, terminology, the identity provider, and the speech provider. Each is closed, open or half-open (with one probe), driven by the failure rate over a rolling window. A retry never retries an open circuit. When ABDM is down, the person sees the existing “try again later” message with a Retry-After, instead of a long spinner per tap.

Metrics are on an internal endpoint the public can’t reach. They cover rate, errors and duration by route (never a raw path, which could contain an id), the database pool, breaker states, rate-limit refusals, Cally call counts and durations (never content), and the audit-chain verification.

Tracing starts at nginx, which sets a request id. The API accepts it only from a trusted proxy, and carries it through every log line with AsyncLocalStorage.

Alerts are in-process for now, sent to a staff webhook with no personal data: a high 5xx rate, a breaker opening, the audit chain failing verification, a spike in sign-in or OTP 429s, the pool exhausted, a stale backup.

8. Guardrails: turning conventions into tests

The readiness review’s sharpest point was that some protections were conventions, not invariants. Four CI guardrails changed that:

The guardrails found five things on their first run, among them some write routes that ignored a body instead of rejecting one, and a couple of callbacks that checked their payload by hand instead of with a schema. They were closed the same day. That’s what a guardrail is for: the first run finds the backlog, and every later run keeps it empty.

9. A load test that measures, and what it found

The load test was explicitly measure only. It starts the API against a disposable, migrated database, seeds synthetic patients with live sessions, and drives eight scenarios with autocannon. The global, sign-in and OTP rate limiters stay on: each request comes from its own synthetic client address. It refuses to run against a database that isn’t local and named as disposable.

The first baseline, on a single shared test machine:

The memory growth turned into a fix. With hundreds of thousands of distinct client addresses, the rate limiter’s in-memory fallback kept one counter per address, with no bound inside its window. In production the counters live in Redis and the sensitive tiers fail closed, but the fallback still needed a ceiling. The new BoundedMemoryStore caps the keys and has two modes, and the difference matters:

Evicting a brute-force counter would let an attacker reset their own count by flooding the table with made-up keys. So a test pins that no fail-closed tier is ever given an evicting store.

10. Cally Voice

The other track was voice. A personal health record in India has to work for people who would rather speak than type, in their own language. Cally Voice lets a person ask Cally a question aloud and choose to hear the answer.

It’s a port of the voice feature in AI Studio. The original files were vendored verbatim first, then re-implemented here in TypeScript with the PHR’s rules. The pieces:

browser (PHR app)            PHR API                         voice worker
  mic tap ──► /cally/voice/session ──► LiveKit join token     (LiveKit agent)
  WebRTC  ◄───────────── self-hosted LiveKit, same origin ─────►  speech-to-text,
  or record ──► /transcribe, /speak (fallback)                    read-aloud
                         └── speech provider in India ◄──────────┘

The design choices, mostly privacy choices:

By the end of the day the API routes, the worker, the conversation bar with its Talk button, and the QA hosting were all merged, every piece of it off by default. Switching it on was left for a later day, behind a privacy decision.

11. Landing all open work at once

One process change was as important as any feature. By the afternoon, many agent sessions had stacked pull requests on each other’s branches: voice on Cally theming, breakers on retries. Merging them one by one would have meant thirty CI runs on a busy CI and a long chain of rebases.

So I decided to land everything at once: one landing branch, all open work merged into it bottom-up, conflicts resolved once (changelogs unioned, migration lists ordered), one CI run instead of about thirty, then, the next morning, a promotion to QA, where I reviewed the merged result as a whole. It’s a deliberate trade. You lose a clean review per pull request, and you gain a single, tested integration, reviewed in the place it will actually run.

12. What I learned on Day 12

Next, Day 13 (12 November): the repository takes over the process. A software factory with a charter, agents, a gate and a dashboard; jobs that start only from an approved issue; Node 24; and an AWS deploy target for the full stack.

The team behind Day 12

The PHR is built by a small Caladrius team working with AI agents:

Cally: taxonomy and intent (Giri)

Cally Voice is a new channel into the same assistant, not a new set of things it may do, and for Giri’s area that is the key point. A spoken request needs the same consent as a typed one, plus permission for voice input and for spoken replies. What changes is the shape of an answer: every spoken reply passes a speech filter that turns it into speakable text, with no markup and no identifiers read aloud. The day also fixed a rule that touches every intent: any call that carries a person’s words or audio to a model or speech vendor is made once, never retried, because each attempt is a disclosure. Counts are audited, never content, and voice stays off until a privacy decision switches it on.

Development, infrastructure and go-live (Krishna)

Day 12 was the most go-live-shaped day so far, and it sits squarely in Krishna’s area. Backups are encrypted before they touch the disk and come with a restore drill. The API no longer runs with full database rights. Indexes came from planning every statement, metrics and alerts arrived, and a measuring load test showed one API process is the first limit, so more instances come before a cache. The voice worker runs isolated in its own container next to a self-hosted real-time server, and its QA hosting was merged off by default. Fifty-four PRs merged, and the open work was landed at once, and promoted to QA for review the next morning.

Narrative and personas (Preetha)

Two people were in view on Day 12. The first is someone who would rather speak than type, in their own language; Cally Voice exists for them, and the microphone is asked for only when they tap. The second is someone on a phone with a poor connection who taps twice: idempotency keys make sure a double tap is one consent, one link or one booking, not two. When ABDM is down, they see a “try again later” message instead of a long spinner. In Preetha’s area of wording, the privacy notice gained a paragraph about voice and a new version, so, once voice is switched on, everyone who agreed to the earlier one is asked again.

Product and technology direction (Manish)

I fixed backups first, because everything else is recoverable and lost patient data is not. I held the readiness track to one item at a time, approved before it starts, and built once in the platform layer when every app needs it. I treated “what not to retry” as a privacy decision, not a reliability one. I accepted that audited reads cost like writes, because changing that is a decision about an S1 guarantee. And I chose to land all open work at once, trading a clean review per PR for one tested integration that I reviewed where it actually runs.

Further reading

See all 16 parts