---
title: 'Day 12: Production Readiness, and Cally Finds Its Voice'
series: Building the Caladrius PHR with agents
part: 12
series_total: 15
date: '2026-11-29'
reading_time: 16 min
description: 'The production-readiness review became code: backups with a restore
  drill, an API that no longer runs with full database rights, idempotency keys, circuit
  breakers, metrics and a load test. Alongside it, Cally learned to listen and speak,
  switched off until a privacy decision.'
canonical_url: https://caladriushealth.ai/solutions/phr-build-diary/day-12-production-readiness-and-cally-finds-its-voice/
publisher: Caladrius Health AI Studio
---

# Day 12: Production Readiness, and Cally Finds Its Voice

The production-readiness review became code: backups with a restore drill, an API that no longer runs with full database rights, idempotency keys, circuit breakers, metrics and a load test. Alongside it, Cally learned to listen and speak, switched off until a privacy decision.

*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](https://caladriushealth.ai/platform/brief/#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 database dump is **encrypted as it is written**, so an unencrypted copy never exists on disk, and the backup
  host can write backups it cannot read.
- Each backup carries an encrypted summary of what it holds and a checksum, and older backups are rotated out on a
  schedule.
- A **restore drill**, which is the part that makes backups real. It checks the file, restores it into a **throwaway**
  database (never the live one), proves the restored audit trail is intact, opens a few **real encrypted fields**
  without printing any value, and removes the copy. A drill passes only when all of those pass, and it fails on a wrong
  key or a damaged file.

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](https://caladriushealth.ai/what-is-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:

- The **key** is scoped to the person and the resource, and stored only as a hash. Raw values never reach the store
  or a log. Requests without a signed-in user aren't made idempotent.
- The **first request** claims the key. A successful answer is kept for a limited time; anything else releases the
  key: a failure or a validation error isn't a result to replay.
- **The same key again** gets the stored answer. If the first is still running, the repeat is told to wait and try
  again. The same key with a **different body** is refused.
- **If the store is down, the handler does not run.** A client that asked for exactly-once can't be given it, and
  running anyway is the very duplicate the header exists to prevent.
- **What is stored** is the request hash, the status and the response **encrypted with the field crypto (AES-256-GCM),
  bound to that key**. Never plaintext, never the raw key, never a cookie or a header.
- It runs **after** authentication, permission, rate limit and validation, so a refused request never consumes or
  probes a key.

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](https://caladriushealth.ai/platform/brief/#security) changed that:

- **Route-auth inventory.** A test reads every route in the API source and fails unless each one has an authentication
  guard and a named permission, or sits on an explicit allow-list with a category and a reason (health checks, ABDM
  callbacks with their own gateway authentication, sign-in steps). It checks both ways, so stale allow-list entries
  fail too, and a planted violation proves the scan works.
- **Body-schema inventory**, plus a static-analysis rule: every `POST`, `PUT` or `PATCH` needs a validation schema or a listed
  reason.
- **An error-leak test.** Errors are forced through the real app on each route class, and the body and headers must
  carry no stack, SQL, table or constraint name, file path, vendor text or echoed value.
- **Automated dependency updates**, grouped and spaced out, so upgrades arrive as small, routine pull requests instead of a rush
  when an advisory lands.

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:

- **Throughput levelled off early.** One API process is limited by its own processing, so more concurrency only
  queues. The evidence says to run more API instances before adding a cache.
- **An audited request costs about a quarter of a bare one.** Every read of patient data writes a tamper-evident audit
  row, so in our system reads cost like writes. That's the price of `AGENTS.md` §4.3, and changing it is a decision
  about an S1 guarantee, not a tuning knob.
- **No errors, timeouts or 5xx anywhere.**
- **Memory grew**, and the cause wasn't proven.

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:

- **evict**, for fail-open tiers: when full, drop a small batch of the oldest keys;
- **refuse**, for fail-closed tiers with no shared store: never evict, and answer a *new* key as over the limit while the table is full.

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](https://caladriushealth.ai/platform/brief/#platform). 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:

- **Same consent as the chat.** A voice session needs the person's active, verified Cally consent, plus two
  permissions: voice input and spoken replies.
- **The privacy notice changes.** In a voice build, the notice gets a fifth paragraph saying what happens to your voice,
  and its version moves up, so everyone who agreed to the earlier version is asked again.
- **No audio is kept.** Only the text of a turn is kept. Clips are capped in size and length.
- **The microphone is asked for only on a tap**, never on page load.
- **The real-time server is self-hosted** with signalling on the app's own origin, so the content security policy
  stays `'self'`. The client refuses a session URL that isn't on its own host.
- **The voice worker is isolated.** It runs in its own locked-down container, holds none of the API's database,
  session or ABDM secrets, has no data access and stores nothing.
- **Every spoken reply passes a speech filter** that turns the answer into speakable text: no markup, no identifiers
  read aloud.
- **Counts-only audit**: seconds of audio, characters spoken, never content.
- **Its own rate-limit tier, metrics and breaker**, and **not retried** (section 6).
- **Off unless switched on**, in the API and in the app build.

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

- **Prove a restore, not a backup.** The drill restores, verifies the audit chain and decrypts real fields. Without
  that, a backup is a hope.
- **Least privilege is a test, not a setting.** The database itself refusing the API's account the power to switch
  off the audit protections is the evidence.
- **Decide what not to retry first.** Anything that sends a person's words to a vendor is a disclosure, and each attempt
  counts as one.
- **A measuring load test pays off in unexpected places.** We set out to find throughput and found an unbounded
  counter.
- **Fail-open and fail-closed need different data structures.** Eviction is fine for a global limiter and a
  vulnerability for a brute-force counter.
- **Platform first.** Retries, idempotency and breakers went into `server-core` once, and every app inherits them.

*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:

- **Giri**: CEO; Cally taxonomy and intent framework
- **Krishna**: development, infrastructure and go-live
- **Preetha**: narrative engineer, personas
- **Manish** (me): CTO and CPO, enabling the Caladrius Health AI PHR and the AI Studio framework

### 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

- [Caladrius Health](https://caladriushealth.ai/), the company behind the PHR
- [The Caladrius platform brief](https://caladriushealth.ai/platform/brief/): AI Studio, [Cally](https://caladriushealth.ai/platform/brief/#cally), the [Health Vault](https://caladriushealth.ai/platform/brief/#vault), the [design system](https://caladriushealth.ai/platform/brief/#design-system) and [security by design](https://caladriushealth.ai/platform/brief/#security)
- [Caladrius Pulse](https://caladriushealth.ai/blog/), our blog, including the ABDM series ([What is ABDM?](https://caladriushealth.ai/what-is-abdm/)) and the NHCX series ([What is NHCX?](https://caladriushealth.ai/what-is-nhcx/))
