Design an Aggregated Flight Search Engine
System DesignModel answerLast updated
Design a large-scale flight search engine that aggregates dynamic fares from multiple third-party sources under low latency constraints.
Context
Design an aggregated flight search platform (similar to Skyscanner or Google Flights). The service enables global travelers to search for flights, apply complex filters, compare prices across various ticket vendors, and get redirected to vendor websites for checkout.
Key Requirements
Functional Requirements
- Flight Search: Support one-way and multi-city/round-trip searches given origin/destination codes, dates, passenger count, and cabin class.
- Filtering & Ordering: Users can sort results by price, total travel time, or a custom rank score ("best balance"), and filter by maximum stops, specific airlines, and departure/arrival time windows.
- Data Ingestion: Ingest live pricing and inventory data from hundreds of legacy Global Distribution Systems (GDS like Amadeus/Sabre), direct airline APIs, and online travel agencies (OTAs).
Non-Functional Requirements
- Latency: Sub-2-second response time for search requests, even when downstream external APIs are sluggish or unresponsive.
- Data Consistency: Prices displayed should be reasonably accurate. Small discrepancies between the search result and the final checkout page are tolerable if detected and flagged gracefully.
- Scale: The system must handle peak search workloads of 10,000+ QPS while operating within third-party rate limits and query cost constraints.
Deliverables
- High-level System Architecture: Core components, data ingestion flow, and user query flow.
- API Design: Endpoint specifications for submitting search requests and fetching paginated/filtered results.
- Data Storage & Caching: Database schemas, key structures, and multi-tier caching strategy.
- Resilience Strategy: Patterns for managing slow downstream integrations, rate limits, and cache staleness.
Hints
Hint 1
Consider how to prevent downstream third-party rate limits from becoming a bottleneck when handling millions of queries daily.
Hint 2
Think about an asynchronous or streaming API model to return instant cached data first while gathering fresh updates in the background.
Hint 3
Identify how to deduplicate the same flight itinerary sold by multiple distinct ticket vendors.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Constraints
Quantitative Scope
- User Traffic: ~10M Daily Active Users (DAU), averaging 5 searches per user = ~50M search queries per day.
- Throughput: Average query rate is ~600 QPS, with peak traffic reaching 8,000–10,000 QPS.
- Look-to-Book Ratio: Approximately 1,000:1. Because upstream vendors (GDSs, airlines) bill per query or strictly rate-limit API calls, fanning out every incoming search directly to external suppliers is impossible. Caching and scheduled background refreshes are core architectural requirements.
- Key Cardinality: ~50,000 active airport pairs × 330 bookable days ≈ 16.5M route-date keys for one-way journeys. Round-trip combinations grow exponentially, but queries follow a heavy power-law distribution (the top 1% of routes account for >50% of total volume).
- Latency Budget: Target p99 < 2 seconds. Upstream API response times range from 800ms to 8+ seconds.
2. API Design
Because gathering live flight data across dozens of partners can exceed the tight latency SLA, we adopt an asynchronous polling/streaming session pattern. This allows immediate returns of cached itineraries while streaming in slower provider responses.
Search Session Initialization
POST /v1/search/sessions
Request:
{
"legs": [
{
"origin": "SFO",
"destination": "JFK",
"departure_date": "2025-06-15"
}
],
"passengers": {
"adults": 1,
"children": 0
},
"cabin_class": "ECONOMY",
"currency": "USD"
}
Response (201 Created):
{
"session_id": "sess_8f93ab21",
"status": "PARTIAL",
"poll_interval_ms": 500,
"summary": {
"total_itineraries": 142,
"providers_completed": 12,
"providers_pending": 4
}
}
Fetch & Filter Session Results
GET /v1/search/sessions/{session_id}?sort_by=price&max_stops=1&airlines=UA,DL&page_token=abc123&limit=50
Response (200 OK):
{
"session_id": "sess_8f93ab21",
"status": "COMPLETE",
"pagination": {
"next_page_token": "def456",
"total_results": 310
},
"itineraries": [
{
"itinerary_id": "itin_hash_9921a",
"total_duration_minutes": 335,
"stops": 0,
"segments": [
{
"operating_carrier": "UA",
"flight_number": "UA154",
"origin": "SFO",
"destination": "JFK",
"departure_time": "2025-06-15T08:00:00-07:00",
"arrival_time": "2025-06-15T16:35:00-04:00"
}
],
"best_offer": {
"provider_id": "expedia",
"price": 312.40,
"currency": "USD",
"booking_url": "https://partner.com/book?ref=..."
},
"alternative_offers": [
{
"provider_id": "united_direct",
"price": 320.00,
"currency": "USD",
"booking_url": "https://united.com/book?ref=..."
}
]
}
]
}
3. Data Storage & Multi-Tier Caching
Data Stores
- Hot Search Cache (Redis Cluster)
- Key Format:
route:{origin}:{dest}:{date}:{cabin}:{passengers} - Value: Compressed JSON/Protobuf payload of normalized itineraries and pricing.
- TTL: Dynamic (5 minutes to 6 hours based on route popularity and time-to-departure).
- Key Format:
- Warm Persistent Cache / Offer Store (Apache Cassandra / ScyllaDB)
- Partition Key:
(origin, destination, departure_date) - Clustering Key:
(min_price, itinerary_hash) - Purpose: Durable fallback store for cache misses, feeding historical analytics, and backing low-frequency background queries.
- Partition Key:
- Session Store (Redis Cluster)
- Key Format:
session:{session_id} - Value: Set of itineraries gathered during the active search, per-provider status flags, and user filters. Short TTL (30 minutes).
- Key Format:
- Metadata Store (PostgreSQL with read replicas)
- Tables: Airports, Metro code mappings (e.g.,
NYC→JFK, LGA, EWR), Carrier info, Provider capabilities, and API credentials.
- Tables: Airports, Metro code mappings (e.g.,
+-------------------------------------------------------------------------+
| DATA LAYERS |
| |
| +---------------------+ +---------------------+ +----------------+ |
| | Redis Cluster | | Cassandra / Scylla | | PostgreSQL | |
| | (Hot Route Cache) | | (Warm Offers) | | (Metadata) | |
| | TTL: 5m - 6h | | Durable Records | | Static Specs | |
| +---------------------+ +---------------------+ +----------------+ |
+-------------------------------------------------------------------------+
4. High-Level Architecture
+-------------------+
| Client App |
+---------+---------+
|
v
+-------------------+
| API Gateway |
| (Auth / Limiting) |
+---------+---------+
|
v
+-------------------+
| Search Query |
| Service |
+----+--------+-----+
| |
Cache HIT | | Cache MISS / STALE
+-------------------------+ +--------------------------+
| |
v v
+------------------------+ +--------------------------+
| Redis Route Cache | | Scatter-Gather |
| (Return immediately) | | Orchestrator |
+------------------------+ +------------+-------------+
|
+---------------------+---------------------+
| | |
v v v
+------------------+ +------------------+ +------------------+
| Provider Adapter | | Provider Adapter | | Provider Adapter |
| (Amadeus/GDS) | | (Direct Airline)| | (OTA X) |
+--------+---------+ +--------+---------+ +--------+---------+
| | |
+---------------------+---------------------+
|
v
+--------------------+
| Kafka Ingestion |
+----------+---------+
|
v
+--------------------+
| Normalizer & |
| Deduplication |
+----------+---------+
|
+--------------------+--------------------+
| |
v v
+--------------------+ +--------------------+
| Redis Cache / | | Cassandra Store |
| Session Store | | |
+--------------------+ +--------------------+
End-to-End Query Lifecycle
- Request Intake: API Gateway receives search request, normalizes city codes to airport codes, and forwards to the Search Query Service.
- Cache Inspection: The service generates a canonical hash key for the requested leg(s). It queries the Redis Route Cache.
- Fresh Hit: If results exist and are within TTL, rank, filter, and return immediately.
- Stale / Miss: If absent or expired, push existing cached data (if any) into a new Search Session, return a
PARTIALpayload to the user, and dispatch an event to the Scatter-Gather Orchestrator.
- Scatter-Gather Orchestration:
- The orchestrator identifies which external adapters to invoke based on coverage and available rate-limit quota.
- Adapters query partner APIs concurrently.
- Normalization & Deduplication:
- Responses flow into a Kafka Topic.
- A Normalization Worker transforms provider-specific schemas into a standard internal format (
Itinerary,Leg,Segment,Offer). - Itineraries with identical flight numbers, departure times, and cabins are merged so that a single flight option displays all candidate provider offers.
- Session & Cache Update:
- New offers write to the Redis Route Cache and the Cassandra Offer Store.
- The active user session updates so subsequent client polling returns the full set.
5. Key Design Challenges & Mitigation Strategies
A. Managing Slow & Unreliable Downstream APIs
External provider APIs vary dramatically in response time and uptime. A single hanging API must not delay the overall response.
- Bulkheads: Isolate network connection pools per external adapter. If Partner A’s API stalls, its thread pool saturates while Partner B’s connections remain unaffected.
- Circuit Breakers: Track error and timeout rates per provider using a rolling window. If failure rates exceed 30%, open the breaker for 60 seconds and immediately fall back to cached data for that provider.
- Strict Per-Provider Timeouts: Set timeouts dynamically based on each vendor’s p95 SLA (e.g., 1.2s max). When the deadline expires, aggregate whatever results have arrived so far and return to the client.
B. Intelligent Pre-fetching & Dynamic Cache Invalidation
Relying solely on user-initiated searches to populate caches leads to high cache-miss latency for long-tail queries.
Priority Rank = (Historical Search Volume) × (1 / Days Until Departure) × (Price Volatility Score)
- Background Refresh Scheduler: A distributed worker pipeline evaluates the priority equation continuously. Highly popular routes departing soon (e.g., SFO–JFK in 3 days) are refreshed asynchronously every 5 minutes. Niche routes 9 months out are updated once daily or strictly on demand.
- Push-based Ingestion: Partner with airlines supporting push webhooks or bulk file feeds (e.g., ATPCO fare updates). When a carrier pushes a fare change, write it straight to Kafka to invalidate or update affected cache keys asynchronously.
C. Tiered Staleness ("Stale-While-Revalidate")
Rather than treating cache hits binary-style (valid vs. expired), use a two-tiered TTL policy:
- Fresh Window (0 to $T_{fresh}$): Served directly from Redis. Zero upstream calls triggered.
- Stale-OK Window ($T_{fresh}$ to $T_{stale}$): Served immediately to the user to keep latency low, but an asynchronous job is dispatched to fetch fresh prices.
- Hard Expiry (> $T_{stale}$): Synchronous fetch required before returning complete results.
To prevent thundering herd issues during a cache miss on a high-volume key, use a distributed lock (e.g., Redlock) so only one background worker triggers the upstream fetch per key.
6. Trade-offs & Operational Considerations
| Trade-off Dimension | Choice Made | Rationale & Alternative Considered |
|---|---|---|
| API Paradigm | Async Polling / SSE Session | Chosen: Keeps p99 latency < 2s by allowing partial updates. <br>Alternative: Single blocking HTTP call, which risks frequent timeouts or 5+ second user waits when downstream providers lag. |
| Data Consistency | Eventual Consistency | Chosen: Displays cached pricing and re-validates final price at checkout redirect. Saves massive upstream API costs. <br>Alternative: Strong consistency on every search, which would breach downstream rate limits within minutes. |
| Deduplication Strategy | Canonical Hash Merging | Chosen: Hashes flight segments (Carrier+FlightNum+DepTime) to merge identical flights across vendors. <br>Alternative: Showing unmerged results, which clutters the UI with duplicate listings. |
Failure Modes & Edge Cases
- Price Discrepancy at Checkout: When a user clicks a booking link, perform a synchronous lightweight validation check (
GET /v1/offers/{offer_id}/validate). If the downstream price has changed, present an explicit modal updating the user before redirecting. - Multi-City Route Combinatorics: Searching A → B → C → D creates a massive search space. Limit multi-city upstream fanouts to pre-computed valid connection hubs rather than unconstrained Cartesian joins.