Skip to content

4.1/High-level architecture

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

  1. TypeScript end to end for product services and agents; Python only for ML, pricing models and the itinerary solver.

  2. Temporal Cloud runs every booking saga, monitoring schedule and approval timer.

  3. Postgres with pgvector and PostGIS is the system of record. No separate vector or graph database until scale demands one.

  4. Two frontier providers behind one gateway with automatic failover, while small models handle most calls.

  5. 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.

  1. L1

    Channels

    • Web (Next.js)
    • WhatsApp Cloud API
    • SMS and email
    • iOS and Android (Phase 2)
    • iMessage (Phase 2)
    • Telegram (Phase 2)
  2. L2

    Edge and identity

    • Cloudflare WAF and CDN
    • API gateway
    • Clerk plus phone identity
    • Rate limits and bot protection
  3. L3

    Conversation and realtime

    • Conversation Service
    • Channel adapters
    • Streaming over SSE
    • Notification router
  4. L4

    Agent layer

    • Orchestrator runtime
    • Specialist agent workers
    • Model Gateway (LiteLLM)
    • Prompt registry
    • Eval harness
  5. L5

    Durable workflows

    • Temporal Cloud
    • Booking sagas
    • Monitoring schedules
    • Approval timers
    • Re-shop jobs
  6. L6 · Deterministic code

    Domain services

    • Trip Service (event store)
    • Transaction Service
    • Payments
    • Pricing Service
    • Mandate and Policy Engine
    • Profile and Vault
  7. L7

    Supply Gateway

    • Flights
    • Hotels
    • Experiences
    • Ground and rail
    • Maps and places
    • Weather
    • Flight status
    • Entry rules
  8. 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
Figure 4.1 · System layers, top to bottom from the traveler to the data. The dashed band is deterministic code that no model can bypass.

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.

LayerOur choiceWhyConsidered instead
Frontier modelsAnthropic Claude and OpenAI GPT at the current frontier tier, each reachable directly and through AWS Bedrock or AzureThe 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 modelsThe small, fast tiers of the same familiesExtraction, routing, classification and summaries at a fraction of the cost.Open-weight models on vLLM in Phase 2
EmbeddingsOne hosted embedding model, pinned per index versionRe-embedding is expensive, and pinning keeps vectors comparable.Self-hosted open-weight embeddings
Model gatewayLiteLLM, self-hostedOne API with routing, fallbacks, budgets, caching and cost per feature.Portkey, managed
Agent runtimeA thin in-house runtime on provider SDKs, typed with ZodFull control of prompts, tools, budgets and traces, with no framework lock-in.LangGraph for prototypes
Durable workflowsTemporal CloudExactly-once sagas, millions of timers for monitoring, and waits for human approval that survive deploys.AWS Step Functions, Restate
Table 4.1 · AI and agent layer. Model families are named, not versions: the gateway lets us move to new versions as evals allow.
LayerOur choiceWhyConsidered instead
LanguagesTypeScript for services and agents; Python for ML, pricing models and the solverOne language across web, API and agents, with shared schemas end to end.Python everywhere
APITyped REST with OpenAPI generated from Zod, plus server-sent eventsSimple for mobile and partners, and it streams tokens and cards as they arrive.GraphQL
WebNext.js and React, with TailwindServer rendering for shareable itinerary pages, which feed the SEO growth loop.Remix
MobileReact Native with Expo, in Phase 2Shares types and logic with the web; native modules cover Live Activities.Native Swift and Kotlin
System of recordPostgreSQL on Amazon Aurora, with pgvector and PostGISTransactions, events, profiles, embeddings and geography in one place, with fewer moving parts.Neon or Supabase in the first weeks
Vector searchpgvector with HNSW indexesMemory queries are per traveler and filtered, and tens of millions of vectors fit comfortably.Turbopuffer or Qdrant past 100M vectors
CacheRedis on ElastiCacheQuote cache, working memory, rate limits and idempotency keys.DragonflyDB
Analytics and price historyClickHouse CloudBillions of price observations with fast aggregates for pricing intelligence.BigQuery
EventsA transactional outbox to SNS and SQS at MVP; Redpanda in Phase 2Start simple, then move to a log once volume and replay needs grow.Confluent Cloud, NATS JetStream
SearchTypesenseFast, typo-tolerant search for hotels, places and destinations.OpenSearch
Table 4.2 · Application and data.
LayerOur choiceWhyConsidered instead
PaymentsStripe with Radar, plus Stripe Issuing virtual cards to pay hotelsMerchant-of-record flows, fraud tooling, and one virtual card per booking for clean reconciliation.Adyen, worth revisiting at scale
Sensitive dataBasis Theory or VGSKeeps passports, birth dates and card data out of every system a model can reach.Skyflow
IdentityClerk, plus phone verificationPasskeys, organizations for groups and B2B, and fast to ship.Auth0
MessagingWhatsApp Cloud API directly; Twilio for SMS and voice; Postmark for emailA direct WhatsApp integration keeps per-message costs down.Twilio for WhatsApp too
InfrastructureAWS: ECS on Fargate, Terraform, GitHub ActionsManaged, boring and scalable, with Bedrock in the same cloud.Kubernetes once there is a platform team
ObservabilityOpenTelemetry, Grafana Cloud, Sentry and LangfuseOne trace across services and agent steps, with prompt versions and eval scores side by side.Datadog, LangSmith
Product analyticsPostHogFunnels, session replay, feature flags and experiments in one tool.Statsig
Table 4.3 · Commerce, messaging and operations.

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.

CategoryMVPLaterCommercial modelNotes
Hotelsgetmyhotels contracts and bedbanks, Expedia Rapid API, HotelbedsWebBeds 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.
FlightsDuffel: NDC and aggregated content, ticketing, changes, cancellations and hold ordersA GDS such as Amadeus or Sabre for breadth, private fares and automated exchanges (Phase 2)Service fee plus incentivesNo IATA accreditation needed at MVP. Airline-initiated changes arrive as webhooks.
ExperiencesViator and GetYourGuide, affiliateMerchant APIs and Tiqets (Phase 2)CommissionShow only bookable, dated time slots.
Ground and railMozio for transfersRail through Trainline Partner Solutions or Rail Europe (Phase 2)CommissionOffered when arrival time and luggage make a transfer worth it.
Flight statusFlightAware AeroAPI alerts or CiriumBoth, for redundancyUsage-basedPush alerts, never polling loops.
WeatherTomorrow.ioUnchangedUsage-basedPulled 7, 3 and 1 days before outdoor plans.
Maps and placesGoogle Places and Routes APIs; Mapbox for renderingUnchangedUsage-basedRespect caching limits in the terms: store place ids and refresh details.
Entry rulesSherpaIATA Timatic for airline-grade checksUsage-basedChecked before every booking and again before travel.
Insurance and eSIMNot in the MVPCover Genius XCover and Airalo (Phase 2)Revenue shareOffered only when they fit the trip.
Table 4.4 · Supply integrations by phase.

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.

  1. 01

    Ingest

    Supplier webhooks, flight status alerts, weather alerts, re-shop results, payment events and traveler messages.
  2. 02

    Normalize

    Every input becomes a TripEvent with a type, entities, a source and the time it was observed.
  3. 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.
  4. 04

    Classify

    Deterministic rules set severity. A small model reads only unstructured inputs such as advisories.
  5. 05

    Decide

    A Temporal Recovery workflow starts. The Recovery Agent builds options and the Mandate Engine evaluates them.
  6. 06

    Act

    The Transaction Service executes under a Mandate token, or an approval request is created with an expiry.
  7. 07

    Notify

    The notification router picks channels by severity, quiet hours and channel rules.
SignalSourceCadenceActs when
Flight statusFlightAware or Cirium alertsPush alerts from 72 hours before departure until arrivalA delay of 60 minutes that threatens a connection, or any delay of 3 hours or more
Schedule changesAggregator webhooksImmediatelyAny change of 30 minutes or more, or a broken connection
Hotel pricesSupply Gateway re-shop of refundable bookingsDaily until 7 days before the cancellation deadline, then every 6 hoursSame room, same or better terms, at least $25 and 3% cheaper
WeatherTomorrow.io7, 3 and 1 days before each outdoor plan, then hourly on the dayRain probability of 70% or more during an outdoor slot
Advisories and strikesOfficial feeds plus curated sourcesDaily, and hourly during active tripsHuman review before any traveler-facing claim
Table 4.5 · What the Guardian watches, how often, and when it acts.

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.