Chapter 0410 min read
Technical architecture
A pragmatic, mostly managed stack: TypeScript services and a thin agent runtime, Temporal for durability, Postgres as the system of record, and a Supply Gateway that hides every supplier behind typed tools. Optimized for correctness first, cost second and latency third.
Key decisions in this chapter
TypeScript end to end for product services and agents; Python only for ML, pricing models and the itinerary solver.
Temporal Cloud runs every booking saga, monitoring schedule and approval timer.
Postgres with pgvector and PostGIS is the system of record. No separate vector or graph database until scale demands one.
Two frontier providers behind one gateway with automatic failover, while small models handle most calls.
Duffel for flights at MVP; getmyhotels supply plus Expedia Rapid and Hotelbeds for hotels. A GDS joins in Phase 2.
4.1
High-level architecture
Eight layers, each with one job. The agent layer is only one of them: most of what makes Zilia reliable is ordinary, well-tested software around it.
L1
Channels
- Web (Next.js)
- WhatsApp Cloud API
- SMS and email
- iOS and Android (Phase 2)
- iMessage (Phase 2)
- Telegram (Phase 2)
L2
Edge and identity
- Cloudflare WAF and CDN
- API gateway
- Clerk plus phone identity
- Rate limits and bot protection
L3
Conversation and realtime
- Conversation Service
- Channel adapters
- Streaming over SSE
- Notification router
L4
Agent layer
- Orchestrator runtime
- Specialist agent workers
- Model Gateway (LiteLLM)
- Prompt registry
- Eval harness
L5
Durable workflows
- Temporal Cloud
- Booking sagas
- Monitoring schedules
- Approval timers
- Re-shop jobs
L6 · Deterministic code
Domain services
- Trip Service (event store)
- Transaction Service
- Payments
- Pricing Service
- Mandate and Policy Engine
- Profile and Vault
L7
Supply Gateway
- Flights
- Hotels
- Experiences
- Ground and rail
- Maps and places
- Weather
- Flight status
- Entry rules
L8
Data and events
- Postgres on Aurora, with pgvector and PostGIS
- Redis
- ClickHouse
- S3
- Outbox to SNS and SQS, Redpanda in Phase 2
Across every layer
Observability and safety
- OpenTelemetry
- Langfuse
- Grafana Cloud
- Sentry
- Audit log
- Kill switches
- Spend limits
A request enters through a channel adapter, becomes a canonical message in the Conversation Service, and reaches the Orchestrator. Agents run as stateless workers that read and write Trip State through domain services. Anything that takes longer than one request, waits for a person or moves money runs as a Temporal workflow. Every supplier sits behind the Supply Gateway, and every event is written once to Postgres through an outbox, then fanned out to monitoring, analytics and notifications.
4.2
Recommended stack
Boring where it can be, specialized where it must be. Every choice below has a named alternative, so the team knows what we would switch to and why we have not.
| Layer | Our choice | Why | Considered instead |
|---|---|---|---|
| Frontier models | Anthropic Claude and OpenAI GPT at the current frontier tier, each reachable directly and through AWS Bedrock or Azure | The most reliable tool use and long-context reasoning. Two providers on two clouds remove single-vendor outages and rate-limit ceilings. | Google Gemini as a third route |
| Small models | The small, fast tiers of the same families | Extraction, routing, classification and summaries at a fraction of the cost. | Open-weight models on vLLM in Phase 2 |
| Embeddings | One hosted embedding model, pinned per index version | Re-embedding is expensive, and pinning keeps vectors comparable. | Self-hosted open-weight embeddings |
| Model gateway | LiteLLM, self-hosted | One API with routing, fallbacks, budgets, caching and cost per feature. | Portkey, managed |
| Agent runtime | A thin in-house runtime on provider SDKs, typed with Zod | Full control of prompts, tools, budgets and traces, with no framework lock-in. | LangGraph for prototypes |
| Durable workflows | Temporal Cloud | Exactly-once sagas, millions of timers for monitoring, and waits for human approval that survive deploys. | AWS Step Functions, Restate |
| Layer | Our choice | Why | Considered instead |
|---|---|---|---|
| Languages | TypeScript for services and agents; Python for ML, pricing models and the solver | One language across web, API and agents, with shared schemas end to end. | Python everywhere |
| API | Typed REST with OpenAPI generated from Zod, plus server-sent events | Simple for mobile and partners, and it streams tokens and cards as they arrive. | GraphQL |
| Web | Next.js and React, with Tailwind | Server rendering for shareable itinerary pages, which feed the SEO growth loop. | Remix |
| Mobile | React Native with Expo, in Phase 2 | Shares types and logic with the web; native modules cover Live Activities. | Native Swift and Kotlin |
| System of record | PostgreSQL on Amazon Aurora, with pgvector and PostGIS | Transactions, events, profiles, embeddings and geography in one place, with fewer moving parts. | Neon or Supabase in the first weeks |
| Vector search | pgvector with HNSW indexes | Memory queries are per traveler and filtered, and tens of millions of vectors fit comfortably. | Turbopuffer or Qdrant past 100M vectors |
| Cache | Redis on ElastiCache | Quote cache, working memory, rate limits and idempotency keys. | DragonflyDB |
| Analytics and price history | ClickHouse Cloud | Billions of price observations with fast aggregates for pricing intelligence. | BigQuery |
| Events | A transactional outbox to SNS and SQS at MVP; Redpanda in Phase 2 | Start simple, then move to a log once volume and replay needs grow. | Confluent Cloud, NATS JetStream |
| Search | Typesense | Fast, typo-tolerant search for hotels, places and destinations. | OpenSearch |
| Layer | Our choice | Why | Considered instead |
|---|---|---|---|
| Payments | Stripe with Radar, plus Stripe Issuing virtual cards to pay hotels | Merchant-of-record flows, fraud tooling, and one virtual card per booking for clean reconciliation. | Adyen, worth revisiting at scale |
| Sensitive data | Basis Theory or VGS | Keeps passports, birth dates and card data out of every system a model can reach. | Skyflow |
| Identity | Clerk, plus phone verification | Passkeys, organizations for groups and B2B, and fast to ship. | Auth0 |
| Messaging | WhatsApp Cloud API directly; Twilio for SMS and voice; Postmark for email | A direct WhatsApp integration keeps per-message costs down. | Twilio for WhatsApp too |
| Infrastructure | AWS: ECS on Fargate, Terraform, GitHub Actions | Managed, boring and scalable, with Bedrock in the same cloud. | Kubernetes once there is a platform team |
| Observability | OpenTelemetry, Grafana Cloud, Sentry and Langfuse | One trace across services and agent steps, with prompt versions and eval scores side by side. | Datadog, LangSmith |
| Product analytics | PostHog | Funnels, session replay, feature flags and experiments in one tool. | Statsig |
4.3
Booking and inventory integration
Hotels deep, flights broad, everything else light. Supply is where getmyhotels gives Zilia a head start, so the integration strategy builds on it rather than around it.
| Category | MVP | Later | Commercial model | Notes |
|---|---|---|---|---|
| Hotels | getmyhotels contracts and bedbanks, Expedia Rapid API, Hotelbeds | WebBeds and more direct contracts in top cities (Phase 2); direct connectivity through channel managers such as SiteMinder or DerbySoft (Phase 3) | Merchant: net rate plus markup. Agency for coverage. | De-duplicate on getmyhotels' mapping plus a mapping vendor. Package-only rates appear only inside bundles. |
| Flights | Duffel: NDC and aggregated content, ticketing, changes, cancellations and hold orders | A GDS such as Amadeus or Sabre for breadth, private fares and automated exchanges (Phase 2) | Service fee plus incentives | No IATA accreditation needed at MVP. Airline-initiated changes arrive as webhooks. |
| Experiences | Viator and GetYourGuide, affiliate | Merchant APIs and Tiqets (Phase 2) | Commission | Show only bookable, dated time slots. |
| Ground and rail | Mozio for transfers | Rail through Trainline Partner Solutions or Rail Europe (Phase 2) | Commission | Offered when arrival time and luggage make a transfer worth it. |
| Flight status | FlightAware AeroAPI alerts or Cirium | Both, for redundancy | Usage-based | Push alerts, never polling loops. |
| Weather | Tomorrow.io | Unchanged | Usage-based | Pulled 7, 3 and 1 days before outdoor plans. |
| Maps and places | Google Places and Routes APIs; Mapbox for rendering | Unchanged | Usage-based | Respect caching limits in the terms: store place ids and refresh details. |
| Entry rules | Sherpa | IATA Timatic for airline-grade checks | Usage-based | Checked before every booking and again before travel. |
| Insurance and eSIM | Not in the MVP | Cover Genius XCover and Airalo (Phase 2) | Revenue share | Offered only when they fit the trip. |
One model of the world
Canonical objects in the Supply Gateway
Offer, Quote, Booking, CancellationPolicy, Fee, Traveler, Segment and RoomType. Every quote carries a quote id, supplier, expiry, all-in price and a hash of its policy, so two suppliers selling the same room on the same terms are recognized as one option.
One charge for the traveler
The merchant-of-record setup
Zilia collects the whole trip with Stripe, pays each hotel with a single-use virtual card, and settles flights from its Duffel balance. The traveler sees one charge, and every booking reconciles to one card or one order.
4.4
Real-time monitoring and events
The Guardian is an event-driven pipeline, not an agent polling APIs. Signals flow in, get matched to trips in milliseconds, and only real incidents wake a model.
- 01
Ingest
Supplier webhooks, flight status alerts, weather alerts, re-shop results, payment events and traveler messages. - 02
Normalize
Every input becomes a TripEvent with a type, entities, a source and the time it was observed. - 03
Match
Active trips are indexed by flight number and date, hotel and date, and city and date range, so affected trips are found in milliseconds. - 04
Classify
Deterministic rules set severity. A small model reads only unstructured inputs such as advisories. - 05
Decide
A Temporal Recovery workflow starts. The Recovery Agent builds options and the Mandate Engine evaluates them. - 06
Act
The Transaction Service executes under a Mandate token, or an approval request is created with an expiry. - 07
Notify
The notification router picks channels by severity, quiet hours and channel rules.
| Signal | Source | Cadence | Acts when |
|---|---|---|---|
| Flight status | FlightAware or Cirium alerts | Push alerts from 72 hours before departure until arrival | A delay of 60 minutes that threatens a connection, or any delay of 3 hours or more |
| Schedule changes | Aggregator webhooks | Immediately | Any change of 30 minutes or more, or a broken connection |
| Hotel prices | Supply Gateway re-shop of refundable bookings | Daily until 7 days before the cancellation deadline, then every 6 hours | Same room, same or better terms, at least $25 and 3% cheaper |
| Weather | Tomorrow.io | 7, 3 and 1 days before each outdoor plan, then hourly on the day | Rain probability of 70% or more during an outdoor slot |
| Advisories and strikes | Official feeds plus curated sources | Daily, and hourly during active trips | Human review before any traveler-facing claim |
4.5
Scale, reliability and cost
Agentic workloads fail in new ways and cost money in new ways. These are the guardrails that keep Zilia up, correct and profitable as it grows.
- AI cost per planned trip
- < $0.40AI cost per planned trip
- of net revenue per booked trip spent on AI
- < 2%of net revenue per booked trip spent on AI
- to the first streamed token
- < 1.5 sto the first streamed token
- p95 for a full orchestrator turn
- < 8 sp95 for a full orchestrator turn
Route by task
About 80% of model calls run on small models. Frontier models are reserved for planning, recovery and hard trade-offs.
Cache the stable parts
System prompts and tool schemas come first in every request, so most orchestrator turns hit the prompt cache.
Compact tool results
Models see the top normalized options, never raw supplier data. That alone cuts input tokens several times over.
Code before tokens
Pricing, filtering, schedule checks and policy checks are code. Models explain; they do not compute.
Batch what can wait
Memory extraction, ranking features and evals run through batch APIs at lower prices.
Budget every trip
Each trip has a token and supplier-search budget. Overruns raise alerts long before they reach the bill.
Reliability
- Idempotency keys on every supplier write, and nightly reconciliation of supplier bookings against our ledger.
- Sagas with compensations: no half-booked trip without a visible incident.
- Circuit breakers and fallbacks per supplier and per model provider.
- Kill switches per agent and per Mandate type, plus a global read-only mode for incidents.
- Replayable turns: every decision can be reproduced from Trip State, the prompt version and the recorded tool results.
Security and scale
- Stateless agent workers autoscale on queue depth; Temporal shards by trip; Postgres partitions by trip and time.
- PCI scope kept minimal with Stripe Elements and vault tokens; SOC 2 Type II by month 12.
- Least-privilege tools: each agent gets only the tools its role needs, scoped to the trip in hand.
- Zero data retention agreements with model providers wherever they are offered.
- Prompt-injection defenses for supplier text, reviews and emails, covered in chapter 5.