Vetting and Onboarding Undocumented Travel Funnel Data

Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite

Prompt

You have just taken ownership of a sparsely documented set of hotel shopping and reservation tables in your warehouse (searches, impressions, clicks, bookings, and cancellations). Walk through a concrete, step-by-step onboarding plan that covers the following six areas in execution order:

  1. Schema and key discovery: Inventory the available tables and columns, establish each table's true grain, and empirically verify candidate primary keys, foreign-key links, and parent-child cardinalities.
  2. Column and format profiling: Audit value distributions, null and placeholder patterns, timestamp semantics and time-zone offsets, regional locale formatting, and currency codes or minor-unit scaling.
  3. Deduplication and join safety: Identify exact, versioned, and near-duplicate records, and prevent row multiplication (fan-out) when joining the five funnel tables (searches, impressions, clicks, bookings, and cancellations).
  4. Funnel ordering and delayed ingestion: Verify causal progression across the reservation lifecycle (search through cancellation) while accounting for client clock skew, late-arriving mobile uploads, and event-time watermarks.
  5. Metric and unit-economics definitions: Formulate accurate SQL/analytical logic for core KPIs—including seven-day reservation conversion per search, gross margin (price minus wholesale cost), and Gross Merchandise Value (GMV) versus contribution margin.
  6. Automated quality gates and data contracts: Design executable checks and upstream producer agreements covering non-null constraints, key uniqueness, referential integrity, valid numeric bounds, and freshness SLAs.

Finally, describe at least three domain-specific traps unique to lodging and travel data—such as multi-room itineraries, partial stay shortenings or modifications, cancel-and-rebook behavior, exchange-rate timing between reservation date and check-in date, or adult versus child guest counts—and explain how you would detect each one in the raw tables.

Scope & Expectations

  • Present an ordered onboarding sequence where foundational structural checks (grain, keys, currency units, deduplication) run before funnel joins and financial aggregations.
  • Provide concrete SQL or Python patterns for proving key integrity, pre-aggregating one-to-many tables to avoid fan-out, and applying watermark cutoffs to maturing cohorts.
  • Clearly separate top-line booking value from net unit economics, stating explicit attribution rules, cancellation handling, and FX conventions.
  • Pair travel-specific edge cases with empirical diagnostic queries and upstream producer contract rules that stop regressions before they corrupt downstream reporting.

Step-by-step walkthrough

  1. Map table schemas and verify grain, keys, and cardinality

    Before computing any metric, establish what each table actually represents. Suppose the warehouse has five funnel tables: searches, impressions, clicks, bookings, and cancellations. Every table has a grain—a single plain-English sentence stating what one row represents in the real world (for example, "one row per user search" or "one row per booking modification version").

    Follow four discovery steps before trusting column names:

    1. Talk to owners and read pipeline code first. Ten minutes with the data-engineering owner, dbt models, or ingestion code reveals undocumented filters, backfills, and table deprecations faster than hours of blind querying.
    2. Inventory tables and column types from information_schema.columns. Flag timestamp types (TIMESTAMP without time zone vs. TIMESTAMPTZ with time zone) and money types (NUMERIC(12,2) vs. floating-point DOUBLE, which introduces rounding noise).
    3. Check row counts, date coverage, and refresh cadence. A table that stops updating two days ago or starts six months later than the others invalidates every multi-table join.
    4. Prove primary keys, foreign keys, and cardinality with SQL. A primary key uniquely identifies every row and is never NULL. A foreign key points to the primary key of a parent table; a child row whose parent key is missing is an orphan row. Cardinality describes how many child rows can belong to one parent row (1:1, 1:N, or M:N).
    -- 1. Primary key check: is booking_id unique and never NULL?
    SELECT COUNT(*)                     AS total_rows,
           COUNT(DISTINCT booking_id)   AS distinct_booking_ids,
           COUNT(*) - COUNT(booking_id) AS null_booking_ids
    FROM bookings;
    
    -- 2. Foreign key check (referential integrity): bookings pointing to a missing search
    SELECT COUNT(*) AS orphan_bookings
    FROM bookings b
    LEFT JOIN searches s ON s.search_id = b.search_id
    WHERE b.search_id IS NOT NULL
      AND s.search_id IS NULL;
    
    -- 3. Cardinality check: how many bookings can a single search produce?
    SELECT bookings_per_search,
           COUNT(*) AS search_count
    FROM (
        SELECT search_id, COUNT(*) AS bookings_per_search
        FROM bookings
        WHERE search_id IS NOT NULL  -- exclude untracked bookings so NULLs do not lump together
        GROUP BY search_id
    ) per_search
    GROUP BY bookings_per_search
    ORDER BY bookings_per_search;
    

    Suppose the first query returns 1,204,330 total rows and 1,201,118 distinct booking_id values (3,212 extra rows, or 0.27%). That proves booking_id alone is not the primary key—the table likely logs one row per modification, making (booking_id, version) the true grain. Always check relationships in both directions: children missing a parent (phone or partner bookings with no search_id) and parents missing expected children (searches with zero impressions, which can mean genuine zero-result queries or broken impression logging on one mobile app version).

  2. Inspect value distributions, null patterns, timestamps, locales, and currencies

    For every column, compute the NULL rate, distinct count, top 10 most frequent values, and numeric percentiles (min, p1, p50, p99, max). Raw summaries catch crashes, but silent analytical bugs hide in five places:

    • Sentinel values masquerading as real numbers or dates. A sentinel value is a fake placeholder such as -1, 0, 999, '1970-01-01', or 'N/A' stored instead of NULL. Including -1 in AVG(price) quietly drags the mean down without triggering IS NULL checks.
    • Systematic missingness. Plot NULL rates by day, platform, and booking channel. For example, if cost is NULL on 12% of bookings and every single one is a "pay-at-property" hotel stay, averaging price - cost over non-null rows silently drops an entire business model.
    • Time zones and daylight saving time (DST). Plot hourly search volume for a single-country market: US traffic bottoms out around 03:00–05:00 local time, so if the quietest hours sit at 07:00–10:00, the timestamp is UTC; if they sit at 03:00–05:00, it is local time. Local-time columns also show 23-hour days in spring and 25-hour days in autumn. Meanwhile, hotel check_in_date and check_out_date are property-local calendar dates with no time zone. Computing booking lead time as check_in_date - DATE(booking_ts_utc) turns a same-day 21:00 New York booking on March 1 (already 2026-03-02 02:00 UTC) into -1 days.
    • Locale formatting. Watch for European decimal commas ("1.234,56" truncated to 1.234), swapped DD/MM vs. MM/DD strings (values above 12 in the first slot prove DD/MM), and translated status strings ("Cancelled", "Cancelado", "Annulé").
    • Mixed currencies and minor units. Never sum or average a raw price column before grouping by ISO currency code (USD, EUR, JPY). One unconverted yen booking ruins a 100-booking average:
    99 bookings at 150 USD + 1 booking at 18,000 JPY (exchange rate: 150 JPY = 1 USD)
    
    Naive average (unconverted):  (99 * 150 + 18,000) / 100 = 32,850 / 100 = 328.50  (wrong by +119%)
    Converted to USD first:       (99 * 150 +    120) / 100 = 14,970 / 100 = 149.70  (correct)
    

    Also check minor units—storing money in the smallest indivisible unit (such as cents). USD uses 2 decimal places ($150.00 = 15000 cents), JPY uses 0 (18,000 yen = 18000), and Kuwaiti dinar (KWD) uses 3 (45.000 KWD = 45000). Dividing every currency blindly by 100 understates JPY by 100x and overstates KWD by 10x.

  3. Remove duplicate events and prevent multi-table fan-out

    Duplicates appear in three distinct forms, each needing its own detector:

    1. Exact row duplicates from re-ingested batch files. Group by every column (GROUP BY col1, col2, ... HAVING COUNT(*) > 1) rather than COUNT(DISTINCT ...), because SQL DISTINCT over multiple columns is non-standard in several engines and can mishandle NULL values.
    2. Duplicate keys with different payloads from status updates or retries. Deduplicate deterministically with ROW_NUMBER() OVER (PARTITION BY booking_id ORDER BY updated_at DESC, ingest_ts DESC) = 1.
    3. Near-duplicate client events when a double-tap or network retry fires two events with different event_id values a second apart. Use LAG(event_ts) OVER (PARTITION BY user_id, hotel_id, event_type ORDER BY event_ts) and flag gaps under 5 seconds; fixed 5-second clock buckets miss pairs at 10:00:04.9 and 10:00:05.1.

    Even when every individual table is clean, join inflation (fan-out) corrupts totals whenever two one-to-many child tables are joined directly through their shared parent. Suppose search s1 displays 20 hotel impressions, gets 3 clicks, and leads to 1 booking worth $500:

    Direct join on search_id (many-to-many fan-out across children):
      search s1 (1 row)
        |-- x 20 impressions
        |-- x  3 clicks
        |-- x  1 booking ($500)
      Result: 1 * 20 * 3 * 1 = 60 rows -> SUM(b.total_usd) = 60 * $500 = $30,000 (60x too high!)
    
    Pre-aggregated join (reduce each child table to search_id grain first):
      search s1 (1 row) + imp (1 row: count=20) + clk (1 row: count=3) + bkg (1 row: count=1, rev=$500)
      Result: 1 row -> revenue = $500 (exact)
    
    -- Correct pattern: aggregate every child table to search_id grain BEFORE joining
    WITH imp AS (
        SELECT search_id, COUNT(*) AS impressions
        FROM impressions
        GROUP BY search_id
    ),
    clk AS (
        SELECT search_id, COUNT(*) AS clicks
        FROM clicks
        GROUP BY search_id
    ),
    bkg AS (
        SELECT search_id, COUNT(*) AS bookings, SUM(total_usd) AS revenue_usd
        FROM bookings
        WHERE search_id IS NOT NULL
        GROUP BY search_id
    )
    SELECT s.search_id,
           COALESCE(imp.impressions, 0) AS impressions,
           COALESCE(clk.clicks, 0)      AS clicks,
           COALESCE(bkg.bookings, 0)    AS bookings,
           COALESCE(bkg.revenue_usd, 0) AS revenue_usd
    FROM searches s
    LEFT JOIN imp ON imp.search_id = s.search_id
    LEFT JOIN clk ON clk.search_id = s.search_id
    LEFT JOIN bkg ON bkg.search_id = s.search_id;
    

    Guard every join with two invariants: assert COUNT(*) = COUNT(DISTINCT search_id) on the joined output, and verify that SUM(revenue_usd) after the join matches SUM(total_usd) in bookings for tracked searches.

  4. Check funnel ordering, clock skew, and late-arrival watermarks

    A healthy reservation lifecycle moves forward from search to impression, click, booking, and optional cancellation. Audit every link for out-of-order timestamps and missing steps:

    • Timestamp ordering with clock-skew tolerance. Mobile and browser clocks drift slightly from server clocks, so allow a small measured tolerance (say 2 minutes) when checking click_ts >= impression_ts, while strictly flagging impossible reversals such as a cancellation timestamp earlier than its server-generated booking timestamp.
    • Channel-aware orphan rates. Direct bookmarks, deep links, and call-center reservations legitimately create bookings without clicks or searches; track orphan share by channel so a logging outage on iOS stands out immediately.
    -- 1. Sequence violation beyond a 2-minute client clock-skew tolerance
    SELECT COUNT(*) AS clicks_before_impression
    FROM clicks c
    JOIN impressions i ON i.impression_id = c.impression_id
    WHERE c.click_ts < i.impression_ts - INTERVAL '2 minutes';
    
    -- 2. Arrival lag distribution (processing/ingestion time minus actual event time)
    SELECT event_type,
           PERCENTILE_CONT(0.50)  WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM ingest_ts - event_ts)) AS p50_lag_sec,
           PERCENTILE_CONT(0.99)  WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM ingest_ts - event_ts)) AS p99_lag_sec,
           PERCENTILE_CONT(0.999) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM ingest_ts - event_ts)) AS p999_lag_sec
    FROM all_funnel_events
    WHERE event_ts <= ingest_ts + INTERVAL '2 minutes'  -- quarantine future-stamped bad client clocks
    GROUP BY event_type;
    

    Events occur in event time (event_ts, when the traveler clicked or booked) but land in the warehouse in ingestion time (ingest_ts, when an offline mobile app reconnects and uploads). A watermark is the event-time threshold behind which almost all delayed events have arrived:

    watermark_ts = max(valid event_ts seen so far) - allowed_lateness L
      (after filtering out future-stamped rows where event_ts > ingest_ts + 2 min,
       so one misconfigured phone set to year 2029 cannot jump the watermark forward)
    
    Example for a March 1 UTC search cohort with a 7-day booking window and L = 48 hours:
      Search cohort:       [Mar 01 00:00, Mar 02 00:00)
      Last search converts up to +7 days:              Mar 09 00:00  (conversion window closes)
      Wait L = 48 hours for late uploads to arrive:    Mar 11 00:00  (watermark >= Mar 09 00:00 -> FINAL)
    

    Before March 11 00:00 UTC, label March 1 conversion numbers as provisional. Any ultra-late event arriving after the watermark closes should be routed to a late-arrivals audit table and tracked as a metric rather than silently dropped.

  5. Formulate conversion, gross margin, GMV, and contribution margin

    Every business metric needs a written formula specifying numerator, denominator, attribution rule, time window, and cohort maturity.

    Seven-day booking conversion per search. If a traveler runs 3 searches and makes 1 booking, crediting every prior search gives 3 / 3 = 1.0, whereas crediting at most one search per booking gives 1 / 3 = 0.333. Use single-search last-touch attribution: credit the booking's tracked search_id if it occurred within the prior 7 days; if search_id is NULL, fall back to the same user's most recent search in [booking_ts - 7 days, booking_ts]. Filter out test traffic on both tables using COALESCE(..., FALSE) (so NULL flags are not dropped by SQL three-valued logic), and restrict searches to cohorts whose 7-day window sits behind the watermark:

    WITH watermark AS (
        -- Latest valid event timestamp across bookings minus 48 hours of allowed lateness
        SELECT MAX(booking_ts) - INTERVAL '48 hours' AS wm_ts
        FROM bookings
        WHERE booking_ts <= ingest_ts + INTERVAL '2 minutes'
    ),
    candidate_matches AS (
        SELECT b.booking_id,
               s.search_id,
               -- Deterministic tie-breaker if two searches share the exact same timestamp
               ROW_NUMBER() OVER (
                   PARTITION BY b.booking_id
                   ORDER BY s.search_ts DESC, s.search_id DESC
               ) AS rn
        FROM bookings b
        JOIN searches s
          ON (s.search_id = b.search_id
              OR (b.search_id IS NULL AND s.user_id = b.user_id))
         AND s.search_ts <= b.booking_ts
         AND s.search_ts >= b.booking_ts - INTERVAL '7 days'
        WHERE COALESCE(b.is_test, FALSE) = FALSE
          AND COALESCE(s.is_test, FALSE) = FALSE
    ),
    attributed_bookings AS (
        SELECT booking_id, search_id
        FROM candidate_matches
        WHERE rn = 1
    )
    SELECT DATE(s.search_ts) AS search_day,
           COUNT(DISTINCT a.booking_id) * 1.0 / COUNT(DISTINCT s.search_id) AS bookings_per_search
    FROM searches s
    CROSS JOIN watermark w
    LEFT JOIN attributed_bookings a ON a.search_id = s.search_id
    -- Every search on search_day must have its full 7-day window behind the watermark
    WHERE COALESCE(s.is_test, FALSE) = FALSE
      AND DATE(s.search_ts) + INTERVAL '8 days' <= w.wm_ts
    GROUP BY DATE(s.search_ts)
    ORDER BY search_day;
    

    GMV, gross margin, and contribution margin. GMV (Gross Merchandise Value) is the total room price the traveler pays (state explicitly whether taxes and fees are excluded and whether it is gross or net of cancellations). Under a merchant model (where the platform collects payment from the traveler and pays the hotel), gross margin is price - hotel_cost converted to USD using the same FX rate policy. Contribution margin subtracts variable per-booking expenses—payment processing fees, customer support, and attributed paid-marketing spend—to measure whether the booking actually added profit:

    Worked single booking: 2 rooms x 3 nights x $150/night (merchant model, pre-tax)
      GMV (price paid by traveler):                 2 * 3 * $150  =  $900.00
      Wholesale cost owed to hotel:                               = -$765.00
      Gross margin (price - cost, 15.0% take rate):               =  $135.00
      Payment processing fee (2.5% of GMV):                       =  -$22.50
      Attributed paid-search acquisition cost:                    =  -$40.00
      Contribution margin:                                        =   $72.50
    

    Notice what happens if the traveler later cancels for a full refund: net GMV drops to $0, gross margin drops to $0, but the $40.00 ad click is already spent and part of the payment fee may be non-refundable—turning contribution margin negative. Also report margin per room-night ($135 / 6 = $22.50) so corporate group bookings do not skew averages.

  6. Automate table assertions and upstream producer contracts

    Turn every assumption into an automated SQL check that counts violating rows (0 violations = pass) across six dimensions: key uniqueness, non-nullability, foreign-key integrity, valid value bounds, freshness (max timestamp lag), and volume anomalies (row count vs. same-weekday trailing 4-week average).

    import sqlite3
    
    # Each check returns the count of violating rows; 0 means the check passes.
    QUALITY_CHECKS = {
        "bookings.booking_id_unique": """
            SELECT COUNT(*) FROM (
                SELECT booking_id FROM bookings GROUP BY booking_id HAVING COUNT(*) > 1
            )""",
        "bookings.total_price_not_null": """
            SELECT COUNT(*) FROM bookings WHERE total_price IS NULL""",
        "bookings.search_id_referential_integrity": """
            SELECT COUNT(*)
            FROM bookings b
            LEFT JOIN searches s ON s.search_id = b.search_id
            WHERE b.search_id IS NOT NULL AND s.search_id IS NULL""",
        "bookings.rooms_in_valid_range": """
            SELECT COUNT(*) FROM bookings WHERE rooms < 1 OR rooms > 9""",
        "bookings.adults_at_least_one": """
            SELECT COUNT(*) FROM bookings WHERE adults < 1""",
        "cancellations_not_before_booking": """
            SELECT COUNT(*)
            FROM cancellations c
            JOIN bookings b ON b.booking_id = c.booking_id
            WHERE c.cancel_ts < b.booking_ts""",
    }
    
    
    def run_quality_checks(conn: sqlite3.Connection, checks: dict) -> dict:
        """Return {check_name: violating_row_count} for every check with at least one violation."""
        failures = {}
        for check_name, query in checks.items():
            violation_count = conn.execute(query).fetchone()[0]
            if violation_count > 0:
                failures[check_name] = violation_count
        return failures
    
    
    # Self-contained demo showing every failure mode caught on toy travel rows
    conn = sqlite3.connect(":memory:")
    conn.executescript("""
        CREATE TABLE searches (search_id TEXT, user_id TEXT, search_ts TEXT);
        CREATE TABLE bookings (booking_id TEXT, search_id TEXT, booking_ts TEXT,
                               rooms INTEGER, adults INTEGER, total_price REAL);
        CREATE TABLE cancellations (booking_id TEXT, cancel_ts TEXT);
    
        INSERT INTO searches VALUES
            ('s1', 'u1', '2026-03-01T10:00:00Z'),
            ('s2', 'u2', '2026-03-01T11:00:00Z');
        INSERT INTO bookings VALUES
            ('b1', 's1', '2026-03-01T10:20:00Z', 1, 2, 300.0),
            ('b2', 's2', '2026-03-01T11:30:00Z', 2, 0, 540.0),
            ('b2', 's2', '2026-03-01T11:30:00Z', 2, 0, 540.0),
            ('b3', 's9', '2026-03-02T09:00:00Z', 12, 2, NULL);
        INSERT INTO cancellations VALUES
            ('b1', '2026-03-01T09:00:00Z');
    """)
    
    for name, bad_rows in run_quality_checks(conn, QUALITY_CHECKS).items():
        print(f"FAIL {name}: {bad_rows}")
    # Each rule fails once here except adults_at_least_one, which fails twice because b2 is duplicated.
    

    Downstream tests catch breakage after it lands; a data contract prevents breakage upstream by encoding schema, grain, SLA, and valid ranges as a versioned agreement enforced in the producer team's CI/CD pipeline:

    dataset: bookings_v1
    owner: checkout-platform-team
    grain: one row per booking_id (current state); full audit trail in bookings_events
    freshness_sla: max(ingest_ts) <= 2 hours old; daily UTC partition finalized by 06:00 UTC
    columns:
      booking_id:  {type: string, not_null: true, unique: true, severity: block_pipeline}
      search_id:   {type: string, references: searches.search_id, max_orphan_rate: 0.02, severity: alert}
      rooms:       {type: int, not_null: true, range: [1, 9], severity: alert}
      adults:      {type: int, not_null: true, range: [1, 30], severity: block_pipeline}
      children:    {type: int, not_null: true, range: [0, 20], severity: alert}
      total_price: {type: decimal(12,2), not_null: true, range: [0, 500000], severity: block_pipeline}
      currency:    {type: string, not_null: true, accepted_set: ISO_4217, severity: block_pipeline}
    evolution_policy: additive nullable columns allowed; column renames, type changes, or grain changes require bookings_v2 and 30 days notice
    
  7. Catch hospitality domain traps and execute the onboarding sequence

    Hospitality datasets have domain traps that pass generic schema checks unless tested explicitly:

    1. Multi-room reservations. One partner feed sends a 3-room family trip as a single row with rooms = 3, while another sends 3 separate rows sharing an itinerary_id. Counting rows measures bookings in one feed and room-bookings in the other. Detect: compare COUNT(*) vs. COUNT(DISTINCT itinerary_id) by partner source, and check whether total_price / (rooms * nights) stays stable as rooms increases.
    2. Stay shortenings and partial refunds. Shortening a 5-night stay to 3 nights or cancelling 1 of 2 rooms often mutates total_price in place without inserting a row in cancellations. Detect: diff daily snapshots of bookings for total_price or nights changes on existing booking_ids, check 0 < refund_amount < total_price, and flag impossible rows where summed refunds exceed original total_price.
    3. Cancel-and-rebook price drops. Travelers with free cancellation often cancel and immediately rebook the same hotel when rates drop. One real stay inflates gross bookings to 2 and cancellations to 1. Detect: join cancellations back to bookings for the same user, hotel, and overlapping stay dates within 48 hours:
    SELECT c.booking_id  AS cancelled_booking_id,
           b2.booking_id AS replacement_booking_id
    FROM cancellations c
    JOIN bookings b1 ON b1.booking_id = c.booking_id
    JOIN bookings b2
      ON b2.user_id = b1.user_id
     AND b2.hotel_id = b1.hotel_id
     AND b2.booking_id <> b1.booking_id
     AND b2.booking_ts BETWEEN c.cancel_ts - INTERVAL '48 hours'
                           AND c.cancel_ts + INTERVAL '48 hours'
     AND b2.check_in_date  < b1.check_out_date
     AND b2.check_out_date > b1.check_in_date;
    
    1. Exchange-rate timing: reservation date versus check-in date. A EUR 1,000 summer hotel booked on March 1 at 1.08 USD/EUR equals $1,080, but valued at check-in in June at 1.12 USD/EUR equals $1,120—a $40 (3.7%) difference with zero change in hotel performance. Detect: recompute USD columns against daily FX tables at both booking_date and check_in_date to verify which convention each table stores before reconciling with Finance.
    2. Adult versus child occupancy reporting. Some channels populate adults = 2, children = 1, others lump everyone into adults = 3, and mobile quick-search defaults often send adults = 1, children = 0 until checkout. Detect: check adults = 0 (unaccompanied children bugs), children > 0 with missing child-age arrays, and channels where AVG(adults + children) per room sits suspiciously near 1.00.
    3. Scraper bots and bundled packages. Price-comparison scrapers generate thousands of searches with zero bookings, crushing bookings_per_search, while flight + hotel package rows carry opaque allocated room prices. Detect: inspect p99.9 searches per IP/user-hour for bots, and isolate is_package = TRUE rows from standalone hotel price metrics.

    Ordered 10-step onboarding checklist: 1. Interview data producers, inspect ETL/dbt lineage, and snapshot a fixed date range for reproducible auditing. 2. Inventory tables, column types (TIMESTAMPTZ, NUMERIC), row counts, date ranges, and refresh schedules. 3. Write down each table's grain and prove primary keys, bidirectional orphan rates, and relationship cardinalities. 4. Profile column distributions, sentinel values, and systematic missingness across platforms and payment models. 5. Standardize timestamps (UTC vs. hotel-local dates), locales, currency codes, minor units, and FX date rules. 6. Deduplicate exact batch reloads, versioned key updates, and sub-5-second client retry events. 7. Pre-aggregate child tables to the target grain before joining, then assert row counts and reconcile revenue sums. 8. Validate funnel event ordering, filter future-stamped clock skew, measure arrival lag, and set watermarks. 9. Lock written metric definitions (attribution, maturity window, net vs. gross, FX) and reconcile against Finance totals. 10. Deploy automated SQL quality checks with clear severities and sign producer data contracts.

Intuition & how it works

Onboarding an unfamiliar dataset is like inspecting an older house before renovating: you verify the blueprints, test which pipe feeds which faucet, and check the electric meter before tearing down walls or paying the first utility bill. In data science, every table has a grain—a one-sentence rule describing what a single row represents, such as one user search or one booking version—and every metric depends on that grain holding true.

The naive approach is to trust column names at face value, join searches, impressions, clicks, and bookings in one big SQL query, and compute AVG(price) or COUNT(bookings) / COUNT(searches) up through yesterday. That fails silently because SQL happily executes queries that mix Japanese yen with US dollars, multiply revenue across many-to-many joins, and count yesterday's searches as non-converting simply because travelers have not finished booking yet. None of those bugs raise a syntax error; they just produce confident, wrong numbers.

Trace a tiny concrete example of a single search s1 made on March 1 that showed 20 hotel impressions, received 3 clicks, and led to 1 booking on March 5 for 18,000 JPY ($120 USD at 150 JPY/USD):

  1. Key & currency check: Verifying booking_id uniqueness removes a duplicate batch reload row, and converting 18,000 JPY to $120 USD prevents the booking from looking like $18,000.
  2. Pre-aggregated join: Reducing impressions (20), clicks (3), and bookings (1, $120) to one summary row per search_id before joining keeps revenue at $120 instead of fanning out into 20 * 3 * 1 = 60 rows totaling $7,200.
  3. Watermark & maturity check: A watermark—the event-time cutoff behind which almost all delayed data has arrived—holds the March 1 cohort open until March 9 (end of the 7-day booking window) plus 48 hours for late mobile uploads (March 11), so the March 5 booking is properly credited (1 / 1 = 100% conversion instead of 0% if read on March 3).

Key points

  • Prove the grain and keys before writing metric SQL. Verify that candidate primary keys (columns meant to uniquely identify each row) have zero NULLs and zero duplicates, and measure orphan rows (child records whose foreign key points to a missing parent record) in both directions.
  • Profile for silent value traps, not just NULLs. Check for sentinel values (fake placeholders like -1 or '1970-01-01' used instead of NULL), systematic missingness (such as NULL hotel cost on pay-at-property stays), UTC timestamps vs. hotel-local check-in dates, and mixed currencies or minor units (prices stored in smallest sub-units like cents, where USD has 2 decimals, JPY has 0, and KWD has 3).
  • Eliminate fan-out by pre-aggregating child tables. Join inflation (fan-out) happens when joining two one-to-many tables to the same parent multiplies their rows together; always aggregate each child table to the target grain first and reconcile post-join sums back to the raw source table.
  • Separate event time from ingestion time with watermarks. Because mobile apps upload events hours or days late, measure arrival lag (ingest_ts - event_ts), quarantine future-stamped rows from broken client clocks, and mark a 7-day conversion cohort final only once the watermark passes the cohort's conversion window.
  • Write exact metric and financial definitions. Credit at most one search per booking, and distinguish GMV / Gross Merchandise Value (total customer-facing booking value, $900 in the worked example) from gross margin (price - wholesale_cost, $135) and contribution margin (gross margin minus variable payment and marketing costs, $72.50).
  • Codify checks as automated tests and data contracts. A data contract is a formal, versioned schema and quality SLA enforced in the data producer's deployment pipeline so breaking changes fail upstream before corrupting analytics tables.
  • Audit travel-specific domain traps explicitly. Test for multi-room itineraries (1 row with rooms = 3 vs. 3 rows), in-place stay modifications, 48-hour cancel-and-rebook pairs, booking-date vs. stay-date FX rates, adult/child occupancy defaults, and scraper bots.

Common mistakes

  • Assuming booking_id is unique without checking. Modification logs and at-least-once streaming pipelines routinely create 0.1%–1% duplicate keys that silently inflate revenue.
  • Joining searches, impressions, clicks, and bookings in one flat SELECT and summing money. Multiplying 20 impressions by 3 clicks inflates a single $500 booking into $30,000.
  • Averaging prices across currencies or dividing every minor-unit column by 100. One 18,000 JPY row shifts a 100-booking $150 USD mean to $328.50.
  • Filtering boolean flags with WHERE NOT is_test when is_test can be NULL, or removing test rows from bookings while leaving test searches in the searches denominator.
  • Reporting recent cohorts inside an open attribution window as final, creating an artificial conversion cliff over the most recent 7–9 days of every chart.
  • Computing watermark timestamps without filtering future-stamped client clocks, letting one device clock set to year 2029 close every window prematurely.

Follow-up questions

  • After cleaning the reservations table, your monthly totals still differ from Finance's ledger by 4%. How would you track down the discrepancy? Pick one closed historical month and align definitions one rule at a time: match date basis (booking date vs. check-in date vs. checkout date), currency FX table (booking-date rate vs. stay-date rate), taxes and resort fees, gross vs. net of cancellations, and brand/channel scope. Log how much of the 4% gap disappears after each single step. Whatever remains can be row-diffed by booking_id between the two pipelines, which typically surfaces pay-at-property timing differences or late month-end adjustments.
  • What is your strategy when an event log lacks any trustworthy unique event identifier? Construct a deterministic surrogate key—a synthetic identifier built by hashing the columns that define a unique real-world occurrence, such as SHA256(user_id || hotel_id || event_type || event_ts). Measure the exact collision rate, inspect collided rows to distinguish batch reloads from rapid double-clicks, and apply a documented tie-breaker (ORDER BY ingest_ts DESC). Simultaneously add a true producer-generated UUID to the team's next data contract version.
  • How would you organize ongoing data-quality alerts post-onboarding so on-call engineers do not suffer alert fatigue? Split checks into two severity tiers: hard invariant failures (duplicate primary keys, NULL prices, broken grain) halt the downstream transformation before bad numbers publish, while soft statistical shifts (orphan rate creeping from 1.5% to 2.5%, or daily volume dropping 25% vs. the trailing 4-week same-weekday average) page the on-call owner without blocking loads. Store every check's daily violation count in a monitoring table so gradual drift is visible long before a threshold breaks.

Follow-up questions

Similar questions

More Expedia interview questions

All 12 Expedia questions →