Design Google Flights – Frontend System Design

We’ll walk through the frontend system design for Google Flights: a search UI that stays honest about prices that expire, dates that live in city timezones, and a result list users share, filter, and compare without a network round trip for every chip. You’ll see why the URL is the query, why a fare calendar is a cheaper index than the itinerary list, how filter chips stay local, and how Book hands off to someone else’s checkout after you revalidate a quote.
This is not a catalog search. An e-commerce filter can refetch. Flight search cannot. A full itinerary search talks to airline inventory and takes one to three seconds. Calendar prices are a separate, staler index. The number on a card is a timed quote, not a computed total. Design it like a product grid and you will refetch too often, paint the wrong day around midnight, and send people to book a fare that no longer exists.
Problem Statement
Design the frontend for a flight search product like Google Flights.
Requirements:
- One-way, round-trip, and multi-city search, with shareable URLs
- A fare calendar and a price graph so users pick dates by cost, not just by day
- A result list that filters by stops, airlines, times, and duration without refetching everything
- Displayed fares that expire, with a clear path when the price changes
- Compare a few itineraries on-site, then hand off to an airline or OTA to book
- Correct dates across timezones, DST, and the international date line
Describe the client architecture, the query model, how results stay fast, and how booking leaves your origin.
Interviewers are checking three things. Is the URL the source of truth, or a share afterthought? Can you split chips that slice a cache from filters that change the market? And is a fare a quote with a clock, not a number you render until Book?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Which trip types? | One-way, round-trip, and multi-city up to six legs. |
| 2 | Do we sell the ticket? | No. We search and compare. Book hands off to an airline or OTA. |
| 3 | How stale can prices be? | Calendar cells: hours. Itinerary quotes: 15–30 minutes. Book always revalidates. |
| 4 | How many results? | 50–200 typical. Nearby airports can push past 300. |
| 5 | Live price ticks? | No socket. Poll or revalidate. The calendar is not a trading chart. |
| 6 | Auth? | Optional. Signed-in users get saved searches and price tracking. |
| 7 | Devices? | Desktop and mobile web. Same URL, same query. |
Question 2 splits the product in half. Compare is our UI. Book is a redirect we do not control. Question 3 splits the calendar API from the itinerary API: they are not the same payload with a different view. Question 4 forces a virtualized list. Question 5 tells you not to invent a WebSocket for fares.
Requirements
Functional
- Search by trip type, airports or cities, civil dates, cabin, and passenger mix.
- Multi-city: add, remove, and reorder legs. Each leg has its own origin, destination, and date.
- A month calendar showing the cheapest fare per day, and a graph of those prices across a range.
- Results sorted by a default (best / cheapest / fastest) with chips for stops, airlines, departure windows, duration, bags, and emissions.
- Pin two or three itineraries in a compare tray. Book starts a partner checkout with a live quote.
- The address bar always reflects the current query. Back, forward, and a pasted link restore it.
Non-Functional
- A chip that only slices the current set applies in a frame, not after another 2s search.
- First itineraries on screen in about a second of server time, with the calendar in parallel.
- A 200-row result list stays smooth to scroll and to filter. Only the visible window mounts.
- No booking at a price the user did not see. A 409 on revalidate is a confirm step, not a silent retry.
- Dates do not jump a day because the laptop is in California and the flight leaves Tokyo.
- Keyboard and screen reader access to the form, the calendar grid, the list, and the chips.
The chip budget is one frame. If every chip hits the itinerary service, the UI feels broken no matter how pretty the calendar is.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| Itinerary payload | ~400 KB–1 MB | 180 itineraries × 2–5 KB JSON | One search is expensive. Cache it. |
| Calendar month | ~2 KB | 31 cells × { date, lowest } | Different index. Fetch in parallel, not nested. |
| Price graph | ~90 points | Cheapest fare per day for ~3 months | No downsampling needed. Plot every cell. |
| Mounted rows | ~15 | Viewport ~1200px / ~80px row | 200 mounted cards will make chips jank. |
| Local filter | < 1 ms | 180 records × a cheap predicate | The chip is a function, not a GET. |
| Quote TTL | 15–30 min | Airline hold, server clock | The card is a promise. Book revalidates. |
Architecture
The client has four layers. The important decision is which one owns the query.
| Layer | Owns | Runs on | Talks to |
|---|---|---|---|
| UI Shell | Form, calendar, list, chips, compare tray | React, main thread | Reads derived state, sends intents |
| Search Core | URL, query, fare cache, filters, quote clock | TypeScript, main thread | Network clients |
| Network | Search, calendar, quotes, airport typeahead | Main thread + AbortController | REST. No fare socket. |
| Partner | Checkout | Another origin | Redirect with a booking token |
React never holds the canonical query. A typed store parses location into a SearchQuery, and every committed edit writes the URL first. Views subscribe with useSyncExternalStore. Same boundary as Uber between the trip core and the map: chrome renders, the core owns facts. Airport typeahead is the Maps search pattern: debounce, AbortController, cache by query plus a coarse city. The selection is an IATA code plus an IANA timezone, not a lat/lng.
“The URL is the query. React renders the form and the list from a store that parses the address bar. A chip that can be answered from the cache never starts a search.”
Data Model
Two clocks live in this product, and they must not share a type. A civil date is the day the user picked on a calendar: year, month, day, interpreted in the departure city’s timezone. An instant is a real moment: departure, arrival, quote expiry. Mixing them is how you ship the midnight bug.
type AirportCode = string & { readonly __brand: "IATA" };
type IanaTz = string & { readonly __brand: "IANA" };
interface CivilDate { year: number; month: number; day: number } // month is 1-12
interface Leg {
origin: AirportCode;
dest: AirportCode;
date: CivilDate;
originTz: IanaTz; // "America/Los_Angeles", from the airport record
}
interface SearchQuery {
tripType: "oneWay" | "roundTrip" | "multiCity";
legs: Leg[];
cabin: "economy" | "premiumEconomy" | "business" | "first";
pax: { adults: number; children: number; infants: number };
nearbyAirports: boolean;
sort: "best" | "price" | "duration";
filters: FilterSet; // stops, airlines, windows, max duration, max price
}
interface FareQuote {
quoteId: string;
itineraryId: string;
amount: { cents: number; currency: string };
expiresAt: string; // ISO instant, server clock
bags: { carryOn: number; checked: number };
bookingToken: string;
}
interface Itinerary {
id: string;
slices: Slice[];
stops: number;
durationMin: number;
airlines: string[];
emissionsKg: number | null;
quotes: FareQuote[];
}
interface CalendarCell {
origin: AirportCode;
dest: AirportCode;
date: CivilDate;
lowest: { cents: number; currency: string } | null;
asOf: string; // when this estimate was computed
}
Four choices are worth defending.
The URL stores SearchQuery, not itineraries. Results are a cache keyed by the search half of the query (legs, cabin, passengers, nearby). Filters sit on the query so a shared link restores chips, but they are not part of the cache key. That is how a chip can change the URL without busting the set you already paid for.
Civil dates, not Date. Date.parse("2026-05-15") is UTC midnight on the 15th, which is the evening of the 14th in the United States. A calendar that then calls getDate() highlights the wrong cell. Keep a triple. Format it with the origin city’s timezone when you need a string.
Instants stay ISO strings from the server. Departure, arrival, and expiresAt are instants. You may display them in the departure city, the arrival city, or the viewer’s timezone, but you store the instant. Never reconstruct an instant by combining a civil date with new Date() on the laptop.
Calendar cells are a different type from quotes. lowest is an estimate with an asOf. It is allowed to be hours old and to disagree with the itinerary list. A quote is what you might book, and it dies at expiresAt. If you reuse one Price type for both, the UI will treat a calendar cell like a holdable fare.
URL as Source of Truth
Every interesting state in this app is a search someone will share. That includes chips. If the chips live only in React state, the back button undoes a destination change and forgets “nonstop”, and a pasted link opens a blank form.
Parse on boot and on popstate. Write on every committed edit. Derive the view from the store, never the other way around.
A single URL writer owns this. It takes the next query and a write kind, either "commit" (a new market) or "tweak" (a chip or a keystroke). It serializes the query to a stable query string (trip type, legs, cabin, passengers, nearby airports, filters) and returns early if the URL wouldn’t change. A commit pushes a history entry and a tweak replaces the current one. Either way it updates the store with the same query, so the URL and the store can never disagree.
Use pushState when the user commits a new market: airports, dates, cabin, passengers, trip type, an added multi-city leg. Use replaceState for in-progress typing and for local chips. Back should undo “JFK to LHR”, not each letter of “LHR” and not “1 stop” as if it were a page. Validate on parse: drop unknown keys, clamp passengers, reject a leg whose origin equals its destination, and fall back to an empty form rather than crashing on a hand-edited URL.
The store is the only place that decides whether a write refetches. Compare the new query to the cache key. If only filters or sort changed, slice the cache. If the search half changed, abort the in-flight pair and fetch again.
The cache key is a stable serialization of the search half only: trip type, legs, cabin, passengers, and nearby airports. On each query change the store compares the previous key with the next one.
- Same key: re-run the pure filter and sort over the cached itineraries, synchronously. No network.
- Different key: abort the in-flight requests, then start the itinerary search and the calendar request in parallel.
Key order must be fixed in the serializer, or two equal queries produce different keys and the cache misses for no reason.
Multi-city Search
Round-trip is two legs you generate from an origin, a destination, and two civil dates. Multi-city is an explicit list. Do not special-case round-trip as a boolean plus a return date once you have three or more hops. One legs[] keeps the form, the URL, the cache key, and the calendar request the same shape.
- Each row is origin, destination, civil date. Swapping origin and destination on one row does not swap the others.
- Adding a leg copies the previous destination into the new origin. That is the usual next hop, and it is wrong often enough that the field stays editable.
- Removing a middle leg does not renumber dates. The user chose those civil days. You may warn if date[i] is before date[i-1], but you do not silently rewrite them.
- A date is valid relative to the previous departure civil date, not relative to arrival. Arrival can be the next calendar day, or the previous one when you fly east across the date line. Comparing instants belongs in the result row, not in the form validator.
Airport fields use abort-and-debounce typeahead, biased toward the last selected city. A city pick (“New York”) sets nearbyAirports or expands to that city’s airports. JFK-only and NYC-area are different cache keys. Cabin and passengers belong on the query, not on a chip: they change inventory. Putting them next to “Nonstop” in the UI is fine. Putting them on the same code path is the bug.
Fare Calendar and Price Graph
The calendar answers a different question than the list. The list is “what can I fly on these dates?” The calendar is “which dates are cheap for this market?” Those are two indexes. Fetch them in parallel when the search half of the query changes. Do not wait for itineraries to draw the grid, and do not ask the itinerary service for thirty extra dates.
A cell is (origin, dest, civil date) -> lowest fare. For round-trip, hold the return fixed and vary the outbound. That is enough in an interview. A return-versus-outbound grid is the follow-up.
The graph is those same cells as a polyline. Ninety points do not need Robinhood-style downsampling. Hover previews a civil date. Click commits it: pushState, new cache key, new itinerary search. Hover does not write the URL.
A cell click commits a new query with that leg’s date, as a push, not a replace. Prefetch the next month when the grid is idle, and cancel that prefetch if the market changes. Stale cells are expected: never put a calendar lowest on the Book button. A date with no inventory is a muted cell, not $0. A month the index has not built is a skeleton, not a guess from the last market.
Filter Chips That Do Not Refetch
This is the part juniors miss. They put every control on one useEffect that refetches. Seniors split the controls.
Local, no network: stops, airlines, departure or arrival windows, max duration, emissions, alliance, overnight. Each of those fields is already on the itinerary. The chip is a predicate. Facet counts come from the cached set, so tapping “Nonstop” can dim “United” if no nonstop United remains.
Refetch: airports, nearby, dates, cabin, passengers, trip type, extra legs. These change the market. The cache is wrong. Abort and replace it.
The one hybrid: a max-price slider. If the payload is not truncated, filter locally. If the server capped at “best 180” and they drag below the cheapest cached fare, you already have every cheaper option. Only refetch with a price ceiling if truncation could hide cheaper inventory. Say that so the interviewer knows you thought about it.
The filter is a pure function from the cached itineraries and a filter set to a new list. Each chip is one predicate, and an itinerary must pass all of them: stop count at or under the limit, at least one selected airline, duration under the cap, a live quote under the max price, and a first departure inside one of the selected windows. Because it is pure and runs over a few hundred items, it finishes well inside one frame and needs no worker or debounce.
Departure windows are in the origin city’s civil day, not the viewer’s laptop. A “morning” chip means morning in SFO when the flight leaves SFO. Compute minutes from local midnight with the slice’s timezone. That function is the same one the calendar uses, so a flight that leaves at 00:20 JST does not fall into “evening” because you parsed the instant in Pacific time.
Sort is local too. “Best” is a server score if the payload has one. Do not invent a score that will disagree with the next refetch. Fall back to price. Write the chip with replaceState. Facets come from the unfiltered cache so two airlines can still be checked.
Virtualized Results
A flight row is a heavy card: two slice timelines, airline marks, duration, stops, one or more fare chips, emissions, and a compare control. Two hundred of those in the DOM will make the first paint and every local filter feel slow. Window the list.
- A fixed row height (or a small set of heights: collapsed versus expanded fares) lets you compute the window from scrollTop without measuring.
- Keep a buffer of a few rows above and below the viewport so fast flings do not flash empty space.
- Keys are
itineraryId, never the index. A filter pass that remounts row 0 as a different flight will steal focus and reset expand state. - Overscan images: airline marks are tiny and cacheable. Do not lazy-load the twelve logos on screen.
A tall spacer plus rows positioned at i * ROW is enough. Overscan four rows so a fling does not flash empty space. Expanding a row for fare families (basic economy versus a bag) changes height: keep two heights and recompute the spacer. Do not drop virtualization for one open card.
Empty and error states sit outside the window. A chip that filters to zero rows is not a network failure: offer “Clear filters” from the same cache. After a search or a chip, an aria-live="polite" region says “42 flights, from $248”. Do not announce on scroll.
Stale Fare Quotes
The number on the card is a promise from the quote service: this itinerary, this amount, until expiresAt. The client does not compute fares. It displays one, watches the clock, and revalidates before anyone leaves for checkout.
Track a clock offset the same way you would for an Uber quote. When a response includes a server Date header or a serverNow field, store offsetMs = serverNow - Date.now(). Remaining time is Date.parse(expiresAt) - (Date.now() + offsetMs). A laptop with a wrong clock must not show an expired quote as live, or kill a live quote two minutes early.
type QuoteView = "fresh" | "aging" | "expired" | "revalidating" | "price_changed";
Two pieces sit behind that union. A pure quote view function computes time left from expiresAt and the server-corrected clock: zero or less is expired, under two minutes is aging, anything else is fresh. The revalidating and price_changed states come from the second piece, a revalidate call. It asks the quote service about the quote id and returns either the refreshed quote or a “changed” result when the amount or currency differs.
fresh shows the amount and enables Book. aging adds a quiet countdown and starts a background refresh so T-0 is not a spinner. expired dims the amount and disables Book; a pinned compare card expires on its own clock. revalidating blocks a second click. price_changed puts the new amount on screen and waits for confirm. Never redirect at $458 while the button still says $412.
Calendar prices stay estimates. If the list is $40 above the cell, show the list. The cell was hours old. The quote is the contract. When the tab becomes visible, recheck aging quotes in the list and tray. Do not refetch the whole search because the user glanced at Slack.
Compare Versus Book
Compare and Book look like two buttons on the same card. They are different products.
Compare stays on your origin. Pin two or three itineraries. The tray holds itinerary id, slice summary, and the quote that was live when pinned. Each pin expires on its own clock; a dead card offers refresh and does not evict the others. Sorting the list does not clear the tray. Changing the market does, or you mix SFO–JFK with SFO–LHR.
Book leaves your origin. Do not embed a partner checkout. Revalidate, then navigate to the URL the quote service returns, with the booking token and a return URL equal to the current search URL. A user who abandons checkout lands back on the same query. Same tab on mobile; new tab on desktop if you must. Do not lose the search URL.
The booking handoff is two steps. First, revalidate. If the price changed, put the new quote in the store and stop, so the user has to confirm the new amount and start again. Second, call startBooking with the quote id, the booking token, and the current search URL as the return URL, then navigate the whole tab to the partner redirect URL the server returns.
Idempotency belongs on startBooking. Generate the key on first confirm and reuse it on retry so a double click does not create two partner sessions. If asked about embedding the airline page, say no: cookies, CSP, PCI, and a UI you do not control. A redirect is the boundary. Your job ends when the quote is still valid and the user sees the same price on the way out.
Timezone and Date-Boundary Bugs
This is the section that separates a search page from a flight product. Most of the bugs are the same bug: you stored a civil date as a JavaScript Date.
| Bug | What the user sees | Fix |
|---|---|---|
| Date-only ISO parse | May 15 becomes May 14 in the US | Store CivilDate. Never new Date("2026-05-15"). |
| Laptop timezone | A traveler in London books a SFO morning flight as “afternoon” | Windows and formatting use the slice’s origin timezone. |
| Date line westbound | SFO→NRT leaves May 15 and arrives May 16 | Show both local dates on the row. Do not forbid arrive > depart civil. |
| Date line eastbound | NRT→SFO leaves May 16 and arrives May 15 | Show “arrives previous day”. Do not sort that row as negative duration. |
| DST spring / fall | 02:30 does not exist, or 01:30 happens twice | Display the server instant. Do not invent a local clock time. |
| Multi-city mix | Leg 2’s date validated in leg 1’s city | Each leg carries its own originTz. |
Format a civil date as noon in that city with Intl.DateTimeFormat and an explicit timeZone, so DST cannot slide it across midnight. Minutes-from-midnight for a “morning” chip uses the same API on the slice instant. Do not subtract getTimezoneOffset(): that is the viewer’s zone, and it changes on DST weekends. If the airport lookup has not returned originTz, you do not know the civil day. Block search.
Duration is elapsed instants, not civil days. A flight that arrives “yesterday” still has a positive durationMin from the payload. Do not replace it with arriveDate - departDate in local calendars.
API
All of this is request/response. There is no fare socket. Abort in-flight work when the cache key changes.
// REST
GET /api/airports?q= // typeahead: code, city, tz
GET /api/itineraries?q= // SearchQuery minus local-only display
GET /api/calendar?origin=&dest=&month= // CalendarCell[]
GET /api/graph?origin=&dest=&from=&to= // same cells, range
POST /api/quotes/check // { quoteId } -> FareQuote | 409
POST /api/bookings // Idempotency-Key, quoteId, returnUrl
// ItinerariesResponse: serverNow, truncated, facets, itineraries[]
// BookingSession: redirectUrl (partner origin), expiresAt
Send serverNow on every search and check so the quote clock can set offsetMs without trusting Date. Send truncated so the price slider knows whether local filter is complete. Send facet counts from the unfiltered set.
On a failed search, keep the last cache and show retry. A calendar failure must not blank the list, and the reverse. Saved searches store the serialized query. Opening one is writeQuery(..., "commit"). Price tracking is email from the server, not a socket on this page.
State and Data Flow
One store, two writes, one cache. Keystrokes replaceState a partial query and do not refetch. A commit (Search, calendar click, complete airport) pushStates, aborts, and fetches itineraries plus calendar. The response fills the cache and sets offsetMs. A chip replaceStates filters and slices that cache; facets stay on the unfiltered set. Pins live in the compare tray, not the URL. Book revalidates, then location.assign. popstate runs the same onQueryChange as a write. Keep an LRU of a few cache keys so Back onto yesterday’s dates is instant; evict on cabin or passengers, not on chips.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Chip feels like a search | Cache key excludes filters | Predicate in one frame |
| 200 heavy rows | Windowed list, fixed row height | Style and layout stay on ~15 cards |
| Two searches in flight | AbortController per cache key | An old LHR response cannot overwrite SFO |
| Calendar waits on list | Parallel GET, separate caches | Dates paint while itineraries stream |
| Quote dies at T-0 | Background check in aging |
Book is a confirm, not a surprise spinner |
| Back to a recent market | LRU of a few cache keys | Instant list, then a quiet revalidate |
If the itinerary API streams, paint the first rows as they arrive and recompute facets at the end. If it is one JSON body, show the calendar and a skeleton list. Do not block the calendar on the list.
Handling Edge Cases
- Partial query. Origin without destination is typeahead, not a search. Do not fire
/itinerarieson an incompleteSearchQuery. - Same-day multi-city. Allowed. Validate airports, not hours, in the form. Impossible connections show up as missing itineraries, not as a blocked date picker.
- Sold out after calendar click. The list is empty and the cell still shows $248. Explain that the estimate is stale. Offer nearby dates from the calendar cache.
- Currency. Quotes carry a currency code. Do not mix USD cells with EUR list prices without a convert step. Default to the user’s selected currency on the query so the cache key includes it.
- Infant on lap. Passenger mix changes inventory. Refetch, even if the stepper sits next to the chips.
- Long disconnect. Keep the last cache, expire quotes by the clock, retry when online. A 40-minute-old quote is not bookable.
- Partner tab blocked. Fall back to same-tab redirect. Never drop the booking token.
Accessibility and Security
Accessibility
- The search form is labeled fields. The calendar is a
gridwith arrow keys andaria-selectedon the civil day. - Chips are toggle buttons. The name includes state: “Stops, 1 stop, selected”.
- The result list is a list or table. Virtualization still announces count (or
aria-setsize). A canvas list is a non-starter. - The graph is not the only way to pick a cheap date: the calendar, or a day/price table, is the accessible alternative.
- Quote ageing is text, not color alone: “Price expires in 1:48”.
- Respect
prefers-reduced-motionon month changes and row expand.
Security
- The booking token is a capability. Do not log it or put it in your address bar.
- Build the partner return URL from
serialize(query), not from a user-supplied parameter. - Typeahead names are text, not HTML.
- A shared search URL is not secret. A booking session URL is.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| State | React state plus a fetch in useEffect | URL is the query; store parses it; cache key ignores chips |
| Filters | Refetch on every chip | Local predicates vs market changes; facets from the unfiltered cache |
| Calendar | Same search, thirty times | Separate cheap index, parallel fetch, estimates not quotes |
| Dates | new Date(yyyy-mm-dd) |
CivilDate + airport IANA zone; instants for depart and expiry |
| Price | A number on the card | Quote with offset clock, aging, 409 confirm, then handoff |
| Book | POST and hope | Revalidate, idempotent session, redirect, return URL is the search |
Conclusion: How to Design Google Flights
Start with the query. Put it in the URL, parse it into a SearchQuery, and let the store decide whether a write is a local chip or a new market. Fetch itineraries and the fare calendar in parallel: different indexes, different freshness.
Keep civil dates out of Date, and quotes on a server clock. Virtualize the list so a chip runs in a frame. When the user books, revalidate and leave. If you can explain why “1 stop” does not refetch and why May 15 must not parse as UTC midnight, you designed the product, not a search box with a table under it.
