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
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
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.
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.
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.
One turn per conversation
The turn function runs with concurrency 1 keyed on the conversation, with retries.
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.
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.
Write the reply to an outbox
The reply is stored as PENDING before anything is sent, then moves through SENDING to SENT or FAILED.
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.
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
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.
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.
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.
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.
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
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.
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.
Tell the patient the truth
An outbox message sets an expectation without promising minutes. Outside business hours it says when the clinic opens.
Alert reception
After the commit, reception gets an approved WhatsApp template, with Telegram and email as fallbacks.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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.