All work

Case study

Citania

A WhatsApp AI agent that books appointments, with a shared inbox for the humans behind it

Citania answers a clinic's WhatsApp in seconds, from the clinic's real catalogue, prices, hours and policies. It proposes bookings that the patient confirms with a button, and hands the conversation to reception when a person is needed. It runs in production on a single VPS and is in first-client validation.

Role
Sole engineer: product, backend, agent, dashboard, infrastructure
Timeline
May 2026 to present
Status
In production on a single VPS · first-client validation
1
engineer: product, agent, backend, dashboard, infrastructure
72
eval scenarios the agent has to pass
~2,779
automated tests
3
apps in production on one server

Context

The problem

Clinics in Mexico get most patient messages on WhatsApp, often from paid ads, and answer them by hand. Messages arrive at night, in bursts, and in several short pieces. A late answer is often a lost patient.

An AI agent can answer in seconds, but a clinic cannot accept a wrong price, a double-booked chair or a patient left waiting after being told a person would reply. The hard part was never generating text. It was making every side effect safe: each message answered once, each booking authorised by the patient and checked against the real agenda, each handoff followed up.

I built it alone. Each clinic is a tenant with its own WhatsApp number, catalogue and staff. Reception works in a shared inbox with an agenda. The product started in May 2026 as a booking bot for salons and was repositioned to clinics in November. The first pilot tenant is not a dental clinic, and AI replies to its real customers wait on the team's explicit approval.

System design

How it fits together

Three apps run in production. A Hono API receives WhatsApp webhooks, runs the agent, owns bookings, handoff, reminders and credit settlement, and hosts the Inngest functions. A Next.js dashboard is the inbox, agenda and settings for clinic staff, plus an admin area for me. A marketing site with a scripted demo runs on Vercel.

Everything stateful lives on one VPS, bound to loopback and published through a reverse proxy: PostgreSQL as the system of record, a self-hosted Inngest server for durable work and crons, private agent transcripts, private media and observability. Kapso, an official WhatsApp BSP, carries messages. Vercel AI Gateway is the only path to a model.

System design

Citania system architecturePatients write on WhatsApp. Meta delivers to Kapso, which calls the API on a single VPS. The API runs the Pi agent, which reaches models through Vercel AI Gateway. Inngest, PostgreSQL, the staff dashboard and observability run on the same VPS. Backups are pulled off the server; the marketing site runs on Vercel.PeopleThird partiesSingle VPS · loopback services behind a reverse proxyOff the VPSwebhook · HMACHTTPSPrismaencrypted pullPatientWhatsAppClinic staffBrowserWhatsAppMeta Cloud APIKapsoOfficial BSPVercel AI GatewayCost-sorted routingModel providersGLM 5.3 Flash defaultInngestSelf-hosted · cronsAPIHono · NodePi agentTyped tools onlyPi sessionsPrivate transcriptsDashboardNext.js · tRPC · SSEPostgreSQL 18System of recordObservabilityOpenObserve · OTelMarketing siteVercelBackupsEncrypted, off-site
The API (ink) is the only process that talks to WhatsApp and to the model. The agent (accent) runs inside it with typed tools and no filesystem or shell. Staff never call the API directly: the dashboard reads PostgreSQL and gets live updates through LISTEN/NOTIFY.
ComponentResponsibilityTechnologyRuns on
APIWebhooks, the durable conversation pipeline, the agent, reservations, handoff, reminders, notifications, credit settlement, Inngest function hostHono 4, Node, Zod, PrismaVPS, PM2
DashboardInbox, agenda, services, contacts, templates, settings and credits for staff; admin area with traces and analytics; realtime over SSENext.js 16, tRPC 11, Better AuthVPS, PM2
InngestDurable queue, retries and crons: turn recovery, handoff follow-up, reminders, template reconciliation, credit settlementSelf-hosted server, SQLite storeVPS, PM2
PostgreSQLSystem of record, separate production and staging databases, advisory locks, LISTEN/NOTIFY for the inboxPostgreSQL 18, Prisma migrationsVPS
Agent sessions and mediaOne private transcript per conversation and prompt version; inbound media served only through authenticated, tenant-scoped routesFiles on diskVPS
ObservabilityAllowlisted API logs, dashboard errors, host metrics; agent traces stay in PostgreSQLOpenObserve, OpenTelemetry CollectorVPS
BackupsEncrypted database and runtime backups, pulled off the server and verifiedScriptsOff-site
Marketing siteProduct site and a scripted dental demo with no backendNext.js 16Vercel

Stack

Channel
WhatsApp Cloud API through Kapso, Meta Graph for templates, Telegram Bot API for alerts
Backend
Node, Hono 4, TypeScript (strict), Zod 4, TypeBox, pino
Agent
Pi harness, Vercel AI Gateway, GLM 5.3 Flash by default
Async
Self-hosted Inngest
Data
PostgreSQL 18, Prisma 7, advisory locks, LISTEN/NOTIFY
Frontend
Next.js 16, React 19, tRPC 11, Better Auth, shadcn, TanStack
Infra
VPS with PM2 and Caddy, Vercel for the marketing site, OpenObserve and OpenTelemetry
Tooling
pnpm workspaces, Turborepo, Vitest, ESLint, Playwright

Flows

The paths that matter

01 Incoming message to reply: the durable turn

WhatsApp delivers at least once, patients send three messages in two seconds, and the process can die mid-send. The turn has to answer each message once, in order, and never send a reply twice.

Flow 1 · The durable turn

Incoming WhatsApp message to AI replyKapso posts the message; the API stores it and only then answers 200. An Inngest event runs the turn with one turn per conversation, the agent writes the reply, and the reply is stored in an outbox before it is sent.KapsoWhatsApp BSPAPIHonoPostgreSQLInngestself-hostedPi agentin the API1 POST webhookHMAC checked on the raw body2 Insert message, QUEUEDunique on the provider message id200Async, after the 2003 Event, id = message id4 Run turnconcurrency 1 per conversation5 Claim next batchlease plus fencing token6 Run the agenttyped tools, budgetsReply text7 Outbox row, PENDINGstored before it is sent8 Send reply9 SENT, finish batchcompare-and-swap on the lease
The 200 goes back only after the message is stored. The reply is stored in an outbox before it is sent, so a crash leaves a row to reconcile instead of a lost or duplicated message.
  1. Verify and normalise the webhook

    The API checks the HMAC signature on the raw body, validates the payload with Zod and keeps the signed envelope for seven days for diagnosis. The tenant is resolved from the exact destination number. Unknown numbers are dropped: there is no default tenant.

  2. Persist before acknowledging

    One transaction stores the message as QUEUED, deduplicated by a unique constraint on the provider message id, and advances the conversation sequence. Only then does the webhook return 200.

  3. Enqueue a deduplicated event

    The Inngest event id is the provider message id, so a redelivered webhook cannot start a second turn. When Inngest is off, an inline fallback runs the turn.

  4. One turn per conversation

    The turn function runs with concurrency 1 keyed on the conversation, with retries.

  5. Claim a batch under a lease

    The turn claims every queued message of the conversation as one ordered batch, with a 10-minute lease and a fencing token. Several quick messages become one answer.

  6. Run the agent

    After a credit check and a fail-closed check of the business, conversation and contact, the agent resumes its transcript and calls the model through the gateway. It sees only typed domain tools, never tenant or actor ids, and works within generation, tool and time budgets.

  7. Write the reply to an outbox

    The reply is stored as PENDING before anything is sent, then moves through SENDING to SENT or FAILED.

  8. Send through Kapso

    If the provider may have accepted the message before a crash, the row stays SENDING, the conversation moves to a human and an operator event is raised. An uncertain send is never retried blindly.

  9. Finish the batch

    A compare-and-swap on the lease closes the batch. Interrupted leases are reset at boot and by a 5-minute sweep. A generation error aborts into a durable retry instead of sending an empty or generic reply.

02 Booking with consent

A model that says "booked" has not booked anything. Bookings had to be proposed by the agent, authorised by the patient and written by the application against the live agenda.

Flow 2 · Booking with consent

Booking with consentThe agent prepares a booking, the application stores a pending action and sends a summary with Sí and No buttons. A tap is resolved without the model; the booking is written in one transaction under a per-business lock, and reception reviews it.PatientWhatsAppAPIHonoPi agentPostgreSQLReceptionDashboardAsks for a timeTurn1 prepare bookinga tool call, validated like any use case1 Pending action, 1 h expirybound to actor, tenant and turn2 Summary + Sí / No buttonswritten by the applicationNo model on this path3 Taps Sí4 Lock business, revalidateone transaction, advisory lock4 Appointment PENDING_REVIEWholds the slot, plus outbox row5 Shows in the agenda5 Confirm, adjust or reject5 Template messagedurable delivery outbox
The model only prepares. The tap on Sí goes straight to the application, and the write happens in one transaction under a per-business advisory lock.
  1. The agent prepares, the application records

    When the agent has complete facts it calls a prepare tool. A state machine stores a pending action bound to the actor, tenant, turn and preconditions, with a one-hour expiry.

  2. The application writes the summary

    The turn ends with a summary written by the application, not the model, sent as an interactive message with Sí and No buttons. It falls back to text when it exceeds 1,024 characters or when the button send definitely failed.

  3. A tap skips the model

    A button tap applies only the exact current pending action. Typed answers go through a tool that classifies them as accept, reject, change or ambiguous. A change supersedes the old proposal first, so stale data cannot be confirmed.

  4. One transaction under a lock

    The apply step takes a per-business PostgreSQL advisory lock, revalidates hours, closures, time off, capacity and overlaps, then writes an appointment pending review, which holds the slot, and an outbox row. A successful tool result is the only proof of a write.

  5. Reception has the last word

    Staff confirm, adjust or reject in the agenda, and a durable template delivery tells the patient.

03 Handoff to a human, without silence

A patient told "a person will reply" at 9 pm and then left in silence is worse off than one who never wrote. The handoff had to set an honest expectation and keep following up until someone answers.

Flow 3 · Handoff without silence

Handoff to a humanAn escalation moves the conversation to a human in one transaction and tells the patient what to expect. Reception is alerted. A sweep every five minutes re-alerts once at 15 business-hours minutes and notifies the owner at 60.PatientWhatsAppAPIHonoPostgreSQLFollow-up sweepInngest cronReceptionOwner1 Escalateagent signal or clinic safety net2 Mode HUMAN, event, noteone transaction3 Acknowledgementan expectation, no minutes4 Alerttemplate, Telegram, emailEvery 5 minutes, counted in business-hours minutes5 Find pending episodesthe shared definition of pending5 Re-alert at 15 minonce per episode5 Notify owner at 60 min6 Reply from the panelidempotent, rechecks the 24h window6 Reply, sent oncenever auto-retried when uncertain
Every step runs once per episode. The sweep counts business-hours minutes, and the API, the SQL and the panel share one definition of a pending episode.
  1. Escalate

    The agent only signals that a human is needed, with an urgent flag. For clinics, a deterministic safety net also catches urgencies and explicit requests for a person.

  2. Move to a human in one transaction

    The conversation records an escalation event, switches to human mode with an attention timestamp, cancels pending agent work and stores a private handoff note with a summary and the next action.

  3. Tell the patient the truth

    An outbox message sets an expectation without promising minutes. Outside business hours it says when the clinic opens.

  4. Alert reception

    After the commit, reception gets an approved WhatsApp template, with Telegram and email as fallbacks.

  5. Follow up in business-hours minutes

    A sweep every five minutes sends one re-alert at 15 minutes. At 60 it notifies the owner, and the agent resumes and says so, only inside WhatsApp's 24-hour window. Technical failures, ambiguous deliveries and exhausted credits never go back to the agent.

  6. Reply from the panel

    A staff reply reserves an outbound message with the actor and rechecks the assignee, the mode, the 24-hour window and the bound number. It is idempotent by client request id and never auto-retries an uncertain send.

Decisions

What I chose, and what it cost

  1. 01

    Chose the application as the authority over letting the model decide what happens

    Why
    Every agent tool is an application use case with its own validation. Mutations need a lookup first, then a proposal in a state machine, then the patient's consent. Which tools the model can see is not treated as an authorisation boundary.
    Cost
    More code per feature, and new agent capabilities take longer to ship.
  2. 02

    Chose exact catalogue lookups over RAG and embeddings

    Why
    Prices have to be exact. Search is Prisma filters plus deterministic normalisation of accents, plurals and synonyms, and a get-service tool returns the authoritative facts.
    Cost
    Keywords and synonyms have to be maintained per tenant.
  3. 03

    Chose deterministic Sí / No buttons for consent over the model interpreting "sí"

    Why
    Consent is the moment a booking becomes real. A tap is resolved by the application without calling the model, so it is exact and costs no credits.
    Cost
    Two paths to maintain: buttons, and a text fallback for long summaries or failed button sends.
  4. 04

    Chose credits charged from real gateway cost over an estimate from list prices

    Why
    The list-price estimate overcharged about 4 to 6 times. Each model call's generation id is stored, and a sweep every minute reads the real cost from the gateway and debits an append-only ledger once per run.
    Cost
    Settlement is delayed and needs a fallback: after 30 minutes it uses a flagged estimate. Unknown cost is never treated as zero, and a script reconciles the ledger against the invoice.
  5. 05

    Chose self-hosted Inngest with one turn per conversation over fire-and-forget turns inside the webhook handler

    Why
    The first handler started the turn and returned 200 at once, so a crash lost work. Now it is persist, then 200, then a durable event with concurrency 1 per conversation and retries.
    Cost
    One more stateful service, with its own store to back up.
  6. 06

    Chose SSE over PostgreSQL LISTEN/NOTIFY, inside the dashboard over a separate websocket service or Redis

    Why
    Writes trigger a NOTIFY. One listener runs per process, the tenant comes from the session, the session is rechecked every 60 seconds and reconnects reconcile against the authoritative rows. No new infrastructure.
    Cost
    Realtime lives inside the dashboard process. It sits behind a small transport interface so it can move out later.
  7. 07

    Chose PostgreSQL on the VPS over staying on Neon

    Why
    I rehearsed the cutover on staging with a benchmark, copied with writers paused, tested a restore off the server, and kept Neon as the recovery source.
    Cost
    Backups became my job: encrypted off-site pulls and restore drills.
  8. 08

    Chose Kapso, an official WhatsApp BSP over Meta's API directly

    Why
    Messaging started on an unofficial client and moved to Kapso. I built a per-tenant direct-Meta path and a separate agents service, then froze both to focus on getting clients.
    Cost
    A dependency on Kapso, and finished work parked on a branch.
  9. 09

    Chose one VPS with PM2 and a reverse proxy over Docker Compose or a managed platform

    Why
    I built the container setup first and kept it as a documented alternative. One VPS is cheap and simple to operate for one engineer at this stage.
    Cost
    A single point of failure, so there is no SLA in this phase.
  10. 10

    Chose a modular monolith over services per domain

    Why
    The API's domains are modules with an explicit dependency graph. Shared packages exist only for code with more than one consumer.
    Cost
    Webhooks, turns, crons and reminders share one process, one deploy and one failure domain.

What broke

Incidents and what changed

An eval suite that passed 100% and measured nothing

What happened
The first baseline of 14 scenarios passed every time, including against an agent redesign. It could not tell a better agent from a worse one.
What changed
I replaced it with 29 harder scenarios and ran them three times: 27, 25 and 27 of 29. Two scenarios failed all three runs, a booking mixed with a payment-plan question and the formal usted register, which gave me real work to do. Silent turns now fail the eval.

Handoffs that ended in silence

What happened
A patient handed to a person at 9 pm got no reply and no explanation.
What changed
Three rounds of revision after independent reviews produced the current flow: an honest acknowledgement, alerts with fallbacks, follow-up counted in business-hours minutes, and one definition of an episode and of pending, shared by the TypeScript code and the SQL. It replaced an older rule that a conversation never returned to the agent by time.

Empty replies

What happened
A generation error in the agent produced an empty reply, which ended up as a generic "please wait" message to the patient.
What changed
A generation error now aborts the turn into a durable retry. Nothing is sent until there is a real answer.

Overcharging for AI usage

What happened
Credits estimated from list prices came out about 4 to 6 times the real cost.
What changed
Settlement from the gateway's real cost per generation, an append-only ledger and a reconciliation script against the invoice.

Double-booking and cross-tenant risk

What happened
Concurrent bookings could race for the same slot, and a message to an unknown number could fall back to a default tenant.
What changed
Per-business advisory locks with full revalidation inside the booking transaction. Unknown destination numbers now fail closed.

WhatsApp payloads that did not match the schema

What happened
Kapso started sending null nested objects that broke parsing, and an ad referral and its message arrived as two separate deliveries.
What changed
The parser accepts nulls and logs schema mismatches. The split delivery is joined through a correlated event with a bounded five-second durable wait.

The VPS ran out of disk and memory

What happened
Observability caches and data files exhausted the shared server.
What changed
I bounded the logs, moved temporary files to the faster disk and repaired orphaned files from a verified backup.

Quality

Tests, operations, security, cost

There is no hosted CI yet. Type checks, lint with zero warnings and tests run locally before every release to staging, and staging comes before production.

Tests
About 2,779 test cases in 332 files on Vitest, including PostgreSQL integration suites for reservations, turn processing and transport recovery.
Evals
72 agent scenarios. The runner supports live runs, repeats, pinned clocks, graders and A/B runs between models.
Backups
Encrypted database and runtime backups pulled off the server and verified by read-back and hashes. A backup is required before any production schema change.
Security
HMAC on every webhook. The tenant comes from the session, never from request input. Separate auth for staff and admin. Encrypted per-connection tokens. The agent has no filesystem or shell tools, prompt-template expansion is off, and customer text is treated as data. Services listen on loopback only.
Observability
Allowlisted logs and host metrics in OpenObserve through OpenTelemetry. Every agent run, tool call and event is traced in PostgreSQL and visible in the admin area.
Cost
Cost-sorted gateway routing, an inexpensive default model, a credit ledger with a grace margin that hands off politely when it runs out, and a button path that skips the model. First-reply time is tracked as median, p90 and share under 60 seconds.

Method

How I built it

I build with AI coding agents. I write the rules they work under in an AGENTS.md file, scope each task, and review what comes back before it merges. September alone has 258 of the 433 commits.

Decisions go into a dated log with the alternative and the trade-off, about 150 entries, including the ones I later reversed. I also had the API, the dashboard and the agent audited in writing, with each finding marked as verified or assumed.

Hindsight

What I'd do differently

  • I would set up CI on day one. Today every gate runs on my machine, which works for one engineer and fails silently the day I skip a step.
  • I would plan for a second production host early. One VPS keeps costs and operations small, but it is the only path to production, and external uptime checks and failure alerts are still open.
  • I would keep the scope narrow until the product had traction. I built a direct-Meta integration, a web widget and a CMS that are now frozen, and the move from salons to clinics removed work I had already shipped.