Skip to main content

Question bank

Try each question before you open the hints or the solution.

Showing 100 of 100 questions

A build-vs-buy decision you drove

Behavioralmediumsenior · lead12 min
#build-vs-buy#tradeoffs#platform-strategy

"Tell me about a time you had to decide whether to build a data tool or capability in-house or buy it (or adopt an open-source or managed option). How did you decide, who did you have to convince, and how did it turn out?"

Hint 1

The interviewer wants your decision process, not the product name. What criteria did you compare, and what would have changed your mind?

Hint 2

Total cost includes people. How many engineers would have maintained the built version, and for how long?

Show solution

Structure: the problem and why it mattered now → the options (build, buy, open source, managed) → the criteria and how each option scored → the decision and who had to agree → what happened, including what you'd revisit.

Strong signals:

  • Total cost of ownership, not license price: engineer time to build and run it, on-call, upgrades, security reviews, plus the license or cloud bill. "Building it is free" is the classic mistake.
  • Core vs context: build what differentiates the business or where nothing fits; buy commodity capabilities (ingestion connectors, observability, BI) unless scale or cost makes them unworkable.
  • Exit cost and lock-in: open formats, data portability, what migrating away would cost in three years.
  • A time-boxed proof of concept with success criteria agreed before it started, on your own data.
  • Bringing security, finance and the teams who'd use it into the decision early.
  • Honest outcome: what turned out more expensive or harder than expected, and what triggers a re-evaluation (price change, scale).

Example spine:

"Our team maintained 45 custom ingestion scripts that broke about twice a week. I compared building a framework (two engineers for six months, then ongoing), a managed connector service, and an open-source tool we'd host. We ran a two-week trial of the managed service and the open-source tool on our ten worst sources. Managed cost about a third of the engineer time we spent on maintenance, so we bought it for standard SaaS sources and kept custom code for two internal systems no vendor supported. Breakages dropped from eight a month to one. The bill grew faster than forecast with row volume, so we added usage alerts and renegotiated at renewal."

Lead level: show how the decision fit a platform strategy (fewer, well-supported tools), and how you handled engineers who wanted to build.

What a strong answer covers

  • Compares options on explicit criteria including total cost of ownership (people, not just licenses) (weight 3)
  • Considers core vs commodity, lock-in and exit cost (weight 2)
  • De-risks with a time-boxed proof of concept and involves stakeholders (security, finance, users) (weight 2)
  • Shares a measurable outcome and what they would revisit (weight 2)

Follow-ups

  • The vendor raises prices 60% at renewal. What do you do?

    Know your options before the renewal: usage data, the cost of the alternatives and of migrating. Negotiate with that leverage (volume commitments, multi-year terms), reduce usage that isn't worth it, and keep a credible exit plan, which is why open formats and limited lock-in matter at decision time.

  • An engineer on your team strongly wants to build it instead. How do you handle that?

    Take the argument seriously: ask for the build case on the same criteria, including who runs it in two years. If the decision is still to buy, explain the reasoning openly and give them meaningful work elsewhere, ideally on the part that really does need building.

Pitch a 12-month data platform strategy

Behavioralhardlead15 min
#platform-strategy#finops#stakeholders

"You've just joined as the data platform lead. The warehouse bill grew 70% last year, three teams run their own pipelines with different tools, and the CFO doesn't trust the revenue numbers. The CTO asks for your 12-month data platform strategy in two weeks. How do you build it, what's in it, and how do you get buy-in?"

Hint 1

What would you do in the first two weeks before writing anything?

Hint 2

A strategy is choices. What will you explicitly not do this year?

Hint 3

How will the CTO know in six months whether it's working?

Show solution

1. Listen and measure first (the two weeks). Interview the CTO, CFO, the three teams and key consumers. Pull the facts: cost by team and workload, incident history, the revenue discrepancy and where it comes from, tool inventory, on-call load. A strategy without numbers reads as opinion.

2. Frame the problems by business impact. For example: (1) revenue numbers aren't trusted, so decisions are slow and risky; (2) cost is growing faster than usage; (3) fragmented tooling means duplicated work and inconsistent quality.

3. Make a few clear bets, in sequence.

  • Quarter 1, trust: one certified revenue model with an owner, reconciliation to the ledger, tests, and a public definition. Visible, fast, and it fixes the CFO's problem first.
  • Cost (FinOps): attribute spend to teams and workloads, fix the top offenders (full refreshes, oversized compute, unused tables), set budgets and alerts. Aim for a concrete saving, such as 25% of run-rate, and report it monthly.
  • Paved road: one supported way to build pipelines (ingestion, orchestration, transformation, quality checks, CI). Migrate teams onto it gradually, starting with the team that has the most pain. Don't force a big-bang migration.
  • Explicitly not this year: for example, real-time streaming for everyone, or a new BI tool. Saying no is part of the strategy.

4. Define success metrics and checkpoints. Revenue reconciliation within tolerance, number of data incidents found by the data team first, cost per query or per team, share of pipelines on the paved road, delivery time for new data requests. Review quarterly and adjust.

5. Get buy-in. Pre-wire the proposal with each stakeholder before the big meeting, show how it solves their problem, be honest about costs (people, migration effort), and ask for specific decisions (headcount, a tool deprecation, a mandate for the paved road).

What a strong answer covers

  • Gathers facts and stakeholder input before proposing (cost, incidents, inventory) (weight 2)
  • Prioritizes by business impact and sequences the work (trust first, quick visible win) (weight 3)
  • Includes a concrete cost (FinOps) plan with attribution and targets (weight 2)
  • States what they will not do, and defines measurable success criteria with checkpoints (weight 2)
  • Plans buy-in: pre-wiring, tailoring to each stakeholder, explicit asks (weight 1)

Follow-ups

  • One of the three teams refuses to move to the paved road. What now?

    Find out what the paved road lacks for them and whether it's a real gap or a preference. Fix real gaps, offer migration help, and agree a timeline with their leadership. If they stay off it, they own the full cost of their own stack (on-call, compliance, cost) so the trade-off is visible.

  • Halfway through the year, the company cuts your headcount plan by half. How do you revise the strategy?

    Re-prioritize, don't spread thinner: keep the highest-impact bet (usually trust in key numbers), slow or stop the rest, and tell stakeholders explicitly what moves out and why. Look for leverage: buying instead of building, automating toil, deprecating low-value pipelines.

Growing and structuring a data team

Behavioralhardlead15 min
#hiring#team-design#leadership

"You have budget to grow the data team from 4 to 12 people over the next year. The business wants faster answers, the platform is fragile, and two product teams want dedicated data support. How would you structure the team, who would you hire first, and how would you run hiring?"

Hint 1

Start from the problems, not the org chart. Which problem hurts most if you leave it for six months?

Hint 2

What are the trade-offs of a central team, embedded engineers and a hybrid?

Hint 3

How do you keep hiring quality consistent when several people interview?

Show solution

1. Diagnose before designing. Name the top problems with evidence: incidents per month, request backlog and wait time, who is waiting on what. A fragile platform slows everything else, so it usually gets the first hires.

2. Choose a structure and say why.

Model Strength Risk
Central team Shared standards, efficient platform work Becomes a ticket queue; far from the business
Embedded in product teams Close to decisions, fast Duplicated tooling, inconsistent quality, isolated engineers
Hybrid (platform team + embedded or domain-aligned engineers) Platform consistency with business closeness Needs clear ownership boundaries and a shared practice

A common answer at this size: a small platform team (ingestion, orchestration, warehouse, quality, cost) and analytics engineers aligned to domains, who sit with the product teams but share standards, code review and a weekly practice meeting.

3. Sequence the hiring. For example: first a senior platform engineer to stabilize (on-call, tests, CI), then one analytics engineer per demanding product team, then more as backlog data justifies it. Hire seniors early so they can set standards and mentor juniors later. Plan for a manager or tech lead once the team passes about 6–8 people.

4. Run hiring well. Write a role scorecard (skills, level expectations) before posting. Use a structured loop: each interviewer covers different competencies with prepared questions and a rubric, writes feedback before discussing, and the debrief decides against the scorecard. Use a realistic exercise (a SQL or modeling task, a design discussion) rather than puzzles. Track time-to-hire, offer acceptance and how hires perform after six months.

5. Show you'd measure the result: incidents, request turnaround, stakeholder satisfaction, and whether the platform team's work is reducing toil.

What a strong answer covers

  • Starts from the problems with evidence and prioritizes the platform stability vs demand trade-off (weight 2)
  • Compares central, embedded and hybrid models and justifies a choice (weight 3)
  • Sequences hires (seniors first, when a manager/lead is needed) (weight 2)
  • Describes a structured, fair hiring process (scorecard, rubric-based loop, independent feedback) (weight 2)
  • Defines how success would be measured (weight 1)

Follow-ups

  • Six months in, the embedded analytics engineers are building three different versions of the same customer table. What do you change?

    Make shared models a platform responsibility with one owner, agree on naming and domain ownership, and add the duplicates to a deprecation plan. Strengthen the shared practice: cross-team code review, a model catalog, and a rule that core entities are reused, not rebuilt.

  • How do you decide between hiring a senior engineer and two juniors?

    Look at what the team lacks most: if nobody can set standards, review designs or mentor, juniors will struggle and the senior comes first. Once that capacity exists, juniors add throughput and growth. Also consider the work: ambiguous platform problems need experience; well-defined modeling work suits juniors with support.

Getting productive in an unfamiliar domain or codebase

Behavioraleasyjunior · mid8 min
#learning#onboarding#communication

"Tell me about a time you had to get productive quickly in a domain, tool or codebase you didn't know, for example a new business area, an unfamiliar orchestrator or a legacy pipeline nobody understood."

Hint 1

Interviewers want your method for learning, not that you're a fast learner.

Show solution

Structure: what was new → why speed mattered → the steps you took → the first useful thing you delivered → what you'd reuse next time.

Strong signals:

  • A method, with specifics. For example: traced one important number end to end (dashboard → table → job → source); drew the lineage; read the last 20 incidents or tickets; ran the pipeline locally on one day of data.
  • Asking good questions early, prepared ("I've read X and think Y; is that right?"), and writing the answers down.
  • An early, small win that proved understanding, like a fixed alert, a documented runbook or a test on a flaky table.
  • Leaving it better: the onboarding doc or lineage diagram you made is now used by the next person.

Avoid: "I just read all the docs"; a story where you never asked anyone anything; no concrete outcome.

What a strong answer covers

  • Describes a concrete learning method (e.g. trace one metric end to end) (weight 2)
  • Asks prepared questions and records answers (weight 1)
  • Delivers an early, specific win (weight 2)
  • Leaves documentation or tooling that helps the next person (weight 1)

Follow-ups

  • What's the first thing you'd do in your first week here?

    Map the system before changing it: read the runbooks and the main DAGs, trace one important dataset from source to dashboard, and ask its consumers what they rely on. Then ship a small, low-risk change (a test, a doc fix) to learn the deploy path and get early feedback.

  • How do you know when you understand a system well enough to change it?

    When you can predict what a change will affect: name the upstream inputs and downstream consumers, explain why the current design looks the way it does, and say how you'd notice and roll back if you were wrong. If you can't do that yet, you need more context or a reviewer who has it.

Two teams disagree on what a metric means

Behavioralmediummid · senior · lead10 min
#stakeholders#metrics#influence

"Tell me about a time two stakeholders or teams disagreed about a number, for example two dashboards showing different 'active users' or 'revenue'. What did you do?"

Hint 1

Explain how you found out why the numbers differed before anyone argued about which was right.

Hint 2

The win is usually a shared definition with an owner, not you picking a side.

Show solution

Structure: the conflict and why it mattered → how you found the actual difference → how you got to a decision → how you made it stick.

Strong signals:

  • Diagnose first. Lay the two definitions side by side (filters, time zone, dedup, grain, late data) and quantify how much each difference explains ("marketing excludes trial users: 70% of the gap; time zone: 25%").
  • Separate facts from decisions. The data team explains the options and their consequences, and the business owner of the metric decides. If nobody owns it, getting an owner named is the outcome.
  • Make it durable. One definition in code (a semantic layer or dbt metric), documented, with the old dashboards migrated or clearly labeled.
  • Keep relationships intact. Nobody was publicly "wrong".

Example spine:

"Sales and finance reported Q2 revenue 3% apart. I reconciled the two queries line by line: finance recognized annual contracts monthly, sales counted bookings, and sales also included a test account. I presented both as valid for different questions, and the CFO decided 'revenue' meant recognized revenue and sales would show 'bookings' under that name. I implemented both in our metrics layer and added a dashboard banner during the transition. The weekly 'which number is right' thread stopped."

What a strong answer covers

  • Diagnoses and quantifies the sources of the difference before debating (weight 3)
  • Gets a decision from the right owner instead of deciding unilaterally (weight 2)
  • Makes the definition durable (single definition in code, documentation, migration) (weight 2)
  • Maintains trust and relationships (weight 1)

Follow-ups

  • What if the business owner chose the definition you thought was wrong?

    Disagree and commit: make sure your concerns and the trade-off are written down, then implement the owner's definition properly. Name it precisely, document the edge cases it excludes, and revisit it with data if the risk you flagged shows up.

  • How do you stop new conflicting definitions from appearing?

    Define metrics once, in a governed place (a semantic layer or a single dbt model) with a named owner and documentation. Make dashboards read from that definition instead of recomputing it, and review new metric requests against the existing catalog.

Walk me through a migration you led

Behavioralmediummid · senior · lead12 min
#migrations#planning#stakeholders

"Tell me about a significant migration you led or played a key part in, for example on-prem to cloud, one orchestrator or warehouse to another, or batch to streaming. How did you plan it, how did you know it worked, and what went wrong?"

Hint 1

Migrations are judged on how you de-risked them, so explain parallel runs, validation and rollback.

Hint 2

Have one "what went wrong" moment ready; a migration story with no problems isn't believable.

Show solution

Structure: why migrate (business reason, with a number) → scope and constraints → plan (phases, order, what moved first and why) → how you proved parity → cutover and rollback → what went wrong and how you handled it → result.

Strong signals:

  • A real reason ("license renewal in 9 months", "nightly batch missed the 7am SLA 6 times a month"), not "cloud is modern".
  • An inventory of what existed (jobs, tables, consumers) and a decision on what not to migrate.
  • Parallel runs with automated comparison (row counts, checksums, key metrics within tolerance) before cutover, and a documented rollback.
  • Moving consumers in waves, with the highest-risk or noisiest consumer early, not last.
  • A quantified result: cost, runtime, incidents, freshness.

Example spine:

"We moved 340 Teradata jobs to Snowflake and dbt before the contract renewal. I built a comparison harness that ran every migrated model next to the legacy job for two weeks and flagged differences over 0.1%. That caught a timestamp-timezone difference affecting 12 models before any consumer saw it. We cut over in four waves by business domain. Nightly runtime went from 6 hours to 70 minutes, and we decommissioned the old system a month early."

Lead level: add how you staffed it, how you kept feature work going during it, and how you got other teams to move their consumers.

What a strong answer covers

  • States a concrete business reason and measurable goal (weight 2)
  • Describes de-risking: inventory, parallel runs with automated parity checks, rollback (weight 3)
  • Explains sequencing and stakeholder/consumer coordination (weight 2)
  • Shares a real problem and how it was handled (weight 2)
  • Quantifies the outcome (weight 1)

Follow-ups

  • What did you decide not to migrate, and how did you get agreement on that?

    Name what you left out, such as unused reports, dead jobs or low-value history, and the evidence for leaving it (query logs, last-access dates). Agree on it explicitly with the owners, with a date after which it's switched off and a way to restore it if someone shouts.

  • How did you handle a consumer who refused to move?

    Find out why first: missing features, no time, or distrust of the new numbers. Remove the blocker (pair with them, add the missing piece, show the reconciliation), and agree a deadline with their manager, so the legacy path doesn't stay alive for one team forever.

Tell me about a data incident you owned

Behavioralmediumjunior · mid · senior · lead10 min
#incidents#ownership

"Tell me about a time a pipeline you owned broke, or produced wrong data, in production. What happened, what did you do, and what changed afterwards?"

Hint 1

Pick an incident with real impact, like a wrong number someone acted on, or an SLA missed, not a typo caught in review.

Hint 2

Interviewers listen for what you changed so it can't happen again, not only how you fixed it that night.

Show solution

Structure: situation (one or two sentences) → impact (who was affected, how badly, with a number) → what you did, in order → root cause → what you changed → what you learned.

A strong answer sounds like this:

"Our daily revenue table double-counted refunds for three days after a source team added a new refund status. Finance had already sent a board pre-read with revenue 4% too high. I noticed it when a dashboard check flagged revenue above the 30-day range. I paused the downstream publish, posted in the finance channel with what we knew and when we'd know more, and traced it to our CASE statement that treated any unknown status as a sale. I fixed the mapping, backfilled the three days, and confirmed totals against the payment processor. Then I made two changes: unknown statuses now fail the load instead of passing through, and we added an accepted-values test on the status column with an alert to the source team. We haven't had a silent status change since."

What separates levels: junior candidates show calm debugging and honesty. Mid candidates add communication and a permanent fix. Senior and lead candidates show the systemic change (contracts, tests, on-call process, a blameless postmortem that changed how other teams work too).

Avoid: blaming another team; incidents with no impact; ending at "and I fixed it".

What a strong answer covers

  • Quantifies impact (who was affected, how much, for how long) (weight 2)
  • Clear personal actions in sequence, including communicating to stakeholders early (weight 2)
  • Identifies the root cause, not just the symptom (weight 2)
  • Describes a lasting prevention (test, contract, alert, process), not only the fix (weight 3)
  • Owns their part without blaming others (weight 1)

Follow-ups

  • What would you do differently in the first 30 minutes now?

    A strong answer is concrete: acknowledge and tell stakeholders sooner, stop the bad data from spreading (pause downstream jobs or flag the dashboard) before root-causing, and write down a timeline as you go. Show what you learned, not just what you'd repeat.

  • How did you decide whether to stop the dashboards or let them show possibly-wrong data?

    Weigh the cost of a wrong decision against the cost of no data. For decisions made on the numbers (finance, pricing), mark the dashboard stale or hide it. For low-stakes monitoring, keep it up with a clear warning banner. Either way, tell the users which data is affected.

You were asked to ship data faster than you could make it reliable

Behavioralmediumjunior · mid · senior · lead10 min
#tradeoffs#communication#prioritization

"Tell me about a time you were under pressure to deliver a dataset or pipeline quickly, and doing it properly would take longer. How did you handle it?"

Hint 1

Say what you shipped, what you deliberately didn't, and how you made that visible.

Show solution

Structure: the ask and the deadline → what "properly" would have required → the options you laid out → what you chose and why → how you contained the risk → what happened next.

Strong signals:

  • You quantified the trade-off ("a manual extract by Friday that's right for the launch view, or an automated, tested pipeline in 3 weeks").
  • You shipped a scoped version with its limits made visible: labeled "preliminary", known gaps listed, an owner, an expiry date.
  • You didn't quietly take on debt. The follow-up work was scheduled, and you either did it or explicitly re-negotiated it.
  • At senior and lead level: you changed something so the next request doesn't hit the same wall, such as a reusable ingestion template or an intake process with realistic lead times.

Avoid: "I worked all weekend" as the whole story (heroics aren't a strategy); "I refused" without offering options; a shortcut that later caused an incident you don't mention.

What a strong answer covers

  • Lays out options with explicit trade-offs and time estimates (weight 2)
  • Ships a scoped version with limits clearly communicated (weight 2)
  • Follows through on the deferred work (or re-negotiates it openly) (weight 2)
  • Improves the process so the situation recurs less (senior+) (weight 1)

Follow-ups

  • What would have made you say no?

    Say no (or 'not like this') when the shortcut risks real harm: wrong numbers in a regulatory or financial report, exposing PII, or breaking other consumers. Otherwise prefer 'yes, with these caveats', stated in writing, so the risk is a shared decision.

  • How did you make sure the "temporary" dataset didn't become permanent?

    Give it an owner, an expiry date and a ticket for the proper version, and label it as provisional where people use it. Then actually schedule the follow-up work and check usage, so it gets migrated or deleted instead of quietly becoming a dependency.

Joint bank accounts and the many-to-many problem

Data modelinghardsenior25 min
#bridge-tables#many-to-many#dimensional-modeling

A bank's fct_account_balance_daily has one row per account per day. An account can have several owners (joint accounts), and a customer can own several accounts.

The business asks two questions:

  1. Total balances by customer segment
  2. Number of customers with more than 100k in total balances

Design the model so both answers are right, and show what goes wrong with a naive join.

Hint 1

If an account with two owners joins to both, what happens to its balance in a SUM?

Show solution

The naive join double counts. Joining the balance fact to customers through ownership gives one row per owner, so a joint account's 50k shows up as 100k in "total balances by segment".

Use a bridge table: bridge_account_owner(account_key, customer_key, allocation_factor, valid_from, valid_to).

  • allocation_factor splits each account across its owners so the factors per account sum to 1 (0.5 / 0.5 for two equal owners, or a legal share). For totals like balances by segment, multiply: SUM(balance * allocation_factor). The grand total then equals the real bank total.
  • For "how much does this customer have access to" (question 2), you intentionally don't allocate: each owner has access to the full balance. Use SUM(balance) per customer, and never add those numbers up across customers.
  • valid_from / valid_to make the bridge SCD2, because owners are added and removed. Join on the balance date.

Say this in the interview: many-to-many has no single right total. The model must make the two meanings explicit (allocated vs full), name them differently in the semantic layer, and test that allocated totals reconcile to the account-level total.

A group key variant (owner_group_key on the fact pointing to a group of customers) also works and keeps the fact narrow when the same owner sets repeat often.

What a strong answer covers

  • Shows the double counting from a naive many-to-many join (weight 2)
  • Introduces a bridge table with an allocation/weighting factor summing to 1 (weight 3)
  • Distinguishes allocated totals from per-customer full-access sums (weight 2)
  • Makes the bridge time-aware (owners change) and adds a reconciliation test (weight 1)

Follow-ups

  • How would you expose both measures in a BI semantic layer so users can't add the wrong one?

    Define two separate, clearly named measures in the semantic layer: the account-level total (which sums each account once) and the allocated per-holder amount (weighted by the bridge's allocation factor). Hide the raw columns and document which to use when, so users can't add the double-counted one.

  • What other domains have this pattern (hint, patients and diagnoses, orders and promotions)?

    Any many-to-many between a fact and a dimension: patients and diagnoses, orders and promotions, articles and authors, products and categories, students and classes. Each needs a bridge table and a decision on whether to allocate or count once.

Model clickstream events for product analytics

Data modelingmediummid · senior30 min
#event-modeling#grain#late-arriving-data

A mobile and web app sends events (screen_view, button_click, add_to_cart, purchase, …) with a few common fields and a JSON properties blob that differs per event type. About 300 million events a day. Events can arrive up to 3 days late from offline phones.

Product wants daily active users, funnels, session metrics and feature adoption. Design the warehouse model from raw events to the tables analysts use.

Hint 1

Separate "store everything faithfully" from "make the common questions fast".

Hint 2

Which timestamp does a late event belong to, and which partitions must be rebuilt?

Show solution

Layers

  1. Raw events (raw_events): append-only, one row per event as received, with event_id, event_name, user_id, anonymous_id, device, event_ts (client), received_at (server), and the untouched properties JSON. Partition by received date, which makes loads idempotent and cheap to replay.
  2. Clean events (fct_events): one row per unique event_id (dedup retries), with typed common columns, both timestamps normalized to UTC, event_date derived from event_ts, and identity stitched (anonymous_id → user_id once known). Partition or cluster by event_date.
  3. Per-event-type tables for the hot ones (fct_purchases, fct_add_to_cart): properties exploded into typed columns, so analysts don't parse JSON.
  4. Derived facts: fct_sessions (one row per session: start, end, events, entry and exit screen) and agg_user_daily (one row per user per day: events, sessions, purchases). DAU and retention come from the latter.

Late data: report by event_ts date (when it happened), but load by received_at. Each daily run re-processes the last 3 event dates (the late window) for clean, session and daily tables. Anything later than that goes into a monthly correction job. Say which policy, and that numbers for the last 3 days are provisional.

Schema evolution: new event types and properties land in raw automatically. Promote a property to a typed column only when it's used. A registry or tracking plan (event name, owner, property types) keeps producers honest, and a data contract test fails the load on type changes.

Identity: DAU on user_id misses logged-out usage; on anonymous_id it double-counts across devices. Pick one definition, document it, and keep the stitching table so both are possible.

What a strong answer covers

  • Keeps an append-only raw layer with the original payload, separate from cleaned tables (weight 2)
  • States grain for each table (event, session, user-day) and dedups on event_id (weight 2)
  • Distinguishes event time vs received time and defines a late-data reprocessing window (weight 3)
  • Handles the JSON properties: typed tables for hot events, raw kept for the rest (weight 1)
  • Addresses identity (anonymous vs logged-in) and its effect on DAU (weight 1)

Follow-ups

  • A producer starts sending price as a string instead of a number. What catches it, and where?

    A schema contract at ingestion: validate events against a registry schema (for example JSON Schema or Avro) and route failures to a quarantine table with an alert to the producer. A type test in the warehouse is a second line of defense, but by then the bad data has landed.

  • Storage costs are doubling every quarter. Where would you cut first?

    Look at what is actually queried. Shorten the retention of raw events, drop or move unused high-volume properties, compress and partition by date, and tier old data to cheaper storage. Pre-aggregated tables can replace scans of the raw table for common dashboards.

Customer address history for finance and marketing

Data modelingmediummid · senior25 min
#scd-type-2#scd-type-6#dimensional-modeling

Customers change their shipping address. Two teams use the same dim_customer:

  • Finance reports revenue by the region the customer lived in when they ordered.
  • Marketing targets customers by their current region.

The source system only keeps the current address and has an updated_at column.

Which slowly changing dimension type(s) do you use, and what does the table look like? How do you load it, and what goes wrong if a change arrives late?

Hint 1

The two teams need different answers from the same history. Can one table serve both without a self-join?

Show solution

SCD Type 2 for history, plus a Type 1 "current" column. That combination is often called Type 6.

dim_customer: customer_key (surrogate), customer_id (natural), region, address, current_region, valid_from, valid_to, is_current.

  • Finance: the fact table stores the customer_key that was valid at order time, so fact_order → dim_customer.region gives the region then.
  • Marketing: current_region is overwritten on every version of the customer, so any row (or is_current = true) gives today's region without a self-join.

Loading. Because the source keeps only the current state, capture it with daily snapshots or CDC. Compare it to the current dimension row on the tracked columns (a hash of region + address is common). On a change: close the old row (valid_to = change time, is_current = false), insert a new row, and update current_region on all rows for that customer. Use MERGE in one transaction.

Late-arriving changes. If a change dated last week arrives today, orders loaded in between point to the wrong version. Either accept it (document that history is "as known at load time"), or insert the version at the right point in the timeline and re-key the affected fact rows. The second option is correct but expensive. Say which you'd pick and why.

Pitfalls: don't track noisy columns (like last_login) as Type 2, or the dimension explodes. Use a far-future valid_to (e.g. 9999-12-31) rather than NULL, so range joins stay simple.

What a strong answer covers

  • Picks Type 2 for finance history and explains why Type 1 alone loses it (weight 2)
  • Serves the current region without a self-join (Type 6 / current column, or is_current view) (weight 2)
  • Fact rows carry the surrogate key valid at order time (weight 2)
  • Explains the load: detect change, close old row, insert new row, ideally in one MERGE (weight 1)
  • Addresses late-arriving changes and the re-keying trade-off (weight 2)

Follow-ups

  • How would you build this in dbt? What does a snapshot give you, and what doesn't it?

    A dbt snapshot (timestamp or check strategy) turns a mutable source into SCD2 with dbt_valid_from / dbt_valid_to. It only captures what it sees at each run, so changes between runs are lost and history before the first run doesn't exist. It also won't reconstruct backdated changes; you still model the final dimension on top of it.

  • A GDPR delete request comes in for a customer with 12 versions. What do you do?

    Delete or anonymize the personal fields in every version (and in snapshots, staging and backups per your retention policy), while keeping the surrogate keys so facts still join. Log the request, and make sure a later rebuild from raw data doesn't bring the data back.

Further reading

When would you choose Data Vault over a Kimball star schema?

Data modelinghardsenior · lead30 min
#data-vault#dimensional-modeling#architecture

A bank is consolidating customer and account data from 6 source systems (core banking, cards, CRM, two acquired companies, a loans platform). Sources change schema often, auditors need full history of what each system said and when, and business definitions of "customer" are still being argued about.

The head of data asks: "Data Vault or Kimball?" Give a recommendation, sketch the core model for customers and accounts, and explain the trade-offs.

Hint 1

These two aren't exclusive. What does each layer optimize for?

Show solution

Recommendation: Data Vault for the integration layer, Kimball stars on top for consumption. Here the hard problems are integration, auditability and change, which are what Data Vault is designed for. Analysts still need stars.

Core Data Vault model

  • Hubs hold business keys only: hub_customer (customer business key + hash key + load date + record source), hub_account.
  • Links hold relationships: link_customer_account (hash of both keys). Many-to-many by design, so "joint account" or "acquired bank's different ownership rules" doesn't need a remodel.
  • Satellites hold descriptive history per source: sat_customer_core, sat_customer_crm, sat_account_cards. Insert-only with load_date and a hash_diff to detect change. Each source evolves independently; a new source means new satellites, not changes to existing tables.
  • Business vault: same-as links for matching customers across systems, and point-in-time (PIT) / bridge tables for query speed.

Why it fits: insert-only plus record source gives auditors "what did system X say on date D". Adding source 7 is additive. The "customer" definition argument is postponed to the business vault and marts, instead of blocking ingestion.

Costs, said honestly: many more tables and joins; needs automation (dbt packages or generators) to be maintainable; unusable directly by analysts; easy to over-engineer for a small team. If the company had 1–2 stable sources and no audit requirement, a straight Kimball model (staging → dims and facts) would be cheaper and faster.

Consumption: dim_customer (SCD2, built from PIT tables), dim_account, and fct_account_balance_daily (periodic snapshot), all in a star schema for BI.

What a strong answer covers

  • Gives a clear recommendation tied to the drivers (many sources, audit, change) (weight 2)
  • Correctly describes hubs, links, satellites (keys vs relationships vs history) (weight 3)
  • Keeps Kimball stars as the consumption layer (weight 2)
  • States real costs (table count, automation need, team skill) and when not to use it (weight 2)

Follow-ups

  • How do you handle a customer that appears in three systems with different IDs?

    Each system's ID lands in its own hub or as separate business keys, and a same-as link records which IDs belong to the same customer, produced by matching rules or a master data system. Raw data stays unchanged, and the match is applied in the business vault.

  • What do PIT tables solve, and when do you need them?

    Point-in-time tables precompute, for each hub key and snapshot date, which satellite row was current. You need them when queries join many satellites as of a date, which is otherwise slow and complex.

Inventory levels and semi-additive measures

Data modelingmediummid · senior25 min
#periodic-snapshot#semi-additive-measures#fact-types

A retailer with 400 stores and 50,000 products wants:

  • Stock on hand by store, product and day
  • Average stock last month, and days of stock remaining
  • Shrinkage (stock that disappears without a sale)

The source sends every stock movement (receipts, sales, transfers, adjustments). Design the facts, and explain how analysts must aggregate the stock measure.

Hint 1

Can you SUM stock on hand across days?

Show solution

Two facts.

  1. fct_inventory_movement is a transaction fact, one row per movement: date_key, store_key, product_key, movement_type (receipt, sale, transfer_in, transfer_out, adjustment), quantity (signed). Fully additive. Shrinkage is the sum of adjustment rows with a shrink reason.
  2. fct_inventory_daily is a periodic snapshot, one row per store × product × day with quantity_on_hand at end of day, plus quantity_received and quantity_sold that day. It's built by cumulatively summing movements, and daily snapshots are cheap to query for "stock on 15 March".

Semi-additive measure: quantity_on_hand adds up across stores and products (total stock today) but not across time. Summing 30 daily snapshots gives 30× the stock. Across days, use the average (average stock last month), the last value (month-end stock) or min/max. Document this in the semantic layer so the default aggregation isn't SUM.

Size: 400 × 50,000 × 365 is about 7.3 billion rows a year. Common answers: snapshot only store-product pairs with any stock or movement, keep daily granularity for 13 months and monthly snapshots beyond, and partition by date.

Days of stock remaining = current on hand ÷ average daily sales over the last N days, computed from the snapshot.

What a strong answer covers

  • Pairs a movement transaction fact with a daily periodic snapshot, grains stated (weight 3)
  • Explains stock on hand is semi-additive (not summable over time) and the right aggregations (weight 3)
  • Estimates snapshot size and proposes a way to control it (weight 1)
  • Derives shrinkage from adjustment movements (weight 1)

Follow-ups

  • A store's counts are corrected after an audit two weeks ago. How do the snapshots get fixed?

    Fix the source of truth (the movements or the corrected count), then rebuild the affected snapshot days from the correction date forward, because every later daily balance depends on it. Make the rebuild idempotent by overwriting by date partition, and record the restatement for downstream users.

  • How would you test that snapshots and movements stay in sync?

    Reconcile them: yesterday's snapshot plus today's net movements must equal today's snapshot, per product and store. Run it as a data test after every load, and fail or alert on any difference above a small tolerance.

Star schema or One Big Table for the BI layer?

Data modelingmediummid · senior20 min
#one-big-table#star-schema#performance

Your analysts use a BI tool on a columnar cloud warehouse. They complain that joining fct_orders to six dimensions is slow and confusing, and ask for "one wide table with everything".

Do you build it? When is a One Big Table (OBT) the right call, and what do you lose?

Hint 1

Columnar storage changes the cost of wide tables. What does it not change?

Show solution

Usually yes, as a serving layer on top of the star, not instead of it.

Why OBT works on columnar warehouses: queries read only the columns they touch, so 200 columns cost little until they're used. Pre-joining removes join cost and join mistakes (wrong key, fan-out) from every dashboard. BI tools and casual users find one table far easier.

What you lose

  • History semantics. Flattening an SCD2 dimension means picking one version per row, usually the one at the fact's time. "Current region" vs "region at order time" must become two explicit columns, or one meaning silently wins.
  • Rebuild cost. A change to a dimension attribute (customer renames segment) means updating every fact row, not one dimension row. With huge facts that's a big recurring bill, so OBTs are usually rebuilt incrementally or on a schedule.
  • Consistency. Each OBT duplicates logic. Two OBTs that both define region will drift unless they're built from the same conformed dimensions.
  • Grain discipline. Wide tables tempt people to add columns from a different grain (customer lifetime value on an order line), which invites double counting.

Rule of thumb: keep the star as the source of truth (staging → conformed dims and facts), and build OBTs per use case (obt_orders_for_bi) from it, with one stated grain, documented columns and an automated rebuild. Don't build one OBT for the whole company.

What a strong answer covers

  • Recommends OBT as a derived serving layer, keeping the star as source of truth (weight 2)
  • Explains why columnar storage makes wide tables cheap to query (weight 1)
  • Names the loss of SCD/history semantics when flattening (weight 2)
  • Mentions rebuild cost and logic duplication/drift (weight 2)

Follow-ups

  • How would you build the OBT incrementally when a dimension attribute changes?

    Track which dimension keys changed, then rebuild only the OBT rows that reference them (a merge on those keys), or partition the OBT and overwrite affected partitions. If attributes change often, keep them in a dimension and join at query time instead of copying them into the OBT.

  • The BI tool has a semantic layer. Does that change your answer?

    Usually yes. A semantic layer defines joins and metrics once, so a clean star schema underneath works well and avoids the duplication of an OBT. OBTs still help for tools without a semantic layer or for very hot dashboards.

Orders, partial returns and fulfillment status

Data modelingmediummid · senior30 min
#grain#fact-types#accumulating-snapshot

An online store needs:

  • Net revenue by product and day (gross sales minus returns and refunds)
  • Return rate by category, where one order can return some of its items, sometimes weeks later
  • How long orders take from placed → paid → shipped → delivered, and where they get stuck

Design the fact tables. Be explicit about grain and about how each one changes over time.

Hint 1

Net revenue and "how long did each stage take" are different fact types.

Hint 2

Is a return a negative sale, or its own fact?

Show solution

fct_order_line is a transaction fact, one row per order line at purchase. Keys: order_id, order_line_id, product_key, customer_key, order_date_key. Measures: quantity, gross_amount, discount_amount, tax_amount. Inserted once and never updated.

fct_return_line is another transaction fact, one row per returned line item event, keyed back to order_line_id, with return_date_key, returned_quantity, refund_amount and reason. Returns get their own fact because they happen on a different date, at a different grain (partial quantities), with their own attributes. Net revenue by day is SUM(gross) - SUM(refunds), each on its own date. "Return rate for products sold in March" joins returns back to the original lines.

fct_order_fulfillment is an accumulating snapshot, one row per order, updated as milestones happen: placed_at, paid_at, shipped_at, delivered_at, cancelled_at, plus lag measures (hours_to_ship, hours_to_deliver) and a current_stage. This is the one fact table that's meant to be updated in place, and it makes "stuck orders" a simple filter.

Why not one table? Putting returns as negative rows in the order fact works for net revenue but breaks the return rate and the timing analysis. Updating order rows in place for returns would destroy what was originally sold.

Conformed dimensions (dim_product, dim_customer, dim_date) are shared, so revenue, returns and fulfillment can sit on one dashboard.

What a strong answer covers

  • Order line grain for sales; separate return fact at returned-line grain (weight 3)
  • Uses an accumulating snapshot (one row per order, updated per milestone) for fulfillment timing (weight 3)
  • Explains date attribution: sales on order date, refunds on return date (weight 2)
  • Uses conformed dimensions across the facts (weight 1)

Follow-ups

  • An order ships in three parcels on different days. What happens to the accumulating snapshot's grain?

    The grain must be clear. Either move the accumulating snapshot to one row per shipment (parcel) with its own milestones, or keep one row per order line and define milestones as first and last shipped and delivered dates. Don't silently overwrite one parcel's dates with another's.

  • Finance wants revenue recognized at delivery, not at order. What changes?

    Revenue facts need a recognition date. Add a delivered date or a separate revenue-recognition fact keyed by the delivery event, and report finance revenue on that date. Returns and cancellations then reverse revenue at their own event dates.

Point-in-time correct training data for a churn model

Data modelinghardsenior · lead30 min
#point-in-time-joins#feature-engineering#ml-data

Data scientists train a churn model. Each training example is (customer_id, prediction_date, label), where the label means "churned within 30 days after prediction_date". Features include number of support tickets in the last 30 days, current plan, days since last login, and lifetime spend.

Their first model scored great offline and badly in production. Design the data model and pipeline for training data so offline matches online, and explain what probably went wrong.

Hint 1

What did the feature values look like on the prediction date, as opposed to today?

Show solution

What went wrong: label leakage through features. Features were probably computed from current tables, such as today's plan, today's lifetime spend, or tickets including ones after the prediction date. The model learned from the future. In production that information doesn't exist yet, so performance collapses.

Model:

  • Feature history, not current state. Keep features as time-stamped rows: feature_customer_daily(customer_id, as_of_date, tickets_30d, plan, days_since_login, lifetime_spend), or as event logs with event_ts from which features can be recomputed. Plan comes from an SCD2 dimension.
  • Spine: training_spine(customer_id, prediction_date, label), with the label computed from events strictly after prediction_date (within 30 days).
  • Point-in-time join: for each spine row, take each feature's latest value with as_of_date <= prediction_date. Use <, not <=, if the feature is computed at end of day and predictions run in the morning. Feature stores (Feast, Tecton, Databricks) do exactly this join; in SQL it's an as-of join.

Making offline equal online:

  • Compute features once, with the same code for training and serving, from the same definitions.
  • Log the feature vector actually served at prediction time, and train on logged features when you can.
  • Account for data latency: if tickets land in the warehouse 6 hours late, the training join must also only see tickets that would have been available at prediction time.

Also check: customers who churned can't appear after their churn date in the spine; split train and test by time, not randomly, or the test set leaks too.

What a strong answer covers

  • Identifies leakage from using current-state features (weight 3)
  • Keeps time-stamped feature history (or SCD2) instead of current snapshots (weight 2)
  • Builds a label spine and joins features as of the prediction date (strict inequality reasoned) (weight 3)
  • Addresses training/serving skew: shared definitions, logged features, data latency (weight 2)
  • Uses a time-based train/test split (weight 1)

Follow-ups

  • Backfilling two years of daily features for 50 million customers is expensive. How do you make it tractable?

    Compute features incrementally per day instead of rescanning history for every date: rolling windows can be built from daily aggregates. Partition by date, process in parallel by date range, sample customers for experiments, and store the results so a backfill runs once.

  • Where would you put data quality checks for features, and what would they test?

    Check at ingestion and before training: null rates, value ranges, row counts per day and distribution shift compared to previous days. Also check point-in-time correctness (no feature timestamp after its label date) and that offline and online values match on a sample.

Model trips for a ride-sharing app

Data modelingmediumjunior · mid · senior30 min
#grain#star-schema#dimensional-modeling

You're the first data engineer at a ride-sharing app. Analysts want to answer:

  • Trips and gross bookings by city per day and per hour
  • Driver earnings per week
  • Cancellation rate, split by who cancelled (rider or driver)
  • Average rating given by riders to drivers, and by drivers to riders

Design the warehouse model: fact table(s), grain, dimensions and key measures. Say what you'd do about drivers who move to another city.

Hint 1

State the grain of each fact table in one sentence before listing any columns.

Hint 2

Is a cancelled trip a different fact, or the same fact with a different status?

Show solution

Grain first. fact_trip: one row per trip request, whether it ends completed or cancelled. Cancellations live in the same fact (status, cancelled_by, cancelled_at), so the cancellation rate is one GROUP BY and the denominator is right.

fact_trip

  • Keys: trip_id (degenerate), rider_key, driver_key (NULL if no driver was assigned), city_key, request_date_key, request_hour
  • Timestamps: requested_at, accepted_at, completed_at, cancelled_at, stored in UTC plus the city's local date for reporting
  • Additive measures: fare_amount, surge_amount, platform_fee, driver_payout, distance_km, duration_min
  • Status: status, cancelled_by

Ratings. Each trip can have two ratings in two directions, given at different times. Model fact_trip_rating at one row per trip per direction (rated_by: rider/driver, score). Putting two nullable columns on fact_trip also works, but then the fact row has to be updated after the trip closes.

Dimensions: dim_date, dim_city (timezone, country, region), dim_rider, dim_driver.

Drivers who move: make dim_driver an SCD Type 2 on home_city (and vehicle type), with valid_from, valid_to, is_current. Look up the driver key that was valid at requested_at when loading the fact, so history reports by the driver's city at the time.

Driver earnings per week come from summing driver_payout by driver_key and week, with no separate table. Add an aggregate later only if it's slow.

What a strong answer covers

  • States the grain of fact_trip (one row per trip request) before listing columns (weight 3)
  • Keeps cancellations in the same fact so the cancellation rate has the right denominator (weight 2)
  • Handles two-directional ratings (separate fact or two columns), with the trade-off stated (weight 1)
  • Uses SCD Type 2 for driver city and picks the key valid at trip time (weight 2)
  • Measures are additive money/distance/time columns; timestamps in UTC with a local reporting date (weight 1)

Follow-ups

  • A trip is reassigned to a second driver mid-way. How does your grain cope?

    Keep the trip grain and add a trip-segment (or trip-driver) fact with one row per driver per trip, with the distance and time of each part. The trip fact stays one row per trip, so trip counts don't double, and driver earnings come from the segment fact.

  • Surge pricing rules change weekly. Where does that history live?

    In a pricing-rules dimension with SCD2 history (valid_from / valid_to), or with a rule version id stored on each trip. Also store the actual multiplier applied on the trip fact, so you never have to reconstruct it.

Further reading

Model subscriptions so finance can report MRR movements

Data modelinghardsenior · lead45 min
#periodic-snapshot#fact-types#dimensional-modeling

A B2B SaaS company sells monthly and annual plans in several currencies. Customers upgrade, downgrade, pause, cancel and come back.

Finance wants a monthly report of MRR and its movements: new, expansion, contraction, churn and reactivation. They also want to drill into which accounts caused each number.

Design the model. Cover the fact tables and their grain, how you'd compute the movements, and what makes these numbers hard to keep stable.

Hint 1

You need both what changed (events) and what is true at month end (state). Those are different fact types.

Hint 2

How does an annual plan paid upfront show up in monthly recurring revenue?

Show solution

Two fact tables, because there are two questions:

  1. fact_subscription_change is a transaction fact: one row per change to a subscription (created, plan_changed, paused, cancelled, reactivated), with mrr_before and mrr_after. It answers "what happened and why".
  2. fact_account_mrr_monthly is a periodic snapshot: one row per account per month, with the MRR at month end and the movement class. It answers "what is MRR and how did it move".

Normalizing MRR: annual price / 12, in a reporting currency, at a fixed rate policy (for example the rate at contract start, so FX moves don't show up as expansion). Exclude trials and one-time fees. Discounts reduce MRR; taxes don't count.

Classifying movements compares an account's month-end MRR with the previous month's:

  • prev = 0, curr > 0: new if it's the first time ever, otherwise reactivation
  • prev > 0, curr = 0: churn
  • curr > prev: expansion; curr < prev: contraction

This needs a row for every account that has ever been active, including months at zero (a spine of account × month). Otherwise churn has nowhere to land.

Dimensions: dim_account (segment, owner; SCD Type 2 if finance slices by segment at the time), dim_plan (price history), dim_date.

What makes it hard:

  • Backdated changes (a cancellation keyed in late) change closed months. Decide with finance: restate history, or book the change in the current month. Keep the snapshot rebuildable from the change fact either way.
  • Mid-month changes: month-end state is the usual convention. Agree it in writing.
  • Reconciliation: start MRR + movements must equal end MRR every month. Make it a data test.

What a strong answer covers

  • Separates a change/transaction fact from a monthly snapshot fact, with each grain stated (weight 3)
  • Normalizes annual plans and currencies into MRR with a stated FX policy (weight 2)
  • Classifies movements by comparing to the prior month, including zero months for churn (weight 2)
  • Addresses backdated changes and restatement policy with finance (weight 2)
  • Adds a reconciliation check: start + movements = end (weight 1)

Follow-ups

  • The CFO wants daily MRR. What does that do to your snapshot's size and how would you control it?

    A daily row per subscription grows quickly (subscriptions × days). Keep the daily grain only for a recent window, store monthly snapshots for history, or store only change events and compute daily MRR on demand from valid-from / valid-to ranges.

  • Sales says expansion is understated because seat add-ons are billed separately. How do you model add-ons?

    Model add-ons as their own subscription lines (or line items) that roll up to the customer, and classify their start and increase as expansion. MRR movements are then computed per customer across all lines, so a new add-on shows as expansion rather than a new subscription.

Read a large CSV in fixed-size batches with a generator

Pythoneasyjunior · mid15 min
#generators#files

A CSV file is too large to load into memory. Write a generator batches(f, size) that takes an open text file (with a header row) and yields lists of up to size rows, each row a dict keyed by the header.

  • The last batch may be smaller.
  • An empty file (header only) yields nothing.
  • size must be a positive integer; otherwise raise ValueError when called, before any reading.
Example tests
import io
f = io.StringIO("id,name\n1,a\n2,b\n3,c\n4,d\n5,e\n")
out = list(batches(f, 2))
assert [len(b) for b in out] == [2, 2, 1]
assert out[0][0] == {"id": "1", "name": "a"}
assert out[2] == [{"id": "5", "name": "e"}]
assert list(batches(io.StringIO("id,name\n"), 10)) == []
for bad in (0, -1, 1.5, "2", True):
try:
batches(io.StringIO("id\n1\n"), bad)
raise AssertionError(f"no ValueError for {bad!r}")
except ValueError:
pass
# streams: a reader that would explode if fully consumed
def rows():
yield "id\n"
for i in range(10):
yield f"{i}\n"
raise RuntimeError("read too far")
first = next(batches(rows(), 3))
assert [r["id"] for r in first] == ["0", "1", "2"]
Hint 1

csv.DictReader already streams rows; your job is to group them.

Hint 2

A generator function doesn't run until it's iterated. How do you raise immediately?

Show solution
import csv
from itertools import islice

def batches(f, size):
if not isinstance(size, int) or isinstance(size, bool) or size < 1:
raise ValueError("size must be a positive integer")
return _batches(csv.DictReader(f), size)

def _batches(reader, size):
while batch := list(islice(reader, size)):
yield batch

csv.DictReader streams. itertools.islice takes the next size rows without materializing the rest, so memory stays at one batch.

The subtle part is validation. Code in a generator function runs on the first next(), not at the call. Splitting into a plain function that validates and a generator that does the work makes batches(f, 0) fail immediately, where the bug is, rather than later in some loop.

What a strong answer covers

  • Streams with constant memory (no reading the whole file) (weight 3)
  • Validates size eagerly, explaining lazy generator execution (weight 2)
  • Handles the partial last batch and the header-only file (weight 1)

Follow-ups

  • Each batch is written to a database. How do you make a crash halfway resumable?

    Checkpoint progress: after each batch commits, record the last row number (or byte offset) in a durable place, ideally in the same transaction as the write. On restart, skip to that point. Making writes idempotent (upserts by key) also protects you if a batch is replayed.

  • When would you reach for pandas read_csv(chunksize=...) or pyarrow instead?

    pandas chunksize when you need DataFrame operations on each chunk. pyarrow when speed or typed columnar output matters (for example writing Parquet), or when files are large. Plain csv with a generator is fine for simple row-by-row work with no dependencies.

Keep the latest version of each record

Pythoneasyjunior15 min
#deduplication#dictionaries

A CDC feed gives you a list of dicts like {"id": 7, "updated_at": "2024-05-01T10:00:00Z", "status": "paid"}. The same id appears several times.

Write latest(records, key="id", ts="updated_at") that keeps, for each key, the record with the greatest timestamp. If two records for the same key share a timestamp, the one that appears later in the input wins. Return the records sorted by key.

Timestamps are ISO-8601 strings in UTC with the same format, so they compare correctly as strings.

Example tests
rs = [
{"id": 2, "updated_at": "2024-05-01T10:00:00Z", "status": "new"},
{"id": 1, "updated_at": "2024-05-01T09:00:00Z", "status": "new"},
{"id": 2, "updated_at": "2024-05-01T11:00:00Z", "status": "paid"},
{"id": 2, "updated_at": "2024-05-01T08:00:00Z", "status": "late-replay"},
{"id": 1, "updated_at": "2024-05-01T09:00:00Z", "status": "tie-later-wins"},
]
out = latest(rs)
assert [r["id"] for r in out] == [1, 2]
assert out[0]["status"] == "tie-later-wins"
assert out[1]["status"] == "paid"
assert latest([]) == []
assert latest([{"k": "a", "t": "1"}], key="k", ts="t") == [{"k": "a", "t": "1"}]
Hint 1

One pass with a dict from key to the best record so far.

Hint 2

>= vs > decides the tie rule.

Show solution
def latest(records, key="id", ts="updated_at"):
best = {}
for r in records:
k = r[key]
if k not in best or r[ts] >= best[k][ts]:
best[k] = r
return [best[k] for k in sorted(best)]

One pass, O(n) time, one dict entry per key. The tie rule lives in a single character: >= lets a later record with the same timestamp replace the earlier one. Say that out loud, because it's exactly the kind of rule that differs between teams.

The prompt says string comparison is safe only because the timestamps share one format and timezone. With mixed formats or offsets, parse them first (datetime.fromisoformat) or results are silently wrong.

What a strong answer covers

  • Single pass with a dict; O(n) (weight 2)
  • Implements and explains the tie rule (>= so later input wins) (weight 2)
  • Notes when string timestamp comparison is unsafe (weight 1)

Follow-ups

  • The feed is 500 million records and doesn't fit in memory. How would you dedup it?

    Don't hold everything in memory. Use an engine (SQL with ROW_NUMBER(), Spark), or partition the input by a hash of the key into files that each fit in memory and dedup each one. An external sort by key and timestamp followed by a single pass also works.

  • CDC also sends deletes ("op": "d"). How does the output change?

    Treat a delete as the latest version of that key: if the newest event for a key is op = 'd', drop the key from the output (or emit a tombstone or soft-delete flag if downstream needs to know).

Find missing and empty date partitions from object storage keys

Pythoneasyjunior · mid20 min
#parsing#file-ingestion#aws

A lake stores tables in object storage with Hive-style partition paths, for example:

raw/orders/dt=2024-03-01/part-0000.parquet
raw/orders/dt=2024-03-01/_SUCCESS
raw/payments/dt=2024-03-02/part-0001.parquet

Write check_partitions(keys, tables, start, end) that takes a list of object keys (as a listing would return them), a list of table names, and an inclusive date range (datetime.date). For each table, return the dates in the range that are missing (no data file under that partition) and the dates that are incomplete (data files but no _SUCCESS marker).

Return {table: {"missing": [dates], "incomplete": [dates]}}, with sorted lists of date objects. Data files are any key ending in .parquet. Ignore keys for other tables, other prefixes, or malformed partition values.

Example tests
from datetime import date
keys = [
"raw/orders/dt=2024-03-01/part-0000.parquet",
"raw/orders/dt=2024-03-01/_SUCCESS",
"raw/orders/dt=2024-03-02/part-0000.parquet", # no _SUCCESS -> incomplete
"raw/orders/dt=2024-03-04/_SUCCESS", # marker but no data -> missing
"raw/payments/dt=2024-03-01/part-0000.parquet",
"raw/payments/dt=2024-03-01/part-0001.parquet",
"raw/payments/dt=2024-03-01/_SUCCESS",
"raw/payments/dt=2024-02-30/part-0000.parquet", # malformed date, ignored
"raw/orders/_temporary/0/part-9.parquet", # not a partition, ignored
"curated/orders/dt=2024-03-03/part-0000.parquet", # other prefix, ignored
"raw/refunds/dt=2024-03-01/part-0000.parquet", # table not requested
]
r = check_partitions(keys, ["orders", "payments"], date(2024, 3, 1), date(2024, 3, 4))
assert r["orders"] == {
"missing": [date(2024, 3, 3), date(2024, 3, 4)],
"incomplete": [date(2024, 3, 2)],
}
assert r["payments"] == {
"missing": [date(2024, 3, 2), date(2024, 3, 3), date(2024, 3, 4)],
"incomplete": [],
}
assert set(r) == {"orders", "payments"}
one = check_partitions([], ["orders"], date(2024, 3, 1), date(2024, 3, 1))
assert one == {"orders": {"missing": [date(2024, 3, 1)], "incomplete": []}}
Hint 1

Parse each key into (table, date, file name) once, then work with sets.

Hint 2

Generate the expected dates from the range; a missing partition only shows up when you compare against what should be there.

Show solution
from datetime import date, timedelta


def check_partitions(keys, tables, start, end):
data, success = set(), set()
for key in keys:
parts = key.split("/")
if len(parts) != 4 or parts[0] != "raw" or not parts[2].startswith("dt="):
continue
table, raw_dt, name = parts[1], parts[2][3:], parts[3]
try:
d = date.fromisoformat(raw_dt)
except ValueError:
continue
if name.endswith(".parquet"):
data.add((table, d))
elif name == "_SUCCESS":
success.add((table, d))
days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
return {
t: {
"missing": [d for d in days if (t, d) not in data],
"incomplete": [d for d in days if (t, d) in data and (t, d) not in success],
}
for t in tables
}

This is the file-system version of a date spine: an absent partition only shows up when you compare the listing against the expected dates. Parse every key once into (table, date) sets, then check each expected day.

The _SUCCESS marker matters because object stores have no atomic "directory": a reader can list a partition while a job is still writing it. Jobs write the marker last (Spark and Hadoop committers do this by default), so data files without a marker mean a partial or failed write. Table formats such as Iceberg and Delta solve this properly with atomic commits; on plain Parquet-on-S3 the marker plus this check are the usual guard.

Parsing defensively (exact path shape, valid ISO dates) keeps one odd key, such as dt=2024-02-30 or a temporary folder, from crashing a monitoring job. Cost is O(keys + days × tables).

What a strong answer covers

  • Parses keys defensively into (table, date) and ignores malformed or unrelated keys (weight 2)
  • Generates expected dates to find missing partitions (weight 2)
  • Uses the _SUCCESS marker to detect incomplete writes and explains why (weight 2)

Follow-ups

  • Listing the bucket takes 20 minutes because there are millions of objects. What would you do instead?

    List only the prefixes you need (one per table and date range) using the delimiter to get partition "folders" without listing every file, or use a storage inventory report or the table catalog's partition list. Better still, have writers record completed partitions in a table that the check queries.

  • How does a table format like Iceberg or Delta change this check?

    Commits are atomic, so readers never see half-written data, and the table's metadata lists exactly which files and partitions exist. You'd query the table's metadata (or partition summary) for missing dates instead of listing storage, and markers aren't needed.

Parse a fixed-width file with a layout spec and a reject list

Pythonmediumjunior · mid25 min
#parsing#file-ingestion#reject-handling

A bank partner sends fixed-width files. Each record line has fields at fixed positions; the first line is a header (H + file date) and the last is a trailer (T + record count, zero-padded to 6 digits).

Write parse_fixed_width(lines, spec) where spec is a list of (name, start, length, kind) tuples (0-based start; kind is "str", "int" or "cents"). It returns (records, rejects):

  • Each record line starts with D. Slice every field from its spec position, strip spaces, and convert: "int" → int, "cents" → int cents parsed from a field like 000012345 (so 12345), "str" → str. A record is a dict of field names.
  • A record line that is too short for the spec, or whose int/cents field isn't all digits after stripping, goes to rejects as (line_number, reason) with 1-based line numbers; reasons are "too_short" or "bad_number:<field>" (the first bad field in spec order).
  • Ignore blank lines. If the trailer's count doesn't equal the number of D lines (valid or not), raise ValueError.

Use only the standard library.

Example tests
spec = [("account", 1, 6, "str"), ("amount", 7, 9, "cents"), ("qty", 16, 3, "int"), ("name", 19, 8, "str")]
good = [
"H20240315",
"DACC001000012345007Alice ",
"DACC002000000099001Bob ",
"",
"DACC00300000x100002Carl ", # bad amount
"DACC004000000050", # too short
"DACC005000000100 Dina ", # blank qty
"T000005",
]
recs, rej = parse_fixed_width(good, spec)
assert recs == [
{"account": "ACC001", "amount": 12345, "qty": 7, "name": "Alice"},
{"account": "ACC002", "amount": 99, "qty": 1, "name": "Bob"},
]
assert rej == [(5, "bad_number:amount"), (6, "too_short"), (7, "bad_number:qty")]
# trailer must match the number of record lines sent, valid or not
try:
parse_fixed_width(good[:-1] + ["T000004"], spec)
raise AssertionError("expected ValueError")
except ValueError:
pass
try:
parse_fixed_width(good[:-1], spec) # no trailer at all
raise AssertionError("expected ValueError")
except ValueError:
pass
# Windows line endings and an empty file body
assert parse_fixed_width(["H20240315\r\n", "T000000\r\n"], spec) == ([], [])
Hint 1

A line's length tells you whether every field fits, before you slice anything.

Hint 2

str.isdigit() on the stripped field covers the number check; decide what an empty numeric field means.

Hint 3

Count record lines separately from valid records, because the trailer counts what was sent, not what you accepted.

Show solution
def parse_fixed_width(lines, spec):
need = max(start + length for _, start, length, _ in spec)
records, rejects, sent, trailer = [], [], 0, None
for n, raw in enumerate(lines, start=1):
line = raw.rstrip("\r\n")
if not line.strip():
continue
kind = line[0]
if kind == "T":
trailer = int(line[1:7])
continue
if kind != "D":
continue # header
sent += 1
if len(line) < need:
rejects.append((n, "too_short"))
continue
rec, bad = {}, None
for name, start, length, typ in spec:
value = line[start:start + length].strip()
if typ in ("int", "cents"):
if not value.isdigit():
bad = name
break
rec[name] = int(value)
else:
rec[name] = value
if bad:
rejects.append((n, f"bad_number:{bad}"))
else:
records.append(rec)
if trailer is None or trailer != sent:
raise ValueError(f"trailer count {trailer} != {sent} record lines")
return records, rejects

Fixed-width files are still everywhere in banking, insurance and government integrations, and parsing them is an ETL interview staple. The points that separate a solid answer:

  • Positions come from a spec, not from the code. A layout table (name, start, length, type) is the contract with the sender; changing the layout means changing data, not logic.
  • Validate before converting. Check the line length, then each numeric field, and record why a line was rejected with its line number, so the sender can fix it. Never silently drop a line.
  • Money as integer cents. Implied-decimal amounts (000012345 = 123.45) stay exact as integers; floats would introduce rounding.
  • Control totals. The trailer counts what was sent. If it doesn't match the record lines received, the file is incomplete or corrupt, and the whole file should fail rather than load partially. A rejected line still counts as sent.

It's a single pass, O(n), and streams naturally if lines is a file object.

What a strong answer covers

  • Drives slicing and typing from the spec, stripping padding (weight 2)
  • Rejects with line number and reason instead of dropping or crashing (weight 3)
  • Keeps amounts as integer cents and checks the trailer against lines sent (weight 2)

Follow-ups

  • The partner adds a new field at the end of each line next month. How do you avoid breaking?

    Version the layout spec and pick it from the header (a layout version or file date) or a configuration keyed by the effective date. Lines longer than the old spec still parse; the new field is read only under the new version. Agree on change notice with the partner.

  • The file is 20 GB. What changes?

    Nothing in the logic if you stream: iterate the file object line by line, write records and rejects in batches, and keep only counters in memory. For speed, split by byte ranges at line boundaries across workers, and check the trailer after all parts finish.

Flatten nested JSON records into rows

Pythoneasyjunior · mid20 min
#parsing#recursion#json

An API returns nested JSON records. Before loading them into a warehouse table, flatten each record into a single-level dict.

Write flatten(record, sep="."):

  • Nested dicts become dotted keys: {"user": {"id": 1}} → {"user.id": 1}.
  • Lists are flattened by index: {"tags": ["a", "b"]} → {"tags.0": "a", "tags.1": "b"}.
  • Empty dicts and empty lists are kept as values ({} / []), so the key isn't lost.
  • If two paths produce the same key (for example {"a.b": 1, "a": {"b": 2}}), raise ValueError instead of silently overwriting.
  • record must be a dict; otherwise raise TypeError.
Example tests
assert flatten({}) == {}
assert flatten({"a": 1, "b": None}) == {"a": 1, "b": None}
assert flatten({"user": {"id": 1, "geo": {"country": "DE"}}}) == {"user.id": 1, "user.geo.country": "DE"}
assert flatten({"tags": ["x", {"k": 2}]}) == {"tags.0": "x", "tags.1.k": 2}
assert flatten({"meta": {}, "items": []}) == {"meta": {}, "items": []}
assert flatten({"a": {"b": 1}}, sep="__") == {"a__b": 1}
try:
flatten({"a.b": 1, "a": {"b": 2}})
raise AssertionError("collision not detected")
except ValueError:
pass
try:
flatten([1, 2])
raise AssertionError("non-dict accepted")
except TypeError:
pass
Hint 1

A small recursive helper that carries the key prefix is enough.

Hint 2

Check whether a key already exists before writing it.

Show solution
def flatten(record, sep="."):
if not isinstance(record, dict):
raise TypeError("record must be a dict")
out = {}

def walk(value, key):
if isinstance(value, dict) and value:
for k, v in value.items():
walk(v, f"{key}{sep}{k}")
elif isinstance(value, list) and value:
for i, v in enumerate(value):
walk(v, f"{key}{sep}{i}")
else:
if key in out:
raise ValueError(f"key collision: {key!r}")
out[key] = value

for k, v in record.items():
walk(v, str(k))
return out

A recursive walk that carries the key prefix handles any depth. Two details separate a good answer from a quick one:

  • Empty containers. Recursing into {} or [] produces no keys at all, so the field silently disappears. Keep them as values.
  • Collisions. Real payloads sometimes contain keys with dots in them. Overwriting would lose data without a trace, so fail loudly and let the caller pick a different sep.

Python's default recursion limit (about 1,000 levels) is far beyond any real JSON nesting. Mention it, but an explicit stack isn't needed here.

What a strong answer covers

  • Recursive (or stack-based) walk that handles dicts and lists at any depth (weight 2)
  • Keeps empty dicts/lists instead of dropping the key (weight 1)
  • Detects key collisions instead of silently overwriting (weight 2)

Follow-ups

  • The warehouse needs one row per element of items instead of items.0, items.1. How would you "explode" lists into rows?

    Emit one output row per list element, copying the parent fields onto each row and adding an index column. An empty list produces zero rows, or one row with nulls if you want to keep the parent. Recursively flatten each element's nested objects.

  • New keys appear every week. How does this interact with a fixed table schema?

    A fixed schema breaks or silently drops new keys. Decide a policy: fail and alert, add new columns automatically (schema evolution), or keep unknown keys in a JSON or variant column. Many teams store raw JSON and flatten in the warehouse.

An idempotent batch upsert writer

Pythonmediummid · senior25 min
#idempotency#cdc#upserts

A CDC feed delivers batches of changes. Batches can be replayed after a crash, and changes can arrive out of order. Each change is a dict with id, updated_at (comparable), op ("upsert" or "delete") and, for upserts, other fields.

Write apply_batch(table, batch) that applies a batch to table (a dict from id to row, modified in place) and returns counts {"inserted", "updated", "deleted", "skipped"}:

  • A change applies only if its updated_at is newer than what the table already has for that id. Equal or older changes are skipped.
  • Deletes must not be undone by an older upsert that arrives later.
  • Applying the same batch twice changes nothing the second time (everything is skipped).

Also write live_rows(table) returning the non-deleted rows sorted by id.

Example tests
t = {}
b1 = [
{"id": 1, "updated_at": 1, "op": "upsert", "v": "a"},
{"id": 2, "updated_at": 1, "op": "upsert", "v": "b"},
{"id": 1, "updated_at": 2, "op": "upsert", "v": "a2"},
]
assert apply_batch(t, b1) == {"inserted": 2, "updated": 1, "deleted": 0, "skipped": 0}
assert apply_batch(t, b1) == {"inserted": 0, "updated": 0, "deleted": 0, "skipped": 3} # replay
assert [r["v"] for r in live_rows(t)] == ["a2", "b"]
# out of order: older update arrives late
assert apply_batch(t, [{"id": 1, "updated_at": 1, "op": "upsert", "v": "stale"}])["skipped"] == 1
assert live_rows(t)[0]["v"] == "a2"
# delete, then a late older upsert must not resurrect it
assert apply_batch(t, [{"id": 2, "updated_at": 5, "op": "delete"}])["deleted"] == 1
assert apply_batch(t, [{"id": 2, "updated_at": 3, "op": "upsert", "v": "zombie"}])["skipped"] == 1
assert [r["id"] for r in live_rows(t)] == [1]
# a newer upsert after the delete brings it back
assert apply_batch(t, [{"id": 2, "updated_at": 9, "op": "upsert", "v": "back"}])["updated"] == 1
assert [r["v"] for r in live_rows(t)] == ["a2", "back"]
assert "op" not in live_rows(t)[0]
# same final state regardless of order
import itertools
changes = [{"id": 7, "updated_at": i, "op": op, "v": i} for i, op in [(1, "upsert"), (2, "delete"), (3, "upsert"), (4, "delete")]]
for perm in itertools.permutations(changes):
t2 = {}
apply_batch(t2, list(perm))
assert live_rows(t2) == [] and t2[7]["updated_at"] == 4
Hint 1

To reject a late, older upsert after a delete, the table has to remember the delete.

Show solution
def apply_batch(table, batch):
counts = {"inserted": 0, "updated": 0, "deleted": 0, "skipped": 0}
for change in batch:
key, ts = change["id"], change["updated_at"]
current = table.get(key)
if current is not None and ts <= current["updated_at"]:
counts["skipped"] += 1
continue
if change["op"] == "delete":
# Tombstone: remembers the delete so older upserts can't resurrect the row.
table[key] = {"id": key, "updated_at": ts, "_deleted": True}
counts["deleted"] += 1
else:
row = {k: v for k, v in change.items() if k != "op"}
counts["inserted" if current is None else "updated"] += 1
table[key] = row
return counts

def live_rows(table):
return [r for _, r in sorted(table.items()) if not r.get("_deleted")]

Idempotency comes from one rule: apply a change only if it's newer than what you have, with <= meaning skip. Replays are then harmless, and out-of-order arrival resolves to the same final state no matter the order.

The subtle part is deletes. If a delete just removes the key, a late upsert with an older timestamp looks brand new and brings the row back. A tombstone (the id, its delete time and a deleted flag) keeps the timestamp around so the late upsert is skipped. Tombstones are later purged after a safe window, the same idea as Delta/Iceberg deletion vectors and Kafka compaction tombstones.

Counting a resurrected row (a newer upsert after a delete) as "updated" is a choice. Say it out loud.

What a strong answer covers

  • Applies a change only if newer than the current version (equal = skip) (weight 3)
  • Keeps tombstones so late older upserts cannot resurrect deleted rows (weight 3)
  • Shows the result is order-independent and replay-safe (weight 1)
  • Mentions purging tombstones after a safe window (weight 1)

Follow-ups

  • Two changes for the same id have the same updated_at. How do you break the tie deterministically?

    Add a deterministic tie-breaker, ideally a source sequence such as a log sequence number (LSN) or an offset, else something stable like an ingestion order column. Never rely on input order, which can change between runs.

  • How does this map to a MERGE statement in a warehouse?

    MERGE INTO target USING staged_batch ON target.id = staged.id WHEN MATCHED AND staged.updated_at > target.updated_at THEN UPDATE ... WHEN NOT MATCHED THEN INSERT ..., with the batch deduplicated to one row per id first.

Fetch every page from a flaky paginated API

Pythonmediummid · senior25 min
#apis#retries#idempotency

An API returns pages like {"items": [...], "next": "cursor-or-None"}. Write:

def fetch_all(get_page, max_retries=3, base_delay=1.0, sleep=time.sleep):
  • get_page(cursor) fetches one page; the first call uses cursor=None.
  • It may raise TransientError (timeouts, HTTP 429/5xx). Retry that page with exponential backoff: base_delay, then 2×, then 4×, …, up to max_retries retries. Any other exception propagates immediately.
  • If a page still fails after max_retries retries, raise the last TransientError.
  • Return all items in order.

sleep is injected so tests don't wait. TransientError is defined for you.

Example tests
# TransientError comes from the solution above.
pages ={None: {"items": [1, 2], "next": "a"}, "a": {"items": [3], "next": "b"}, "b": {"items": [4], "next": None}}
fail_plan = {"a": 2} # page "a" fails twice, then works
calls, slept = [], []
def get_page(cursor):
calls.append(cursor)
if fail_plan.get(cursor, 0) > 0:
fail_plan[cursor] -= 1
raise TransientError("503")
return pages[cursor]
assert fetch_all(get_page, sleep=slept.append) == [1, 2, 3, 4]
assert calls == [None, "a", "a", "a", "b"] # only the failing page is retried
assert slept == [1.0, 2.0] # exponential backoff

def always_down(cursor):
raise TransientError("down")
slept = []
try:
fetch_all(always_down, max_retries=2, base_delay=0.5, sleep=slept.append)
raise AssertionError("should have raised")
except TransientError:
pass
assert slept == [0.5, 1.0]

def bug(cursor):
raise KeyError("not transient")
slept = []
try:
fetch_all(bug, sleep=slept.append)
raise AssertionError("should have raised")
except KeyError:
pass
assert slept == [] # no retries for non-transient errors
Hint 1

Retry around one page fetch, not around the whole loop, or a failure on page 40 refetches pages 1–39.

Hint 2

Reset the retry counter after each successful page.

Show solution
import time

class TransientError(Exception):
pass

def fetch_all(get_page, max_retries=3, base_delay=1.0, sleep=time.sleep):
items, cursor = [], None
while True:
for attempt in range(max_retries + 1):
try:
page = get_page(cursor)
break
except TransientError:
if attempt == max_retries:
raise
sleep(base_delay * 2 ** attempt)
items.extend(page["items"])
cursor = page["next"]
if cursor is None:
return items

Retry the smallest unit that can fail, one page, so progress isn't lost. Retry only errors that are worth retrying. A 400 or a bug should fail fast, not be hammered three more times.

In production you'd add jitter to the delay (so many workers don't retry in lockstep), honor a Retry-After header, and checkpoint the cursor so a crashed job resumes instead of starting over. Injecting sleep and get_page is what makes all of this testable without a network.

What a strong answer covers

  • Retries a single page, not the whole crawl, and resets per page (weight 2)
  • Retries only transient errors; others fail fast (weight 2)
  • Correct exponential backoff and re-raises after the last retry (weight 2)
  • Mentions jitter, Retry-After, and checkpointing the cursor for resumability (weight 1)

Follow-ups

  • The job runs hourly and must only pull records changed since the last run. What do you store, and where?

    Store a high-water mark (the latest updated_at or cursor you processed) in a state table or file, and update it only after the data is committed. Query from slightly before it (an overlap) and upsert, so late or same-timestamp records aren't missed.

  • The API rate limit is 10 requests/second across 20 workers. How do you enforce it?

    Use a shared limiter: a central token bucket (for example in Redis), or give each worker a fixed share (0.5 requests/s) with jittered backoff. Respect 429 responses and Retry-After headers either way.

Count HTTP status codes per path from raw log lines

Pythoneasyjunior · mid20 min
#parsing#data-quality

You get an iterable of raw log lines like:

2024-05-01T10:00:00Z GET /api/orders 200 123ms
2024-05-01T10:00:01Z POST /api/orders 500 87ms

Write status_counts(lines) that returns a tuple (counts, bad_lines):

  • counts: dict[path, dict[status_code_int, count]]
  • bad_lines: the number of lines that don't match the format (wrong number of fields, non-integer status, status outside 100–599, latency not ending in ms)

Blank lines are ignored and are not counted as bad. Don't stop on a bad line.

Example tests
lines = [
"2024-05-01T10:00:00Z GET /api/orders 200 123ms",
"2024-05-01T10:00:01Z POST /api/orders 500 87ms",
"2024-05-01T10:00:02Z GET /api/orders 200 10ms",
"2024-05-01T10:00:03Z GET /health 200 1ms",
"",
"garbage",
"2024-05-01T10:00:04Z GET /api/orders abc 5ms",
"2024-05-01T10:00:05Z GET /api/orders 700 5ms",
"2024-05-01T10:00:06Z GET /api/orders 200 5s",
]
counts, bad = status_counts(lines)
assert counts == {"/api/orders": {200: 2, 500: 1}, "/health": {200: 1}}
assert bad == 4
assert status_counts([]) == ({}, 0)
assert status_counts(iter([" ", "\n"])) == ({}, 0) # works on any iterable, blanks ignored
Hint 1

Split on whitespace and validate each field; never let one bad line raise.

Hint 2

collections.defaultdict keeps the nested counting short.

Show solution
from collections import defaultdict

def status_counts(lines):
counts = defaultdict(lambda: defaultdict(int))
bad = 0
for raw in lines:
line = raw.strip()
if not line:
continue
parts = line.split()
if len(parts) != 5:
bad += 1
continue
_ts, _method, path, status, latency = parts
if not status.isdigit() or not 100 <= int(status) <= 599 or not latency.endswith("ms"):
bad += 1
continue
counts[path][int(status)] += 1
return {p: dict(s) for p, s in counts.items()}, bad

The interview signal here is defensive parsing: real logs contain truncated lines, garbage and new formats. Validate each field, count what you skip (so data loss is visible, not silent), and keep going.

Return plain dicts, not defaultdicts, so callers don't get surprise keys on lookup. For huge files, the same function works on a file object because it only iterates once.

What a strong answer covers

  • Never crashes on a malformed line; counts and reports skipped lines (weight 3)
  • Validates each field (count, numeric status, range, latency unit) (weight 2)
  • Streams the input once (works on a file object, not only a list) (weight 1)

Follow-ups

  • The file is 200 GB. What changes, if anything?

    Streaming line by line still works for memory, but one process is slow. Split the file into byte ranges aligned to line breaks, process them in parallel, and merge the counters, or use Spark or a warehouse to do the same.

  • How would you report the bad lines so someone can fix the producer?

    Count them by reason, keep a sample of bad lines with the file name and line number, write them to a quarantine file or table, and alert if the bad-line rate crosses a threshold.

Detect anomalies in daily row counts with a robust baseline

Pythonmediummid · senior25 min
#data-quality#anomaly-detection#algorithms

A monitor records how many rows a table received each day. Write flag_anomalies(counts, window=7, threshold=3.5) that returns the indices of days whose count is anomalous compared with the previous window days:

  • Skip the first window days (not enough history).
  • Baseline: the median of the previous window counts.
  • Spread: the median absolute deviation (MAD) of those counts, scaled by 1.4826 so it's comparable to a standard deviation.
  • A day is anomalous if |count - median| / scaled_mad > threshold.
  • If the MAD is 0 (the previous days were all equal), flag the day only if its count differs from the median.

Use only the standard library.

Example tests
steady = [100, 102, 98, 101, 99, 100, 103]
assert flag_anomalies(steady + [101]) == []
assert flag_anomalies(steady + [0]) == [7] # a missing load
assert flag_anomalies(steady + [250]) == [7] # a double load
assert flag_anomalies(steady[:5]) == [] # not enough history
# one outlier inside the window must not hide the next incident
series = steady + [0, 100, 99, 101, 0]
assert flag_anomalies(series) == [7, 11]
# zero spread: any change is an anomaly, no division by zero
assert flag_anomalies([50] * 7 + [50, 51]) == [8]
# window and threshold are respected
assert flag_anomalies([10, 12, 11, 30], window=3) == [3]
assert flag_anomalies(steady + [110], threshold=10) == []
Hint 1

statistics.median does the hard part. MAD is the median of |x - median| over the window.

Hint 2

Why does one bad day inside the window barely move a median, but drag a mean and a standard deviation a long way?

Show solution
from statistics import median


def flag_anomalies(counts, window=7, threshold=3.5):
flagged = []
for i in range(window, len(counts)):
history = counts[i - window:i]
mid = median(history)
mad = median(abs(x - mid) for x in history) * 1.4826
if mad == 0:
if counts[i] != mid:
flagged.append(i)
elif abs(counts[i] - mid) / mad > threshold:
flagged.append(i)
return flagged

This is the robust cousin of a z-score. A mean and standard deviation are pulled by the very outliers you're trying to catch: after one bad day (say 0 rows), the next week's mean drops and the standard deviation balloons, so a second incident hides inside the widened band. The median and MAD barely move when one value in the window is extreme, so the band stays tight.

The 1.4826 factor makes the MAD match the standard deviation for normally distributed data, so a threshold of 3.5 means roughly "3.5 standard deviations" (a common choice for MAD-based outlier tests).

The zero-MAD case matters in practice: a table that receives exactly the same count every day (a dimension, a fixed export) has no spread, and dividing by zero would crash. Treat any change as anomalous instead.

Cost is O(n × window log window); for a daily series that's nothing. In production you'd also add a seasonal baseline (same weekday), a minimum absolute change, and alert routing.

What a strong answer covers

  • Uses only the previous window as the baseline (no look-ahead, skips days without history) (weight 2)
  • Computes median and scaled MAD correctly and explains why they are robust to outliers (weight 3)
  • Handles zero MAD without dividing by zero (weight 2)

Follow-ups

  • Row counts are fine, but one column suddenly becomes 40% NULL. How would you extend this?

    Track more metrics per load, not just row count: the null rate per column, distinct counts, min/max and sums of key measures. Run the same robust detector on each metric's daily series, and alert on the ones that matter for consumers.

  • How would you avoid paging on every Sunday dip?

    Use a seasonal baseline (compare against the same weekday over the last several weeks), and require a minimum absolute change as well as a relative one. Route low-severity anomalies to a channel instead of a page.

Detect schema drift between two batches of records

Pythonmediummid · senior25 min
#data-quality#schema-evolution

Before loading a new batch of records (a list of dicts), compare its shape with yesterday's batch so the pipeline can stop on breaking changes.

Write drift(old_rows, new_rows) that returns a dict:

  • added: columns present in the new batch but not the old one (sorted list)
  • removed: columns present in the old batch but not the new one (sorted list)
  • type_changes: {column: (old_types, new_types)} for columns in both batches whose set of non-null value types differs, each as a sorted list of type names ("int", "str", "bool", …)
  • became_nullable: columns in both batches that never had a null in the old batch but have one in the new batch (sorted list)

A column missing from a row counts as null for that row. bool is its own type, not int.

Example tests
old = [{"id": 1, "amount": 10, "paid": True}, {"id": 2, "amount": 20, "paid": False}]
new = [{"id": 3, "amount": "30", "paid": 1, "currency": "EUR"}, {"id": 4, "amount": "40", "currency": None}]
d = drift(old, new)
assert d["added"] == ["currency"]
assert d["removed"] == []
assert d["type_changes"] == {"amount": (["int"], ["str"]), "paid": (["bool"], ["int"])}
assert d["became_nullable"] == ["paid"] # missing in the second new row
assert drift(old, old) == {"added": [], "removed": [], "type_changes": {}, "became_nullable": []}
assert drift([{"a": 1}], [{"b": 1}])["removed"] == ["a"]
assert drift([], []) == {"added": [], "removed": [], "type_changes": {}, "became_nullable": []}
Hint 1

Profile each batch once (types seen, null seen, per column), then compare the two profiles.

Hint 2

What's the type name of True?

Show solution
def profile(rows):
cols = {}
for row in rows:
for col in row:
cols.setdefault(col, {"types": set(), "nullable": False})
for row in rows:
for col, info in cols.items():
value = row.get(col)
if value is None:
info["nullable"] = True
else:
info["types"].add(type(value).__name__)
return cols

def drift(old_rows, new_rows):
old, new = profile(old_rows), profile(new_rows)
both = old.keys() & new.keys()
return {
"added": sorted(new.keys() - old.keys()),
"removed": sorted(old.keys() - new.keys()),
"type_changes": {
c: (sorted(old[c]["types"]), sorted(new[c]["types"]))
for c in sorted(both)
if old[c]["types"] != new[c]["types"]
},
"became_nullable": sorted(
c for c in both if not old[c]["nullable"] and new[c]["nullable"]
),
}

Profile, then diff. One pass collects every column name (so a column that appears in only some rows still counts), and a second pass records the types seen and whether a null or missing value appeared.

Two traps:

  • Missing keys are nulls. If you only look at keys that are present, a column that disappears from half the rows never shows up as nullable.
  • bool vs int. isinstance(True, int) is True. Using type(v).__name__ keeps them apart, which matters when a producer starts sending 1/0 instead of true/false.

In a pipeline you'd treat added as safe (additive), and removed, type_changes and became_nullable on a non-null column as breaking: fail the load and alert the producer.

What a strong answer covers

  • Profiles each batch once, then compares profiles (weight 2)
  • Treats missing keys as nulls when checking nullability (weight 2)
  • Keeps bool and int distinct (weight 1)
  • Says which changes are breaking vs safe and what the pipeline should do (weight 2)

Follow-ups

  • The batches have 50 million rows each. What would you sample, and what could sampling miss?

    Sample randomly across the whole batch (not just the first rows), plus check the full set of keys cheaply if you can. Sampling can miss rare fields or rare type changes, so compare full schemas from metadata (Parquet footers) when it's available.

  • Where should this check live, in the producer's CI, at ingestion or in the warehouse?

    As early as possible: contract checks in the producer's CI catch breaking changes before release, while checks at ingestion catch what slips through. Warehouse tests are the last line of defense.

Extract table lineage from SQL statements

Pythonhardsenior · lead35 min
#parsing#lineage#sql

To build a lineage graph, you need the target and source tables of each SQL statement in a repo. Write lineage(sql) that returns (target, sources) for one statement:

  • target: the table written by INSERT INTO, INSERT OVERWRITE [TABLE], CREATE [OR REPLACE] [TEMP|TEMPORARY|TRANSIENT] TABLE [IF NOT EXISTS] … AS, or MERGE INTO; None for a plain SELECT.
  • sources: sorted list of tables read via FROM, JOIN or MERGE … USING.

Names are lowercased, schema qualification is kept (analytics.orders), and double quotes are removed. It must not be fooled by:

  • CTE names (they're not tables)
  • subqueries (FROM (SELECT …))
  • FROM inside functions, like EXTRACT(YEAR FROM ts) or TRIM(BOTH ' ' FROM s)
  • comments (-- …, /* … */) and string literals
  • the target itself (a MERGE target isn't a source)

A full SQL parser isn't needed. Explain the limits of your approach.

Example tests
sql = """
-- nightly load; FROM fake_table in a comment
INSERT INTO analytics.daily_revenue
WITH paid AS (
SELECT o.order_id, EXTRACT(YEAR FROM o.order_ts) AS y
FROM raw.orders o
JOIN raw.payments p ON p.order_id = o.order_id
), recent AS (SELECT * FROM paid WHERE y = 2024)
SELECT r.*, TRIM(BOTH ' ' FROM c.name) AS name, 'FROM not_a_table' AS note
FROM recent r
LEFT JOIN "Raw"."Customers" c ON c.id = r.order_id
WHERE r.order_id IN (SELECT order_id FROM staging.allowlist)
"""
assert lineage(sql) == ("analytics.daily_revenue", ["raw.customers", "raw.orders", "raw.payments", "staging.allowlist"])
assert lineage("select * from a.b join c using (id)") == (None, ["a.b", "c"])
assert lineage("CREATE OR REPLACE TEMP TABLE t AS SELECT x FROM (SELECT x FROM src) s") == ("t", ["src"])
assert lineage("CREATE TABLE IF NOT EXISTS mart.x AS /* FROM nope */ SELECT 1 FROM base") == ("mart.x", ["base"])
assert lineage("MERGE INTO dim.customer d USING stg.customer s ON d.id = s.id WHEN MATCHED THEN UPDATE SET name = s.name") == ("dim.customer", ["stg.customer"])
assert lineage("INSERT OVERWRITE TABLE lake.events SELECT * FROM lake.events_raw") == ("lake.events", ["lake.events_raw"])
assert lineage("SELECT SUBSTRING(s FROM 2) FROM t") == (None, ["t"])
Hint 1

Strip comments and string literals first, then tokenize.

Hint 2

Track parentheses. A ( followed by SELECT or WITH opens a query; any other ( is an expression, where FROM isn't a table.

Show solution
import re

IDENT = r'(?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))*'
TOKEN = re.compile(IDENT + r"|\(|\)|,|\S")

def _name(tok):
return tok.replace('"', "").lower()

def _is_ident(tok):
return re.fullmatch(IDENT, tok) is not None

def lineage(sql):
s = re.sub(r"--[^\n]*", " ", sql)
s = re.sub(r"/\*.*?\*/", " ", s, flags=re.S)
s = re.sub(r"'(?:[^']|'')*'", "''", s)
toks = TOKEN.findall(s)
up = [t.upper() for t in toks]

target, i = None, 0
if up[:2] in (["INSERT", "INTO"], ["MERGE", "INTO"]):
i = 2
elif up[:2] == ["INSERT", "OVERWRITE"]:
i = 3 if up[2:3] == ["TABLE"] else 2
elif up[:1] == ["CREATE"]:
i = 1
while i < len(up) and up[i] in ("OR", "REPLACE", "TEMP", "TEMPORARY", "TRANSIENT"):
i += 1
if up[i : i + 1] == ["TABLE"]:
i += 1
if up[i : i + 3] == ["IF", "NOT", "EXISTS"]:
i += 3
else:
i = 0
if i and i < len(toks) and _is_ident(toks[i]):
target = _name(toks[i])

ctes, sources, stack = set(), set(), []
for j, t in enumerate(toks):
u = up[j]
if t == "(":
stack.append("query" if up[j + 1 : j + 2] in (["SELECT"], ["WITH"]) else "expr")
elif t == ")":
if stack:
stack.pop()
elif (
_is_ident(t)
and up[j + 1 : j + 3] == ["AS", "("]
and j > 0
and up[j - 1] in ("WITH", "RECURSIVE", ",")
and (not stack or stack[-1] == "query")
):
ctes.add(_name(t))
elif u in ("FROM", "JOIN", "USING") and (not stack or stack[-1] == "query"):
nxt = toks[j + 1] if j + 1 < len(toks) else ""
if nxt != "(" and _is_ident(nxt) and nxt.upper() not in ("SELECT", "LATERAL", "UNNEST"):
sources.add(_name(nxt))
return target, sorted(sources - ctes - {target})

The approach is clean, tokenize, then walk with a parenthesis stack:

  1. Remove comments and string literals first, so -- FROM fake and 'FROM x' can't match.
  2. Tokenize into identifiers (including dotted and quoted parts), parentheses and punctuation.
  3. Each ( pushes a context: query if the next token is SELECT or WITH, otherwise expr. A FROM/JOIN only names a table in a query context, which is how EXTRACT(YEAR FROM ts) is ignored while subquery sources are still found.
  4. CTE names are identifiers followed by AS ( right after WITH or a comma. Collect them and subtract them, along with the target.

Limits: comma joins (FROM a, b) find only a; table functions, dynamic SQL and dialect quirks (backticks, bracket quoting) aren't handled. For production lineage, use a real parser such as sqlglot, or the warehouse's own query logs (Snowflake ACCESS_HISTORY, BigQuery INFORMATION_SCHEMA.JOBS), which see what really ran.

What a strong answer covers

  • Removes comments and string literals before matching (weight 2)
  • Distinguishes query parentheses from expression parentheses (EXTRACT/TRIM ... FROM) (weight 3)
  • Excludes CTE names and the target from sources (weight 2)
  • States the limits and suggests a real parser or query-log lineage for production (weight 2)

Follow-ups

  • Extend it to column-level lineage. Why is that much harder?

    Columns pass through expressions, aliases, SELECT *, CTEs, joins, aggregates and window functions, so you need a real SQL parser and the table schemas to resolve each output column to its inputs. Regexes can't do it.

  • The repo has 4,000 SQL files using Jinja templates (dbt). How would you get lineage then?

    Use dbt's own artifacts: manifest.json already has model dependencies from ref and source. For column level, parse the compiled SQL (with a library like sqlglot) rather than the Jinja templates.

Top-k items from a stream with a heap

Pythonmediummid · senior20 min
#heaps#streaming#algorithms

A stream yields (id, value) pairs, where id is an int. It's too large to hold in memory. Write top_k(stream, k) that returns the k pairs with the largest values, sorted by value descending.

  • Ties on value: the smaller id ranks higher.
  • Use O(k) memory, not O(n).
  • k == 0 returns []; a negative k raises ValueError; fewer than k items returns all of them.
Example tests
import random
assert top_k([], 3) == []
assert top_k([(1, 5)], 0) == []
assert top_k([(1, 5), (2, 9)], 5) == [(2, 9), (1, 5)]
assert top_k([(5, 10), (3, 10), (9, 10), (1, 2)], 2) == [(3, 10), (5, 10)] # ties: smaller id first
try:
top_k([], -1)
raise AssertionError("negative k accepted")
except ValueError:
pass
rng = random.Random(7)
data = [(i, rng.randint(0, 50)) for i in range(5000)]
expected = sorted(data, key=lambda p: (-p[1], p[0]))[:25]
assert top_k(iter(data), 25) == expected
assert top_k((p for p in data), 25) == expected # works on a one-pass generator
Hint 1

A min-heap of size k keeps the k best seen so far; its root is the one to evict.

Hint 2

What should the heap's ordering be so that, among equal values, the larger id is evicted first?

Show solution
import heapq

def top_k(stream, k):
if k < 0:
raise ValueError("k must be >= 0")
if k == 0:
return []
heap = [] # (value, -id): the root is the worst kept item
for id_, value in stream:
item = (value, -id_)
if len(heap) < k:
heapq.heappush(heap, item)
elif item > heap[0]:
heapq.heapreplace(heap, item)
return [(-neg_id, value) for value, neg_id in sorted(heap, reverse=True)]

Keep a min-heap of size k. The root is the weakest of the current top k, so each new item only has to beat the root: O(log k) per item, O(n log k) total, O(k) memory.

The tie rule is the trap. With (value, id) in the heap, Python compares ids on equal values and evicts the smaller id first, which is the opposite of what's asked. Storing -id flips it: among equal values the larger id is smaller, so it becomes the root and is evicted first.

heapq.nlargest(k, stream, key=…) is fine in production. In the interview, show you know what it does underneath.

What a strong answer covers

  • Uses a size-k min-heap: O(n log k) time, O(k) memory (weight 3)
  • Handles the tie rule correctly (smaller id wins) (weight 2)
  • Handles k = 0, negative k and fewer than k items (weight 1)

Follow-ups

  • The stream is split across 50 workers. How do you get the global top k?

    Each worker keeps its local top k and sends it to one reducer, which merges them with a heap. This is correct because any global top-k item must be in the top k of the worker that saw it.

  • Now the stream yields word occurrences and you need the top-k most frequent words. What changes, and what if the vocabulary doesn't fit in memory?

    You need a count per word first, then a top-k by count. If the vocabulary doesn't fit in memory, shard words by hash across workers, or use an approximate sketch such as Count-Min Sketch with a heap, which trades accuracy for memory.

Total downtime from overlapping incident windows

Pythonmediummid20 min
#intervals#sorting

Monitoring reports incident windows as (start, end) pairs of datetimes. Windows can overlap, nest, or arrive unsorted, and some extend outside the day you're reporting on.

Write downtime_minutes(windows, day_start, day_end) that returns the total minutes (float) during [day_start, day_end) covered by at least one window. Overlapping time counts once. Ignore windows with end <= start.

Example tests
from datetime import datetime as dt
d0, d1 = dt(2024, 5, 1), dt(2024, 5, 2)
w = [
(dt(2024, 5, 1, 10, 0), dt(2024, 5, 1, 10, 30)),
(dt(2024, 5, 1, 10, 15), dt(2024, 5, 1, 11, 0)), # overlaps -> 10:00-11:00
(dt(2024, 5, 1, 10, 20), dt(2024, 5, 1, 10, 25)), # nested
(dt(2024, 5, 1, 12, 0), dt(2024, 5, 1, 12, 10)), # separate
(dt(2024, 4, 30, 23, 0), dt(2024, 5, 1, 0, 30)), # clipped to 30 min
(dt(2024, 5, 1, 23, 50), dt(2024, 5, 2, 2, 0)), # clipped to 10 min
(dt(2024, 5, 1, 15, 0), dt(2024, 5, 1, 14, 0)), # invalid, ignored
(dt(2024, 5, 3, 1, 0), dt(2024, 5, 3, 2, 0)), # other day
]
assert downtime_minutes(w, d0, d1) == 60 + 10 + 30 + 10
assert downtime_minutes(list(reversed(w)), d0, d1) == 110 # order doesn't matter
assert downtime_minutes([], d0, d1) == 0
assert downtime_minutes([(d0, d1), (d0, d1)], d0, d1) == 24 * 60
touching = [(dt(2024, 5, 1, 1), dt(2024, 5, 1, 2)), (dt(2024, 5, 1, 2), dt(2024, 5, 1, 3))]
assert downtime_minutes(touching, d0, d1) == 120
Hint 1

Clip each window to the day, sort by start, then merge as you go.

Show solution
def downtime_minutes(windows, day_start, day_end):
clipped = sorted(
(max(s, day_start), min(e, day_end))
for s, e in windows
if e > s and e > day_start and s < day_end
)
total = 0.0
cur_start = cur_end = None
for s, e in clipped:
if cur_end is None or s > cur_end:
if cur_end is not None:
total += (cur_end - cur_start).total_seconds()
cur_start, cur_end = s, e
else:
cur_end = max(cur_end, e)
if cur_end is not None:
total += (cur_end - cur_start).total_seconds()
return total / 60

This is the classic merge intervals pattern, which DE interviews like because SLA and uptime reports really need it. Clip to the reporting window first (so a window from yesterday 23:00 to today 01:00 counts one hour), sort by start, and extend the current block while windows overlap or touch. O(n log n) for the sort.

Summing raw window lengths is the usual wrong answer: it double-counts overlaps and reports more than 24 hours of downtime on a bad day.

What a strong answer covers

  • Clips windows to the reporting period before merging (weight 2)
  • Sorts and merges overlapping/nested windows so overlap counts once (weight 3)
  • Handles invalid windows and states the O(n log n) cost (weight 1)

Follow-ups

  • Do the same in SQL for a whole month of incidents per service.

    Order windows per service by start time, flag a new island when a window starts after the running maximum of previous ends, group by island to get each merged window, then sum the durations per service.

  • Windows arrive as a stream, one at a time. How do you keep a running total?

    Keep the merged intervals sorted and insert each new window, merging overlaps, then update the total. If windows arrive in start order, you only need the current merged window and the total.

7-day moving average of completed trips per city

SQLmediummid · senior20 mindataset: rides
#moving-averages#date-spine#window-functions

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

For every city and every calendar day between the first and last requested_at date in the whole table, return:

  • trips: completed trips (status = 'completed') requested that day. Days with none count as 0.
  • trips_7d_avg: the average of trips over that day and the 6 days before it, rounded to 2 decimals. For the first 6 days, average over the days available.

Output: city, trip_date, trips, trips_7d_avg. Order by city, trip_date.

Hint 1

A window over only the days that have trips silently skips the quiet days. Build the full list of days first.

Hint 2

Cross join cities with days, then left join the daily counts.

Show solution
WITH bounds AS (
SELECT MIN(CAST(requested_at AS DATE)) AS first_day,
MAX(CAST(requested_at AS DATE)) AS last_day
FROM trips
),
days AS (
SELECT CAST(UNNEST(GENERATE_SERIES(first_day, last_day, INTERVAL 1 DAY)) AS DATE) AS trip_date
FROM bounds
),
cities AS (
SELECT DISTINCT city FROM trips
),
daily AS (
SELECT city, CAST(requested_at AS DATE) AS trip_date, COUNT(*) AS trips
FROM trips
WHERE status = 'completed'
GROUP BY city, CAST(requested_at AS DATE)
),
filled AS (
SELECT c.city, d.trip_date, COALESCE(x.trips, 0) AS trips
FROM cities c
CROSS JOIN days d
LEFT JOIN daily x ON x.city = c.city AND x.trip_date = d.trip_date
)
SELECT city,
trip_date,
trips,
ROUND(AVG(trips) OVER (
PARTITION BY city ORDER BY trip_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS trips_7d_avg
FROM filled
ORDER BY city, trip_date;

The trap is missing days. ROWS BETWEEN 6 PRECEDING counts rows, not days. If a city has no trips on Tuesday, the window reaches back 8 calendar days and the average is wrong. A date spine (one row per day) cross-joined with cities fixes it.

COALESCE(..., 0) matters too: AVG ignores NULLs, so leaving the gaps as NULL would inflate the average.

What a strong answer covers

  • Spots that a ROWS window over sparse data skips calendar days, and builds a date spine (weight 2)
  • Fills missing days with 0, not NULL, and explains the effect on AVG (weight 1)

Follow-ups

  • Could you use a RANGE frame with an INTERVAL instead of a spine? What would it still get wrong?

    Yes: RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW over the date handles missing days in the window. It still averages only the days that have rows, so a day with zero trips doesn't pull the average down, and days with no trips get no output row. Divide the sum by 7 and use a spine to list every day.

  • In a production pipeline, where would the date spine come from?

    From a shared calendar dimension (dim_date), generated once for a wide range (for example 2000–2050) with attributes like week, month and holidays, or from a generator such as dbt_utils.date_spine. Every model reuses it instead of building its own.

Dialect notes

  • snowflake: No GENERATE_SERIES. Build the spine with `TABLE(GENERATOR(ROWCOUNT => n))` and `DATEADD(day, SEQ4(), first_day)`, or join a calendar table. docs
  • bigquery: `UNNEST(GENERATE_DATE_ARRAY(first_day, last_day))` returns dates directly. docs

Further reading

Build an SCD Type 2 table from a change log

SQLmediummid · senior25 mindataset: ecommerce
#scd-type-2#gaps-and-islands#window-functions

Table: customer_addresses(customer_id, country, effective_date). It's a change log: each row says "from this date the customer lives in this country". The first row is the signup date.

The source sometimes re-records the same country (an address re-verification). Those rows must not create a new version.

Build the SCD Type 2 history: one row per real version, with valid_to = the next version's valid_from (exclusive), 9999-12-31 for the current version, and an is_current flag.

Output: customer_id, country, valid_from, valid_to, is_current. Order by customer_id, valid_from.

Hint 1

First drop rows whose country equals the previous row's country for that customer.

Hint 2

Then LEAD over what's left gives each version's end.

Show solution
WITH marked AS (
SELECT customer_id, country, effective_date,
LAG(country) OVER (PARTITION BY customer_id ORDER BY effective_date) AS prev_country
FROM customer_addresses
),
changes AS (
SELECT customer_id, country, effective_date AS valid_from
FROM marked
WHERE prev_country IS NULL OR prev_country <> country
)
SELECT customer_id,
country,
valid_from,
COALESCE(LEAD(valid_from) OVER w, DATE '9999-12-31') AS valid_to,
LEAD(valid_from) OVER w IS NULL AS is_current
FROM changes
WINDOW w AS (PARTITION BY customer_id ORDER BY valid_from)
ORDER BY customer_id, valid_from;

Two passes: collapse, then close. The no-op rows are a gaps-and-islands problem in disguise: consecutive rows with the same value form one island, and only the first row of each island starts a version. After that, LEAD(valid_from) closes each version.

Applying LEAD to the raw log gives versions that change from DE to DE. They look harmless, but they break "how many customers moved" and bloat the dimension.

Using 9999-12-31 instead of NULL for open versions keeps point-in-time joins (d >= valid_from AND d < valid_to) simple.

What a strong answer covers

  • Collapses no-op re-records before building versions (weight 2)
  • Uses half-open intervals (valid_to exclusive) and a far-future end date, and says why (weight 1)

Follow-ups

  • The log arrives daily. How would you MERGE only today's changes into the existing SCD2 table?

    Stage today's changes, deduplicated to the last change per key per timestamp. Then, in one transaction, close the current row (valid_to = change time, is_current = false) for keys whose attributes changed, and insert the new versions. Many teams do this as one MERGE with a union trick, or as an update followed by an insert.

  • A change arrives that is dated before the current version started. What happens to your MERGE?

    A simple MERGE assumes changes arrive in order, so a backdated change would be inserted as current, or overlap the existing versions. You must split the version that covers that date, insert the late version in between, and fix the following row's valid_from. Often it's simplest to rebuild that key's history from the full log.

Further reading

Cancellation rate, with and without a driver assigned

SQLeasyjunior10 mindataset: rides
#null-traps#aggregation#rates

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare). A cancelled trip has driver_id = NULL if it was cancelled before a driver was assigned.

Per city, return: all trip requests, cancelled requests, the cancellation rate (rounded to 4 decimals), and how many cancellations happened before a driver was assigned.

Output: city, requests, cancelled, cancel_rate, cancelled_before_assignment. Order by city.

Hint 1

COUNT(*), COUNT(column) and SUM(CASE …) each count something different.

Show solution
SELECT city,
COUNT(*) AS requests,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
ROUND(AVG(CASE WHEN status = 'cancelled' THEN 1.0 ELSE 0.0 END), 4) AS cancel_rate,
SUM(CASE WHEN status = 'cancelled' AND driver_id IS NULL THEN 1 ELSE 0 END)
AS cancelled_before_assignment
FROM trips
GROUP BY city
ORDER BY city;

COUNT(*) counts rows, while COUNT(driver_id) counts non-NULL values. So COUNT(*) - COUNT(driver_id) would also give "requests with no driver", but that silently mixes in any future status where the driver is NULL. Spelling out the condition is clearer.

AVG(CASE … THEN 1.0 ELSE 0.0 END) is a compact way to get a rate, and it avoids integer division.

Follow-ups

  • Split cancellations by who cancelled. What column would you ask the source team for?

    A cancelled_by column (rider, driver, system or support) and ideally a cancellation reason and timestamp. Without it, you'd have to guess from other columns, which is unreliable.

  • Where should "cancellation rate" be defined so every dashboard uses the same formula?

    In one governed place: a metric in the semantic layer or a dbt model, with the numerator, the denominator and the edge cases (system cancellations, test trips) documented. Dashboards read the metric instead of re-implementing the formula.

Each category's share of total revenue

SQLeasyjunior10 mindataset: ecommerce
#window-functions#percent-of-total

Tables:

  • products(product_id, name, category, price)
  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

For completed orders, return each category's revenue and its share of total revenue (rounded to 4 decimals).

Output: category, revenue, pct_of_total. Order by revenue descending.

Hint 1

A window function with an empty OVER () sees every row of the grouped result.

Show solution
SELECT p.category,
SUM(oi.quantity * oi.unit_price) AS revenue,
ROUND(SUM(oi.quantity * oi.unit_price) * 1.0
/ SUM(SUM(oi.quantity * oi.unit_price)) OVER (), 4) AS pct_of_total
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status = 'completed'
GROUP BY p.category
ORDER BY revenue DESC;

SUM(SUM(x)) OVER () looks odd but is standard. The inner SUM is the GROUP BY aggregate per category; the outer windowed SUM adds those up across all groups. Window functions run after GROUP BY, which is why this works.

The alternative is a CTE for category revenue and a cross join to its total. It's fine too, and easier for some readers.

Follow-ups

  • Show each category's share within each month instead. What goes in OVER ()?

    Partition the total by month: revenue / SUM(revenue) OVER (PARTITION BY month), after grouping by month and category.

  • Why do window functions run after GROUP BY and before ORDER BY?

    Logically, window functions run over the result of FROM/WHERE/GROUP BY/HAVING, so they can use aggregates such as SUM(revenue) inside OVER. ORDER BY comes after so it can sort by window results. That's also why you can't filter on a window function in WHERE; wrap it in a subquery or use QUALIFY.

Monthly chargeback rate on settled payments

SQLmediummid · senior20 mindataset: payments
#deduplication#left-joins#rates

Tables:

  • transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at): contains replays; the copy with the latest ingested_at per txn_id is the truth.
  • chargebacks(chargeback_id, txn_id, filed_date, amount, reason)

For each month of txn_ts, count settled payments (txn_type = 'payment' and latest status = 'settled'), count how many of them have a chargeback, and compute chargeback_rate = chargebacks / payments rounded to 4 decimals. Attribute a chargeback to the month of its transaction, not the month it was filed.

Output: month (first day of month), payments, chargebacks, chargeback_rate. Order by month.

Hint 1

Dedup first, then LEFT JOIN chargebacks so payments without one still count in the denominator.

Show solution
WITH latest AS (
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
) t
WHERE rn = 1
),
settled AS (
SELECT txn_id, CAST(DATE_TRUNC('month', txn_ts) AS DATE) AS month
FROM latest
WHERE txn_type = 'payment' AND status = 'settled'
)
SELECT s.month,
COUNT(*) AS payments,
COUNT(DISTINCT c.txn_id) AS chargebacks,
ROUND(COUNT(DISTINCT c.txn_id) * 1.0 / COUNT(*), 4) AS chargeback_rate
FROM settled s
LEFT JOIN chargebacks c ON c.txn_id = s.txn_id
GROUP BY s.month
ORDER BY s.month;

Three choices make or break the number:

  1. Dedup before counting, or replays inflate the denominator.
  2. LEFT JOIN, so payments without chargebacks stay in the denominator. An inner join would give a rate of 100%.
  3. Attribution month. Chargebacks are filed weeks later. By transaction month, recent months look artificially good until chargebacks arrive. By filed month, the numerator and denominator come from different populations. Pick one, say which, and flag that recent months are immature.

COUNT(DISTINCT c.txn_id) guards against a transaction with two chargebacks multiplying the payment row.

What a strong answer covers

  • Keeps payments without chargebacks in the denominator (LEFT JOIN) (weight 2)
  • Discusses attribution month and that recent months are immature (weight 2)

Follow-ups

  • Risk wants the rate by amount, not count, in USD. What else do you need?

    Amounts in a common currency: an FX rate table, joined on the currency and the transaction date (or the settlement date, as finance defines it). Decide whether to use the transaction amount or the chargeback amount, since partial chargebacks exist. Then it's SUM(chargeback USD) / SUM(payment USD).

  • How would you alert when a month's rate is abnormally high without paging on immature months?

    Chargebacks are filed weeks or months after the transaction, so recent months look artificially low. Compare each month against earlier months at the same age (for example rate at 30, 60 and 90 days after month end), or alert only on months older than the usual chargeback window.

Customers who ordered in every month of Q4

SQLeasyjunior · mid10 mindataset: ecommerce
#relational-division#aggregation

Table: orders(order_id, customer_id, order_date, status)

Return registered customers who placed at least one completed order in each of October, November and December 2024.

Output: customer_id. Order by customer_id.

Hint 1

Filter to Q4, then count the distinct months per customer.

Show solution
SELECT customer_id
FROM orders
WHERE status = 'completed'
AND customer_id IS NOT NULL
AND order_date >= DATE '2024-10-01' AND order_date < DATE '2025-01-01'
GROUP BY customer_id
HAVING COUNT(DISTINCT DATE_TRUNC('month', order_date)) = 3
ORDER BY customer_id;

"In every one of N buckets" is relational division. The GROUP BY … HAVING COUNT(DISTINCT bucket) = N pattern is the readable way to do it. COUNT(*) >= 3 is the usual wrong answer: three orders in October would pass.

Use a half-open date range (>= start AND < next start), not BETWEEN … '2024-12-31'. It stays correct if order_date ever becomes a timestamp.

Follow-ups

  • Generalize to "ordered in every month since signup". What changes?

    The required month count now varies per customer: count distinct order months since the signup month and compare them to the number of months between signup and now (inclusive). Watch the partial current month and customers who signed up mid-month.

  • Return customers who bought from every product category. Same pattern?

    Yes, it's the same relational-division pattern: group by customer, count distinct categories bought, and keep customers where that equals the total number of categories ((SELECT COUNT(*) FROM categories)).

Customers who never placed an order

SQLeasyjunior · mid10 mindataset: ecommerce
#anti-joins#null-traps

Tables:

  • customers(customer_id, name, country, signup_date)
  • orders(order_id, customer_id, order_date, status)

Guest checkouts are stored with customer_id = NULL.

Return every customer who has no orders at all, in any status.

Output: customer_id. Order by customer_id.

Hint 1

Try WHERE customer_id NOT IN (SELECT customer_id FROM orders) and look at the row count. Why?

Show solution
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
)
ORDER BY c.customer_id;

NOT IN returns zero rows here. x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL, and x <> NULL is unknown, so the whole condition is never true. The guest orders put a NULL in the list.

NOT EXISTS (or LEFT JOIN … WHERE o.order_id IS NULL) has no such trap. Prefer it by default.

What a strong answer covers

  • Explains why NOT IN returns no rows when the subquery contains a NULL (weight 2)

Follow-ups

  • Rewrite it as a LEFT JOIN. Which column must you test for NULL, and why that one?

    LEFT JOIN orders o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL. Test a column that is never NULL in a real match (the primary key order_id, or the join key itself). Testing a nullable column like status would wrongly include customers whose order happens to have a NULL there.

  • Which form is faster on your warehouse, and how would you check?

    Most modern optimizers turn both NOT EXISTS and the LEFT JOIN ... IS NULL form into the same anti-join, so they're usually equal. Check with EXPLAIN or the query profile on realistic data. Avoid NOT IN with a nullable subquery: a single NULL makes it return no rows.

Days between a customer's first and second order

SQLeasyjunior · mid15 mindataset: ecommerce
#window-functions#row-number

Table: orders(order_id, customer_id, order_date, status)

Consider only completed orders from registered customers (customer_id IS NOT NULL). For every customer with at least two such orders, return the dates of their first and second order and the number of days between them. If two orders share a date, the lower order_id comes first.

Output: customer_id, first_order_date, second_order_date, days_between. Order by customer_id.

Hint 1

Number each customer's orders, then put order 1 and order 2 on the same row.

Show solution
WITH numbered AS (
SELECT customer_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, order_id) AS n
FROM orders
WHERE status = 'completed' AND customer_id IS NOT NULL
)
SELECT f.customer_id,
f.order_date AS first_order_date,
s.order_date AS second_order_date,
DATE_DIFF('day', f.order_date, s.order_date) AS days_between
FROM numbered f
JOIN numbered s ON s.customer_id = f.customer_id AND s.n = 2
WHERE f.n = 1
ORDER BY f.customer_id;

ROW_NUMBER with a full tie-breaker (order_date, order_id) gives a stable "first" and "second". Then a self-join on n = 1 and n = 2 puts them side by side; the inner join drops customers with only one order, as asked.

LEAD(order_date) OVER (…) filtered to n = 1 is an equally good answer with no self-join.

Follow-ups

  • Return the median days-to-second-order per signup month. What would you watch out for with recent cohorts?

    Use PERCENTILE_CONT(0.5) (or MEDIAN) over days-to-second-order grouped by signup month. Recent cohorts are censored: customers who will order a second time haven't yet, so their median looks fast and the conversion looks low. Only compare cohorts at the same age, or report the share with a second order within N days.

  • Why does the tie-breaker matter for reproducible pipelines?

    Without a unique ordering (for example two orders at the same timestamp), ROW_NUMBER can pick a different row on each run, so outputs change between identical runs and tests flake. Add a unique column such as order_id to the ORDER BY.

Dialect notes

  • snowflake: `DATEDIFF(day, first_order_date, second_order_date)`. docs
  • bigquery: `DATE_DIFF(second_order_date, first_order_date, DAY)`. Note the argument order: end first. docs
  • sqlserver: `DATEDIFF(day, first_order_date, second_order_date)`. docs

Deduplicate replayed transactions

SQLeasyjunior · mid10 mindataset: payments
#deduplication#window-functions

Table: transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at)

The ingestion job sometimes replays events, so one txn_id can appear several times. Each copy has a different ingested_at. The copy with the latest ingested_at is the truth, because status can change between copies (for example pending → settled).

Count the transactions per status after deduplication.

Output: status, txn_count. Order by status.

Hint 1

Number the copies of each txn_id, newest first, and keep number 1.

Show solution
WITH latest AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
)
SELECT status, COUNT(*) AS txn_count
FROM latest
WHERE rn = 1
GROUP BY status
ORDER BY status;

SELECT DISTINCT doesn't work here, because the copies differ in status and ingested_at. You need "one row per key, chosen by a rule", which is ROW_NUMBER partitioned by the key and ordered by the rule.

Counting DISTINCT txn_id per status is a common wrong answer: a transaction that went from pending to settled would be counted in both.

What a strong answer covers

  • Explains why COUNT(DISTINCT txn_id) per status double-counts transactions whose status changed (weight 2)

Follow-ups

  • Two copies have the same ingested_at. How do you make the result deterministic?

    Add a unique tie-breaker after ingested_at in the ORDER BY: a source sequence or offset if you have one, otherwise a stable column such as the file name plus line number. If the copies are fully identical, any row is fine, but the order must still be deterministic.

  • How would you dedup incrementally each day instead of scanning the whole table?

    Only consider keys that appeared in today's batch: union today's rows with the existing latest rows for those keys, keep the newest per key, and MERGE the result into the deduplicated table. Partition by date so the lookups are cheap.

Dialect notes

  • snowflake: `QUALIFY ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) = 1` removes the CTE. docs

Choose a distribution key by measuring skew

SQLmediummid · senior20 mindataset: rides
#distribution-keys#data-skew#performance

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

You're moving trips to an MPP warehouse that spreads each table's rows across 8 slices by hashing a distribution key. Three candidates have been proposed: city, driver_id and trip_id.

Simulate it: for each candidate, assign every row to slice hash(key) % 8 and report how many slices receive rows, the row count of the fullest slice, and a skew factor = fullest slice ÷ the ideal per-slice count (total rows ÷ 8), rounded to 2 decimals. Use all trips, including cancelled ones.

Output: dist_key, slices_used, max_rows, skew. Order by dist_key.

Hint 1

One GROUP BY hash(col) % 8 per candidate, combined with UNION ALL, then aggregate per candidate.

Hint 2

Why can a key with 5 distinct values never use all 8 slices? What happens to rows where the key is NULL?

Show solution
WITH slices AS (
SELECT 'city' AS dist_key, hash(city) % 8 AS slice, COUNT(*) AS n
FROM trips GROUP BY 1, 2
UNION ALL
SELECT 'driver_id', hash(driver_id) % 8, COUNT(*)
FROM trips GROUP BY 1, 2
UNION ALL
SELECT 'trip_id', hash(trip_id) % 8, COUNT(*)
FROM trips GROUP BY 1, 2
)
SELECT dist_key,
COUNT(*) AS slices_used,
MAX(n) AS max_rows,
ROUND(MAX(n) * 8.0 / SUM(n), 2) AS skew
FROM slices
GROUP BY dist_key
ORDER BY dist_key;

In an MPP warehouse, a query is only as fast as its busiest slice, so the distribution key decides both balance and whether joins need data movement.

  • city has only 5 values, so at most 5 slices can hold rows. Here hash collisions leave just 3 in use, and one slice holds about 4× its fair share. Low-cardinality keys always skew.
  • driver_id has high cardinality but is NULL for cancelled trips with no driver. All NULLs hash to the same slice, which adds visible skew. NULL or default values in a key are a classic hidden hot spot.
  • trip_id is unique, so rows spread almost perfectly. But a unique key doesn't co-locate anything: joins to drivers or riders still move data between slices.

The real choice weighs balance against co-located joins: distribute the big fact on the key it's most often joined on (if that key is high-cardinality and rarely NULL), and replicate small dimensions to every slice (DISTSTYLE ALL in Redshift, REPLICATE in Synapse). Use even/round-robin distribution when there's no good join key.

What a strong answer covers

  • Explains that the slowest (fullest) slice bounds query time (weight 2)
  • Identifies low cardinality and NULL concentration as causes of skew (weight 3)
  • Weighs even distribution against co-located joins, and replicating small dimensions (weight 3)

Follow-ups

  • trips is joined to drivers in most queries. Which distribution would you pick for each table?

    Replicate the small drivers table to every slice (or distribute both on driver_id so the join is co-located), and distribute trips on driver_id if its skew is acceptable. Handle the NULL driver_id rows, for example by giving them a spread-out surrogate value, or choose even distribution for trips and rely on the replicated dimension.

  • How would you check skew on a real Redshift or Synapse table?

    In Redshift, SVV_TABLE_INFO.skew_rows gives the ratio of rows in the fullest slice to the emptiest. In Synapse dedicated pools, DBCC PDW_SHOWSPACEUSED shows rows per distribution across the 60 distributions. Also check query plans for data redistribution steps on joins.

Dialect notes

  • redshift: Distribution styles are `AUTO`, `EVEN`, `KEY` and `ALL`; `SVV_TABLE_INFO.skew_rows` is the ratio of rows in the fullest slice to the emptiest. docs
  • sqlserver: Azure Synapse dedicated SQL pools spread each table over 60 distributions using `HASH`, `ROUND_ROBIN` or `REPLICATE`; choose a hash column with many distinct values and few NULLs. docs

Three-step page funnel with step-to-step conversion

SQLmediummid · senior25 mindataset: events
#funnels#window-functions

Table: page_views(user_id, viewed_at, page)

Product wants a funnel: /docs → /pricing → /billing. A user reaches a step only if they viewed that page at or after the time they reached the previous step. Step 1 is the user's first /docs view.

Output: step, page, users, pct_of_previous, where pct_of_previous = users / users of the previous step rounded to 4 decimals (NULL for step 1). Order by step.

Hint 1

Find each user's first time at step 1, then the first step-2 view after it, and so on.

Hint 2

Counting users who viewed each page at all is not a funnel. Order matters.

Show solution
WITH step1 AS (
SELECT user_id, MIN(viewed_at) AS reached_at
FROM page_views
WHERE page = '/docs'
GROUP BY user_id
),
step2 AS (
SELECT s.user_id, MIN(p.viewed_at) AS reached_at
FROM step1 s
JOIN page_views p
ON p.user_id = s.user_id AND p.page = '/pricing' AND p.viewed_at >= s.reached_at
GROUP BY s.user_id
),
step3 AS (
SELECT DISTINCT s.user_id
FROM step2 s
JOIN page_views p
ON p.user_id = s.user_id AND p.page = '/billing' AND p.viewed_at >= s.reached_at
),
counts AS (
SELECT 1 AS step, '/docs' AS page, COUNT(*) AS users FROM step1
UNION ALL SELECT 2, '/pricing', COUNT(*) FROM step2
UNION ALL SELECT 3, '/billing', COUNT(*) FROM step3
)
SELECT step, page, users,
ROUND(users * 1.0 / LAG(users) OVER (ORDER BY step), 4) AS pct_of_previous
FROM counts
ORDER BY step;

Each step joins only the users who made the previous step, and only page views after the time they made it. Carrying reached_at forward is what enforces the order.

Taking MIN(viewed_at) at each step keeps the funnel as generous as possible: the earliest qualifying view gives the most time for the next step. Say this choice out loud, because "first /pricing after the last /docs" would give a different, also defensible, number.

What a strong answer covers

  • Enforces step order with timestamps, not just "viewed both pages" (weight 2)
  • States which occurrence (first/last) anchors each step and why (weight 1)

Follow-ups

  • Product wants the funnel to count only if all three steps happen within 7 days. What changes?

    For each user, find the first docs view, then the first pricing view after it, then the first billing view after that, and require billing to be within 7 days of the first step. Join each step on user_id with time conditions (or use window functions). Users who take longer drop out of later steps.

  • How would you build this as a dbt model that is cheap to refresh daily?

    Make it incremental: process only new events (with a lookback of at least 7 days, the funnel window), keep a per-user state table with each step's first timestamp, and merge on user_id. Partition by event date and aggregate from the state table.

Employees who earn more than their manager

SQLeasyjunior10 mindataset: ecommerce
#self-joins

Table: employees(employee_id, name, manager_id, department, salary, hired_date)

Return every employee whose salary is higher than their direct manager's.

Output: employee_id, salary, manager_id, manager_salary. Order by employee_id.

Hint 1

Join the table to itself: one copy plays "employee", the other plays "manager".

Show solution
SELECT e.employee_id, e.salary, e.manager_id, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.employee_id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.employee_id;

A self-join with clear aliases. The join condition m.employee_id = e.manager_id reads as "m is e's manager". The inner join drops the CEO, who has no manager, which is what we want here. Say so, so the interviewer knows it's deliberate.

Follow-ups

  • Include employees who earn more than any manager above them, not only the direct one.

    Use a recursive CTE that walks up the chain, producing (employee, ancestor manager) pairs, then keep employees whose salary is greater than at least one ancestor's (EXISTS or salary > MIN(ancestor salary)).

  • What index or clustering would you want if this table had 10 million rows?

    An index or clustering on employee_id (the join target, usually the primary key) and on manager_id. In a columnar warehouse it hardly matters at 10 million rows, because a hash join on a self-join is fast.

Check a month of feed files for missing, late and broken deliveries

SQLmediummid · senior20 mindataset: integration
#file-ingestion#data-quality#date-spine#slas

Tables:

  • feed_files(file_name, feed, business_date, received_at, declared_rows): one row per file received. declared_rows is the line count the sender put in the file's trailer.
  • customer_feed(file_name, line_no, ...): the lines actually loaded from each file.

The CRM sends one file per business day, due by 06:00 the next day. Produce an audit of March 2024 that lists every problem:

  • missing: no file for a business date (file_name is NULL).
  • duplicate: a second or later file for the same business date (the extra file).
  • late: a file received after 06:00 on the day after its business date.
  • row_count_mismatch: a file whose loaded line count differs from declared_rows.

A file can have more than one issue. Output: business_date, issue, file_name. Order by business_date, issue.

Hint 1

A missing file has no row anywhere. What do you need in order to notice an absence?

Hint 2

"Late" is relative to each file's own business date: build the deadline from it.

Hint 3

Compare declared counts with what was loaded, and remember a file could have zero loaded lines.

Show solution
WITH days AS (
SELECT CAST(d AS DATE) AS business_date
FROM generate_series(DATE '2024-03-01', DATE '2024-03-31', INTERVAL 1 DAY) AS t(d)
),
loaded AS (
SELECT file_name, COUNT(*) AS n FROM customer_feed GROUP BY file_name
),
ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY business_date ORDER BY received_at) AS nth
FROM feed_files
)
SELECT d.business_date, 'missing' AS issue, CAST(NULL AS VARCHAR) AS file_name
FROM days d
WHERE NOT EXISTS (SELECT 1 FROM feed_files f WHERE f.business_date = d.business_date)
UNION ALL
SELECT business_date, 'duplicate', file_name FROM ranked WHERE nth > 1
UNION ALL
SELECT business_date, 'late', file_name
FROM feed_files
WHERE received_at > CAST(business_date AS TIMESTAMP) + INTERVAL 30 HOUR
UNION ALL
SELECT f.business_date, 'row_count_mismatch', f.file_name
FROM feed_files f
LEFT JOIN loaded l ON l.file_name = f.file_name
WHERE f.declared_rows <> COALESCE(l.n, 0)
ORDER BY business_date, issue;

A file-based feed needs a control check before anyone trusts the data: did everything arrive, once, on time and complete?

  • Missing files need a calendar. You can't find an absent file by querying the files table; you compare against the dates you expected. Same idea as a date spine.
  • Duplicates: keep the first file per business date and flag the rest. In a real load, a resend should replace or be ignored, never be added on top, or every row is double counted.
  • Late: the deadline is per file: business date + 1 day + 6 hours (30 hours after midnight of the business date).
  • Completeness: a trailer or control count (declared_rows) catches truncated transfers. COALESCE(n, 0) keeps a file with no loaded lines from slipping through the comparison as NULL.

One query, one row per problem, makes a good daily alert: if it returns rows, someone looks.

What a strong answer covers

  • Uses a calendar of expected dates to find missing files (weight 3)
  • Flags duplicates (keeping the first) and computes lateness from each file's own deadline (weight 2)
  • Reconciles declared vs loaded rows, handling files with no loaded lines (weight 2)

Follow-ups

  • The 17 March file arrives on 20 March. How should the pipeline handle it?

    Load it into its own business date (17 March), not the day it arrived, then rerun the downstream steps for that date. Because loads are idempotent per business date, this is a normal backfill. Close the "missing" alert and record it as late.

  • How would you stop a resent file from being loaded twice?

    Track processed files in a load log keyed by business date and a content hash (or file name plus checksum). A resend for an already-loaded date either replaces that date's data atomically (delete-and-insert or partition overwrite) or is skipped if its hash matches. Never append blindly.

Validate a raw feed and count rejects by reason

SQLeasyjunior · mid15 mindataset: integration
#data-quality#reject-handling#file-ingestion

Table: customer_feed(file_name, line_no, customer_code, full_name, email, country, updated_at). Every column arrives as text, exactly as it was in the daily CSV files.

Before loading, each line is checked in this order, and gets the first reason that applies:

  1. missing_code: customer_code is empty or only spaces.
  2. bad_email: email isn't of the form something@something.something with no spaces.
  3. bad_country: country isn't exactly 2 characters.
  4. bad_timestamp: updated_at isn't a valid timestamp in the format YYYY-MM-DD HH:MM:SS.

Lines that pass every check are valid. Count the lines per outcome, across all files.

Output: outcome, rows. Order by outcome.

Hint 1

A CASE expression checks conditions in order and stops at the first match, which gives you the precedence for free.

Hint 2

How do you test whether text parses as a timestamp without the query failing on the bad ones? Some bad values look almost right.

Show solution
WITH checked AS (
SELECT CASE
WHEN TRIM(customer_code) = '' THEN 'missing_code'
WHEN NOT regexp_full_match(email, '[^@ ]+@[^@ ]+\.[^@ ]+') THEN 'bad_email'
WHEN LENGTH(country) <> 2 THEN 'bad_country'
WHEN TRY_STRPTIME(updated_at, '%Y-%m-%d %H:%M:%S') IS NULL THEN 'bad_timestamp'
ELSE 'valid'
END AS outcome
FROM customer_feed
)
SELECT outcome, COUNT(*) AS rows
FROM checked
GROUP BY outcome
ORDER BY outcome;

Validating raw text before it reaches typed tables is the core of an ETL load. Three details matter:

  • Precedence. One line can break several rules; give it one reason, in a defined order, so reject counts add up to the number of rejected lines.
  • Safe parsing. CAST(updated_at AS TIMESTAMP) would fail the whole query on the first bad value. TRY_STRPTIME (or TRY_CAST) returns NULL instead, and an explicit format catches values like 03/14/2024 10:22. It also rejects impossible dates such as 2024-02-30, which a simple pattern check would let through.
  • Trim before checking. A code of ' C0123 ' is valid after trimming; a code of ' ' is empty.

In production the rejected lines go to a reject table with the file name, line number and reason, so the source team can fix and resend them, and the reject rate is monitored per file.

What a strong answer covers

  • Applies the checks in the stated order with one reason per line (weight 2)
  • Parses timestamps safely (TRY_STRPTIME / TRY_CAST) and catches impossible dates (weight 2)
  • Explains where rejects go and how they are reported and reprocessed (weight 2)

Follow-ups

  • The source team fixes 20 rejected lines and resends them. How do you load them without duplicating the good lines?

    Make the load idempotent: upsert by the business key (customer_code) with the newest updated_at winning, so reloading a corrected line replaces or ignores rather than duplicates. Mark the original rejects as resolved, linked to the resend file, so reprocessing is traceable.

  • When should a reject rate stop the whole load instead of loading the valid rows?

    When the rate is far above normal (for example over 5% when it's usually 1%), or a critical field fails everywhere. That usually means a format change or a broken extract, and loading the rest would publish a partial, misleading picture. Set a threshold per feed and fail loudly above it.

Dialect notes

  • snowflake: `TRY_TO_TIMESTAMP(updated_at, 'YYYY-MM-DD HH24:MI:SS')` returns NULL instead of failing on bad values. docs
  • bigquery: `SAFE.PARSE_TIMESTAMP('%Y-%m-%d %H:%M:%S', updated_at)` returns NULL instead of an error. docs
  • sqlserver: `TRY_CONVERT(datetime2, updated_at, 120)` parses the ODBC canonical format and returns NULL on failure. docs

Daily EUR rate for January, filled forward over weekends

SQLmediummid · senior20 mindataset: payments
#date-spine#fill-forward#window-functions

Table: fx_rates(rate_date, currency, usd_rate). Rates are published on business days only; weekends and holidays have no row.

Build a row for every calendar day from 2024-01-01 to 2024-01-31 with the EUR rate in effect that day, which is the latest published rate on or before it. Flag days whose rate was carried forward.

Output: rate_date, usd_rate, is_carried_forward. Order by rate_date.

Hint 1

2024-01-01 is a holiday. Where does its rate come from?

Hint 2

LAST_VALUE(x IGNORE NULLS) over a date spine carries the last known value forward.

Show solution
WITH days AS (
-- start the spine before January so 1 January can inherit December's last rate
SELECT CAST(UNNEST(GENERATE_SERIES(DATE '2023-12-01', DATE '2024-01-31', INTERVAL 1 DAY)) AS DATE) AS d
),
eur AS (
SELECT rate_date, usd_rate FROM fx_rates WHERE currency = 'EUR'
),
filled AS (
SELECT days.d,
LAST_VALUE(eur.usd_rate IGNORE NULLS) OVER (
ORDER BY days.d ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS usd_rate,
eur.rate_date IS NULL AS is_carried_forward
FROM days
LEFT JOIN eur ON eur.rate_date = days.d
)
SELECT d AS rate_date, usd_rate, is_carried_forward
FROM filled
WHERE d >= DATE '2024-01-01'
ORDER BY d;

A date spine plus LAST_VALUE … IGNORE NULLS fills gaps with the last known value.

The trap is the first day. If the spine starts on 1 January, a holiday, there is nothing before it inside the window and the rate is NULL. Start the spine early enough to include the last rate before the range, then filter. A correlated "latest rate on or before" lookup avoids the issue entirely, at a higher cost per row.

A filled-forward daily rate table like this is what you'd materialize once, so every downstream conversion becomes a plain equi-join.

What a strong answer covers

  • Handles the first day of the range (spine starts earlier or as-of lookup) (weight 2)

Follow-ups

  • Materialize this for every currency and every day since 2010. How do you keep it updated daily?

    Materialize a table of (currency, date, rate, source_date) from a calendar cross-join with currencies, filled forward. Update it daily with an incremental model that appends new dates and re-fills a short recent window, because rates can arrive late or be corrected.

  • Finance restates a rate. Which downstream tables must be rebuilt?

    Every table that converted amounts with that rate after its date until the next actual rate: the filled-forward rate table, then the fact and aggregate tables that used it. Lineage plus storing source_date (or a rate version) on the converted rows tells you exactly which rows.

Dialect notes

  • snowflake: `LAST_VALUE(usd_rate) IGNORE NULLS OVER (…)`; the IGNORE NULLS goes after the parentheses. docs
  • bigquery: `LAST_VALUE(usd_rate IGNORE NULLS) OVER (…)`. docs
  • sqlserver: `IGNORE NULLS` for `LAST_VALUE` exists from SQL Server 2022 only. docs

Fix the inflated order count

SQLmediumjunior · mid15 mindataset: ecommerce
#fan-out-joins#aggregation

Tables:

  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

A teammate wrote this report of the top 10 customers by completed-order revenue. Revenue looks right, but order_count is too high:

SELECT o.customer_id,
       COUNT(o.order_id) AS order_count,
       SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'completed'
GROUP BY o.customer_id
ORDER BY revenue DESC
LIMIT 10;

Explain the bug and write a correct version. Ignore guest orders (customer_id IS NULL). Break revenue ties by lower customer_id.

Output: customer_id, order_count, revenue. Order by revenue descending, then customer_id.

Hint 1

How many rows does one order with 3 line items become after the join?

Show solution
WITH order_revenue AS (
SELECT order_id, SUM(quantity * unit_price) AS revenue
FROM order_items
GROUP BY order_id
)
SELECT o.customer_id,
COUNT(*) AS order_count,
SUM(r.revenue) AS revenue
FROM orders o
JOIN order_revenue r ON r.order_id = o.order_id
WHERE o.status = 'completed'
AND o.customer_id IS NOT NULL
GROUP BY o.customer_id
ORDER BY revenue DESC, o.customer_id
LIMIT 10;

This is a fan-out. Joining an order to its line items turns one order into one row per item, so COUNT(o.order_id) counts items, not orders. The revenue sum survives only because each item's revenue appears exactly once.

COUNT(DISTINCT o.order_id) fixes this query, but the more robust habit is to aggregate the child table to the parent's grain before joining. That keeps every later measure safe, including ones that live on the order itself (like shipping fee), which would be multiplied by the item count.

What a strong answer covers

  • Names the cause: the join multiplies each order by its number of line items (weight 2)
  • Explains why COUNT(DISTINCT) works here but breaks for order-level measures like shipping fee (weight 1)

Follow-ups

  • Add an order_discount column from orders to the report. Which version stays correct?

    The fixed version, which pre-aggregates items per order before joining. The original join repeats order_discount once per item, so summing it would inflate discounts exactly like the order count.

  • How would you catch fan-out bugs automatically in a dbt project?

    Add tests on grain: a unique test on each model's key, and row-count or sum reconciliation tests between a model and its source (for example total revenue must equal the sum of order items). Also use a model naming and documentation convention that states each model's grain.

Flag days with abnormal trip volume

SQLmediummid · senior25 mindataset: rides
#data-quality#anomaly-detection#date-spine#window-functions

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

You're adding a volume monitor to the trips pipeline. For every city and every day from 2024-02-01 to 2024-03-31, compare the number of completed trips (by the date of completed_at) with a baseline: the average daily completed trips in that city over the previous 7 days (not including the day itself).

Flag a city-day when the baseline is at least 3 (too little volume is just noise) and the day's count is below half the baseline or above double it. A day with no completed trips is a day with 0 trips, not a missing row.

Output: city, day, trips, baseline (baseline rounded to 2 decimals), flagged rows only. Order by city, day.

Hint 1

Which city-days have no row at all if you group the trips table, and what does that do to "the previous 7 rows"?

Hint 2

Build every (city, day) pair first, then left join the counts. Start the calendar early enough that February 1 has 7 days of history.

Hint 3

A window frame of ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING averages the 7 days before the current one.

Show solution
WITH days AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(DATE '2024-01-25', DATE '2024-03-31', INTERVAL 1 DAY) AS t(d)
),
cities AS (
SELECT DISTINCT city FROM trips
),
daily AS (
SELECT city, CAST(completed_at AS DATE) AS day, COUNT(*) AS trips
FROM trips
WHERE status = 'completed'
GROUP BY city, CAST(completed_at AS DATE)
),
filled AS (
SELECT c.city, d.day, COALESCE(x.trips, 0) AS trips
FROM cities c
CROSS JOIN days d
LEFT JOIN daily x ON x.city = c.city AND x.day = d.day
),
scored AS (
SELECT city, day, trips,
AVG(trips) OVER (
PARTITION BY city ORDER BY day
ROWS BETWEEN 7 PRECEDING AND 1 PRECEDING
) AS baseline
FROM filled
)
SELECT city, day, trips, ROUND(baseline, 2) AS baseline
FROM scored
WHERE day BETWEEN DATE '2024-02-01' AND DATE '2024-03-31'
AND baseline >= 3
AND (trips < 0.5 * baseline OR trips > 2 * baseline)
ORDER BY city, day;

The core of a volume monitor is a baseline and a tolerance. Here the baseline is the trailing 7-day mean and the tolerance is ×0.5 to ×2, with a minimum baseline so tiny volumes don't alert constantly.

The trap is missing days. Grouping trips only produces rows for days that had trips, so a day with zero trips (the most important anomaly a volume check exists for) never appears, and ROWS 7 PRECEDING silently looks further back than 7 days. A city × date spine with COALESCE(count, 0) fixes both. Without it, Denver's two zero-trip days disappear from the output.

The calendar starts on January 25 so the first reported day already has a full 7-day history. The frame ends at 1 PRECEDING so today's value doesn't pull its own baseline toward itself.

What a strong answer covers

  • Builds a city × date spine and treats missing days as zero (weight 3)
  • Baseline excludes the current day (frame ends at 1 PRECEDING) and starts early enough for a full window (weight 2)
  • Explains the minimum-volume floor and the trade-off of fixed thresholds (noise vs missed incidents) (weight 2)

Follow-ups

  • Weekends always look like anomalies against a weekday-heavy baseline. How would you fix that?

    Compare each day with the same weekday in previous weeks (for example the median of the last 4 Mondays), or model weekly seasonality explicitly. That removes the predictable weekly pattern so only real surprises alert.

  • Fixed ×0.5 / ×2 thresholds are either noisy or blind depending on the city. What would you use instead?

    A threshold scaled to each series' own variability: a z-score against a rolling mean and standard deviation, or a robust version with the median and MAD so past outliers don't inflate the band. Tune the threshold on past incidents to balance false alerts against missed ones.

Longest login streak per user

SQLmediummid · senior20 mindataset: events
#gaps-and-islands#window-functions

Table: logins(user_id, login_ts). A user can log in many times a day; each login is one row.

For each user who logged in at least once, return their longest streak of consecutive calendar days with at least one login.

Output: user_id, streak_days. Order by user_id.

Hint 1

Reduce to one row per user per day first.

Hint 2

In a run of consecutive dates, the date minus its row number is the same value.

Show solution
WITH login_days AS (
SELECT DISTINCT user_id, CAST(login_ts AS DATE) AS login_date
FROM logins
),
grouped AS (
SELECT user_id,
login_date - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) AS INTEGER) AS streak_key
FROM login_days
),
streaks AS (
SELECT user_id, streak_key, COUNT(*) AS streak_days
FROM grouped
GROUP BY user_id, streak_key
)
SELECT user_id, MAX(streak_days) AS streak_days
FROM streaks
GROUP BY user_id
ORDER BY user_id;

This is the classic gaps-and-islands trick. Number each user's days 1, 2, 3, … in date order. Inside a streak, the date and the number both go up by 1 each step, so date - number stays constant. A gap in the dates changes it. That constant labels each island; count its rows and take the max.

Skipping the DISTINCT step is the usual bug: two logins on one day give two row numbers for one date and split the streak.

What a strong answer covers

  • Reduces to one row per user per day before numbering (weight 2)
  • Explains why date minus row number is constant within a streak (weight 1)

Follow-ups

  • How would you compute the current streak (ending today) instead of the longest?

    Compute each user's islands as usual, then keep the island whose last date is today (or yesterday, if today isn't over yet). Users with no such island have a current streak of 0.

  • How would you maintain this incrementally in a daily pipeline?

    Keep a per-user state table with current_streak and last_login_date. Each day: users who logged in today continue their streak (+1 if their last login was yesterday) or start a new one at 1. Update longest_streak as GREATEST(longest, current).

Dialect notes

  • snowflake: `login_date - rn` works on DATE values; `DATEADD(day, -rn, login_date)` is the explicit form most teams prefer. docs
  • bigquery: Use `DATE_SUB(login_date, INTERVAL rn DAY)`. docs
  • sqlserver: Use `DATEADD(day, -rn, login_date)`; `date - int` is not valid for the `date` type. docs

Further reading

Accounts with 3 or more failed transactions in a row

SQLhardsenior25 mindataset: payments
#gaps-and-islands#deduplication

Table: transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at). It contains replays; use only the latest copy (ingested_at) of each txn_id.

Order each account's transactions by txn_ts, then txn_id. Find accounts whose longest run of consecutive failed transactions is 3 or more.

Output: account_id, longest_failed_streak. Order by longest_failed_streak descending, then account_id.

Hint 1

A row number over all of an account's transactions minus a row number over only its failed ones is constant within a run.

Show solution
WITH latest AS (
SELECT account_id, txn_id, txn_ts, status
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
) t
WHERE rn = 1
),
numbered AS (
SELECT account_id, status,
ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY txn_ts, txn_id)
- ROW_NUMBER() OVER (PARTITION BY account_id, status ORDER BY txn_ts, txn_id) AS island
FROM latest
),
runs AS (
SELECT account_id, island, COUNT(*) AS run_length
FROM numbered
WHERE status = 'failed'
GROUP BY account_id, island
)
SELECT account_id, MAX(run_length) AS longest_failed_streak
FROM runs
GROUP BY account_id
HAVING MAX(run_length) >= 3
ORDER BY longest_failed_streak DESC, account_id;

This is the "difference of row numbers" version of gaps-and-islands, for runs of a value rather than consecutive dates. Across all rows the first row number goes 1, 2, 3, …; the second counts only within the status. Inside a run of failed both go up together, so their difference is constant. Any non-failed row in between bumps the first counter only and starts a new island.

The tie-breaker on txn_id matters: two transactions at the same timestamp would otherwise be ordered arbitrarily, and streaks could change between runs.

What a strong answer covers

  • Uses the row-number difference (or LAG + running sum) to label runs (weight 2)
  • Dedups replays first and adds a deterministic tie-breaker (weight 1)

Follow-ups

  • Make it a streaming rule that alerts on the third consecutive failure. What state do you keep per account?

    Per account: a counter of consecutive failures (and maybe the time of the first one). On a failure, increment it and alert when it reaches 3. On a success, reset it to 0. Events must be processed in order per account, so key the stream by account.

  • Rewrite it with LAG and a running SUM. Which is easier to explain in an interview?

    Use LAG to flag where the status changes, a running SUM of those flags as a group id, then count the rows per group. The row-number difference trick is shorter but harder to explain; the LAG version reads step by step, which is clearer in an interview.

Median and 90th percentile fare per city

SQLeasyjunior · mid10 mindataset: rides
#percentiles#aggregation

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

For completed trips, return per city the number of trips, the median fare and the 90th percentile fare (continuous, interpolated), both rounded to 2 decimals.

Output: city, trips, median_fare, p90_fare. Order by city.

Hint 1

Look for an ordered-set aggregate: PERCENTILE_CONT(fraction) WITHIN GROUP (ORDER BY …).

Show solution
SELECT city,
COUNT(*) AS trips,
ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY fare), 2) AS median_fare,
ROUND(PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY fare), 2) AS p90_fare
FROM trips
WHERE status = 'completed'
GROUP BY city
ORDER BY city;

PERCENTILE_CONT interpolates between the two middle values; PERCENTILE_DISC returns an actual value from the data. For money, either can be right. Say which one the business wants.

Why median at all? Fares are skewed: a few long airport trips pull the mean up, while the median describes a typical trip.

Follow-ups

  • The table has 5 billion rows. How would you compute an approximate p90, and what's the trade-off?

    Use the engine's approximate percentile function (APPROX_QUANTILES, APPROX_PERCENTILE, t-digest or KLL sketches). It's much faster and uses little memory, but the result has a small, bounded error, and some sketches aren't deterministic across runs.

  • How do you compute a median in an engine that has no percentile function?

    Number the rows per city with ROW_NUMBER ordered by fare, along with the count per city, then average the middle one or two rows: rn IN (FLOOR((n + 1) / 2.0), CEIL((n + 1) / 2.0)).

Dialect notes

  • snowflake: `PERCENTILE_CONT … WITHIN GROUP` works as an aggregate; `MEDIAN(fare)` is a shortcut. docs
  • bigquery: `PERCENTILE_CONT(fare, 0.5) OVER (PARTITION BY city)` is analytic-only. For a grouped result use `APPROX_QUANTILES(fare, 100)[OFFSET(50)]`, or the analytic form plus DISTINCT. docs
  • sqlserver: `PERCENTILE_CONT` requires an `OVER` clause (window function only), so pair it with `DISTINCT` or a subquery to get one row per city. docs

Month-end account balances (a semi-additive measure)

SQLhardmid · senior30 mindataset: payments
#semi-additive-measures#periodic-snapshot#date-spine#window-functions

Tables:

  • transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at): contains replays; the copy with the latest ingested_at per txn_id is the truth.
  • accounts(account_id, customer_name, country, currency, opened_date)

Finance wants a monthly balance report for USD accounts. An account's balance changes only through its settled transactions: a payment adds amount, a refund subtracts it, and transfers are ignored. The month-end balance is the sum of those changes from the account's first settled change up to the end of the month.

For each month of 2024, report how many accounts have a balance (any account whose first settled change is on or before that month, even if nothing happened to it that month), their total month-end balance, and the average month-end balance per account, rounded to 2 decimals.

Output: month, accounts, total_balance, avg_balance (month = first day of the month). Order by month.

Hint 1

Deduplicate first, then compute each account's net change per month.

Hint 2

An account with no transactions in March still has a balance in March. What table gives it a row?

Hint 3

Balances add up across accounts, but not across months. Which window turns monthly changes into a balance?

Show solution
WITH latest AS (
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
) t
WHERE rn = 1
),
flows AS (
SELECT l.account_id,
CAST(DATE_TRUNC('month', l.txn_ts) AS DATE) AS month,
SUM(CASE WHEN l.txn_type = 'payment' THEN l.amount ELSE -l.amount END) AS net
FROM latest l
JOIN accounts a ON a.account_id = l.account_id
WHERE a.currency = 'USD'
AND l.status = 'settled'
AND l.txn_type IN ('payment', 'refund')
GROUP BY l.account_id, CAST(DATE_TRUNC('month', l.txn_ts) AS DATE)
),
months AS (
SELECT CAST(m AS DATE) AS month
FROM generate_series(DATE '2024-01-01', DATE '2024-12-01', INTERVAL 1 MONTH) AS t(m)
),
firsts AS (
SELECT account_id, MIN(month) AS first_month FROM flows GROUP BY account_id
),
grid AS (
SELECT f.account_id, m.month
FROM firsts f
JOIN months m ON m.month >= f.first_month
),
balances AS (
SELECT g.account_id, g.month,
SUM(COALESCE(fl.net, 0)) OVER (PARTITION BY g.account_id ORDER BY g.month) AS balance
FROM grid g
LEFT JOIN flows fl ON fl.account_id = g.account_id AND fl.month = g.month
)
SELECT month,
COUNT(*) AS accounts,
SUM(balance) AS total_balance,
ROUND(AVG(balance), 2) AS avg_balance
FROM balances
GROUP BY month
ORDER BY month;

A balance is a semi-additive measure: you can add balances across accounts on the same date, but never across time. Adding January's and February's balance means nothing. The warehouse pattern is a periodic snapshot: one row per account per month, holding the balance at month end.

Building it from transactions needs two things:

  1. A running sum per account (SUM(net) OVER (PARTITION BY account_id ORDER BY month)) to turn monthly changes into a balance.
  2. An account × month grid. Without it, an account with no activity in a month has no row, so it drops out of accounts and avg_balance. That's the common wrong answer here: the totals look plausible, but the account count dips in quiet months and the averages are wrong.

The grid starts at each account's first settled change, so accounts don't appear before they have a balance. Deduplication comes first, as always with this table.

What a strong answer covers

  • Explains semi-additive measures: balances add across accounts, not across time (weight 2)
  • Builds an account × month grid so accounts without activity keep their balance (weight 3)
  • Uses a running sum per account and deduplicates replays first (weight 2)

Follow-ups

  • Finance also wants the average daily balance per month. What changes?

    You need a daily grain: an account × day grid with the running balance per day, then the average over the days of each month (counting days before the first change as no balance). It's far bigger, so in a warehouse you'd build it as a daily snapshot table incrementally rather than on the fly.

  • How would you store this so dashboards stay fast for 10 million accounts?

    Materialize the monthly (or daily) snapshot as a fact table, partitioned by month and built incrementally: next month's balance is last month's balance plus the month's net change. Dashboards then read the snapshot instead of recomputing from transactions.

Dialect notes

  • redshift: Redshift lists `GENERATE_SERIES()` among unsupported PostgreSQL functions, so build the month grid from a calendar dimension table (or a recursive CTE) instead. docs

Month-over-month revenue growth

SQLeasyjunior · mid15 mindataset: ecommerce
#period-over-period#window-functions

Tables:

  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

For each calendar month, return completed-order revenue, the previous month's revenue, and the growth rate (revenue - prev_revenue) / prev_revenue rounded to 4 decimals. The first month has NULL for both.

Output: month (first day of the month), revenue, prev_revenue, pct_change. Order by month.

Hint 1

Aggregate to months first, then LAG over the monthly rows.

Show solution
WITH monthly AS (
SELECT CAST(DATE_TRUNC('month', o.order_date) AS DATE) AS month,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'completed'
GROUP BY 1
),
with_prev AS (
SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly
)
SELECT month,
revenue,
prev_revenue,
ROUND(CAST(revenue - prev_revenue AS DOUBLE) / prev_revenue, 4) AS pct_change
FROM with_prev
ORDER BY month;

LAG gives "the previous row", not "the previous month". That's the same thing here only because every month has orders. If a month could be empty, build a month spine first, or the growth rate silently compares March to January.

Cast before dividing. Integer or fixed-scale decimal division can truncate in some engines.

What a strong answer covers

  • Notes that LAG means previous row, and a missing month would break it (month spine) (weight 2)

Follow-ups

  • Change it to year-over-year by month. What does LAG need now?

    LAG(revenue, 12) over months ordered by month. That only works if every month is present, so build from a month spine. Alternatively, join each month to the same month of the previous year.

  • Finance wants growth by category too. Where does PARTITION BY go?

    Group by month and category, then use LAG(revenue) OVER (PARTITION BY category ORDER BY month), so each category is compared with its own previous month.

Daily revenue with a month-to-date running total

SQLeasyjunior · mid15 mindataset: ecommerce
#running-totals#window-functions

Tables:

  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

For every day that has at least one completed order (status = 'completed'), return that day's revenue (quantity * unit_price) and a running total that resets on the first day of each month.

Output: order_date, revenue, month_to_date_revenue. Order by order_date.

Hint 1

Build daily revenue first; then a window SUM over it.

Hint 2

What do you partition by so the total resets each month?

Show solution
WITH daily AS (
SELECT o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'completed'
GROUP BY o.order_date
)
SELECT order_date,
revenue,
SUM(revenue) OVER (
PARTITION BY DATE_TRUNC('month', order_date)
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS month_to_date_revenue
FROM daily
ORDER BY order_date;

Partition by month to reset the total and order by date to accumulate it.

Write the frame explicitly. With ORDER BY and no frame, most engines default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats rows with equal sort keys as one peer group. Here dates are unique after the aggregation, so both give the same answer, but on raw rows with duplicate dates they don't.

Follow-ups

  • The business wants every calendar day listed, including days with zero revenue. What do you add?

    A date spine: generate every date in the range, LEFT JOIN the daily revenue, use COALESCE(revenue, 0), then run the running total over the spine.

  • What's the difference between ROWS and RANGE frames, and when does it change the result?

    ROWS counts physical rows. RANGE uses the ORDER BY value, so rows with equal values (peers) are included together. They differ when the ordering has ties: with RANGE, a running total gives every tied row the same total. With time intervals, RANGE also handles missing days.

Dialect notes

  • bigquery: Argument order is reversed: `DATE_TRUNC(order_date, MONTH)`. docs
  • sqlserver: `DATETRUNC(month, order_date)` exists from SQL Server 2022. On older versions use `DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1)`. docs

Reporting depth and management path for every employee

SQLmediummid · senior20 mindataset: ecommerce
#recursive-ctes#hierarchies

Table: employees(employee_id, name, manager_id, department, salary, hired_date). The CEO has manager_id = NULL.

For every employee, return their depth in the org chart (CEO = 0) and the path of employee IDs from the CEO down to them, joined with > (for example 1>4>17).

Output: employee_id, depth, path. Order by employee_id.

Hint 1

Start from the CEO (the anchor), then repeatedly join employees whose manager is already in the result.

Show solution
WITH RECURSIVE chain AS (
SELECT employee_id, 0 AS depth, CAST(employee_id AS VARCHAR) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, c.depth + 1, c.path || '>' || CAST(e.employee_id AS VARCHAR)
FROM employees e
JOIN chain c ON e.manager_id = c.employee_id
)
SELECT employee_id, depth, path
FROM chain
ORDER BY employee_id;

A recursive CTE has an anchor (the CEO) and a recursive step that joins the next level onto rows already found. It stops when a step adds no rows.

Two things to mention: cast the path to a string type wide enough to grow (some engines fix the column type from the anchor), and guard against cycles in dirty HR data, for example with a depth limit or by checking that the path doesn't already contain the ID.

What a strong answer covers

  • Names the anchor and recursive members and the stop condition (weight 2)
  • Mentions cycle protection for bad data (depth limit or path check) (weight 1)

Follow-ups

  • Return, for each manager, the total headcount under them (all levels). How?

    Use a recursive CTE producing every (manager, descendant) pair, then group by manager and count descendants. Exclude the manager themselves unless you want to count them.

  • How would you store this hierarchy so the dashboard doesn't recurse on every query?

    Precompute a closure table (ancestor, descendant, depth) or a materialized path column, rebuilt when the org changes, which is rare. Dashboards then answer headcount and path questions with a simple join or a LIKE on the path.

Dialect notes

  • sqlserver: Write `WITH chain AS (…)` without the `RECURSIVE` keyword; recursion is implied. Default max recursion is 100 (`OPTION (MAXRECURSION n)`). docs
  • snowflake: `WITH RECURSIVE` works; `CONNECT BY` is an alternative syntax for hierarchies. docs
  • bigquery: Needs `WITH RECURSIVE` explicitly. docs

Drivers with overlapping trips

SQLmediummid · senior20 mindataset: rides
#interval-overlap#self-joins

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

A driver can't do two trips at once, so overlapping completed trips point to a data problem (or fraud). Two trips overlap if one starts before the other ends: treat each trip as the half-open interval [requested_at, completed_at).

For each driver with at least one overlapping pair of completed trips, return the number of overlapping pairs.

Output: driver_id, overlapping_pairs. Order by overlapping_pairs descending, then driver_id.

Hint 1

Two intervals [a1, a2) and [b1, b2) overlap when a1 < b2 AND b1 < a2.

Hint 2

Join each trip to the driver's other trips, counting each pair once.

Show solution
WITH done AS (
SELECT trip_id, driver_id, requested_at, completed_at
FROM trips
WHERE status = 'completed'
)
SELECT a.driver_id, COUNT(*) AS overlapping_pairs
FROM done a
JOIN done b
ON b.driver_id = a.driver_id
AND a.trip_id < b.trip_id
AND a.requested_at < b.completed_at
AND b.requested_at < a.completed_at
GROUP BY a.driver_id
ORDER BY overlapping_pairs DESC, a.driver_id;

The overlap test a.start < b.end AND b.start < a.end covers every case (partial overlap, containment, identical intervals) in one condition. Using < instead of <= makes back-to-back trips (one ends at 10:00, the next starts at 10:00) not count, which is what half-open intervals mean.

a.trip_id < b.trip_id counts each pair once and stops a trip matching itself.

This self-join is quadratic per driver. At scale, sort each driver's trips and compare each one to the previous end (LAG(completed_at)). That finds adjacent overlaps in linear time.

What a strong answer covers

  • States the overlap condition correctly, including the boundary (half-open) (weight 2)
  • Counts each pair once (a.id < b.id) and mentions the quadratic cost (weight 1)

Follow-ups

  • Find the maximum number of trips any driver had in progress at the same moment.

    Turn each trip into two events, +1 at start and −1 at end, then run a running sum ordered by time per driver (process ends before starts at the same instant). The maximum running sum is the most simultaneous trips.

  • How would you turn this into a data quality test that runs after every load?

    Write the overlap query as a test that must return zero rows (a dbt singular test), and run it after each load on the newly loaded window, failing or warning with the offending trip ids.

Measure a data freshness SLA from ingestion timestamps

SQLmediummid · senior20 mindataset: payments
#data-quality#slas#freshness#deduplication

Table: transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at)

Each txn_id arrives as one or more copies. Many transactions first arrive as pending and get a later copy with their final status (settled or failed). Some copies are replays: the same final status ingested again later.

The finance team's SLA: a transaction should reach the warehouse with a final status within 24 hours of txn_ts. A transaction reaches finality when its first non-pending copy is ingested. A transaction that is still only pending has missed the SLA.

For each day of txn_ts in June 2024, report the number of transactions, how many reached finality within 24 hours, and that share as a percentage rounded to 1 decimal.

Output: day, txns, final_within_24h, pct_within_sla. Order by day.

Hint 1

Reduce to one row per txn_id first. What timestamp marks finality, and why not the latest copy's?

Hint 2

Transactions that never got a final copy must stay in the denominator.

Show solution
WITH per_txn AS (
SELECT txn_id,
MIN(txn_ts) AS txn_ts,
MIN(CASE WHEN status <> 'pending' THEN ingested_at END) AS final_at
FROM transactions
GROUP BY txn_id
)
SELECT CAST(txn_ts AS DATE) AS day,
COUNT(*) AS txns,
SUM(CASE WHEN final_at <= txn_ts + INTERVAL 24 HOUR THEN 1 ELSE 0 END) AS final_within_24h,
ROUND(100.0 * SUM(CASE WHEN final_at <= txn_ts + INTERVAL 24 HOUR THEN 1 ELSE 0 END)
/ COUNT(*), 1) AS pct_within_sla
FROM per_txn
WHERE txn_ts >= TIMESTAMP '2024-06-01' AND txn_ts < TIMESTAMP '2024-07-01'
GROUP BY CAST(txn_ts AS DATE)
ORDER BY day;

A freshness SLA is measured from when the data became correct in the warehouse, so pick the right event per key: the first non-pending copy (MIN over non-pending ingested_at). Using the latest copy is the common wrong answer: replays arrive later and make the pipeline look slower than it was.

Completeness matters as much as latency. A transaction stuck in pending has final_at = NULL. The comparison NULL <= … isn't true, so it counts as a miss while staying in COUNT(*). Filtering to rows with a final status first would quietly inflate the SLA.

Reporting by day of txn_ts (not by ingestion day) answers "how complete is each business day", which is what finance reads.

What a strong answer covers

  • Uses the first non-pending ingestion per txn_id, not the latest copy (replays) (weight 3)
  • Keeps never-finalized transactions in the denominator as SLA misses (weight 2)
  • Explains how this becomes an alerting metric (target, window, who is paged) (weight 2)

Follow-ups

  • June 30 looks worse than June 2 even with no incident. Why, and how do you report it fairly?

    Recent days are still maturing: transactions from the last 24 hours haven't had their full SLA window yet. Report only days whose SLA window has closed (txn date + 1 day < now), or mark the latest days as provisional.

  • How would you turn this into an alert instead of a report?

    Compute the metric on a schedule for each day as soon as its window closes, compare it with an SLO (for example 95% within 24 hours), and alert the owning team when it breaches, with a link to the affected transactions. Track the error budget over a month instead of paging on every bad day.

Pivot ratings into driver and rider columns

SQLeasyjunior · mid10 mindataset: rides
#pivot#conditional-aggregation#null-traps

Tables:

  • trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)
  • ratings(trip_id, rated_by, score): rated_by = 'rider' means the rider rated the driver; 'driver' means the driver rated the rider.

Return one row per city with the average rating of drivers, the average rating of riders (both rounded to 2 decimals), and the total number of ratings.

Output: city, avg_driver_rating, avg_rider_rating, ratings. Order by city.

Hint 1

One pass, two conditional averages.

Hint 2

What does ELSE 0 do to an average?

Show solution
SELECT t.city,
ROUND(AVG(CASE WHEN r.rated_by = 'rider' THEN r.score END), 2) AS avg_driver_rating,
ROUND(AVG(CASE WHEN r.rated_by = 'driver' THEN r.score END), 2) AS avg_rider_rating,
COUNT(*) AS ratings
FROM ratings r
JOIN trips t ON t.trip_id = r.trip_id
GROUP BY t.city
ORDER BY t.city;

Conditional aggregation is the portable pivot. Leave out the ELSE: the CASE returns NULL for the other direction, and AVG skips NULLs. Writing ELSE 0 would count every rating of the other kind as a zero and drag both averages down. That's a classic silent bug.

Read the direction carefully: rated_by = 'rider' is a rating of the driver.

What a strong answer covers

  • Explains why ELSE 0 would corrupt the averages (AVG ignores NULLs) (weight 2)

Follow-ups

  • Add a column for the share of trips that got no rating at all. Which join do you need now?

    Start from trips and LEFT JOIN ratings, because trips with no rating don't appear in ratings. Then compute AVG(CASE WHEN no rating THEN 1.0 ELSE 0 END) per city over distinct trips (aggregate per trip first if a trip can have two ratings).

  • When would you use the engine's PIVOT operator instead, and what does it cost you?

    When the engine supports it and the pivot values are known and fixed, PIVOT is shorter. It's less portable across dialects, needs the value list hardcoded, and is harder to combine with several aggregates than conditional aggregation with CASE.

Dialect notes

  • snowflake: `PIVOT (AVG(score) FOR rated_by IN ('rider', 'driver'))` is available, but the value list must be known up front (or use `ANY`). docs
  • bigquery: `PIVOT(AVG(score) FOR rated_by IN ('rider', 'driver'))` in the FROM clause. docs

Revenue by the customer's country at order time vs today

SQLhardsenior · lead30 mindataset: ecommerce
#point-in-time-joins#scd-type-2

Tables:

  • customers(customer_id, name, country, signup_date): country is the current country.
  • customer_addresses(customer_id, country, effective_date): change log, "from this date the customer lives in this country".
  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

Finance reports revenue by where the customer lived when they ordered. Marketing has been using the current country. Show both side by side for completed orders from registered customers.

Output: country, revenue_at_order_time, revenue_by_current_country (0 where a country has none). Order by country.

Hint 1

For each order, find the latest address row with effective_date <= order_date.

Hint 2

A country can appear in one view and not the other. Which join keeps both?

Show solution
WITH order_revenue AS (
SELECT o.order_id, o.customer_id, o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'completed' AND o.customer_id IS NOT NULL
GROUP BY o.order_id, o.customer_id, o.order_date
),
at_order_time AS (
SELECT (
SELECT a.country
FROM customer_addresses a
WHERE a.customer_id = r.customer_id AND a.effective_date <= r.order_date
ORDER BY a.effective_date DESC
LIMIT 1
) AS country,
r.revenue
FROM order_revenue r
),
historical AS (
SELECT country, SUM(revenue) AS revenue FROM at_order_time GROUP BY country
),
current_view AS (
SELECT c.country, SUM(r.revenue) AS revenue
FROM order_revenue r
JOIN customers c ON c.customer_id = r.customer_id
GROUP BY c.country
)
SELECT COALESCE(h.country, c.country) AS country,
COALESCE(h.revenue, 0) AS revenue_at_order_time,
COALESCE(c.revenue, 0) AS revenue_by_current_country
FROM historical h
FULL OUTER JOIN current_view c ON c.country = h.country
ORDER BY country;

This is a point-in-time join, the main reason SCD Type 2 exists. Each order needs the version of the customer that was valid on the order date. The correlated subquery is the portable way to do it. In a warehouse model you would precompute valid_from / valid_to once (see the SCD2 question) and join on order_date >= valid_from AND order_date < valid_to.

Both views must total the same revenue, since only the country attribution moves. That makes a cheap sanity check worth mentioning.

Aggregate items to the order first, so the address lookup runs once per order, not once per line item.

What a strong answer covers

  • Picks the address version valid on the order date (latest effective_date <= order_date) (weight 2)
  • Keeps countries present in only one view (FULL OUTER JOIN or union) and zero-fills (weight 1)
  • Suggests a reconciliation check: both columns sum to the same total (weight 1)

Follow-ups

  • With 2 billion orders, the correlated subquery is too slow. Rewrite it with an SCD2 table and a range join, or an ASOF JOIN.

    Build the address history as SCD2 rows with valid_from and valid_to (using LEAD on effective_date), then join orders ON customer_id AND order_date >= valid_from AND order_date < valid_to. Engines with ASOF JOIN (DuckDB, Snowflake) do this match directly and efficiently.

  • The fact table stores customer_key at load time instead. What are the pros and cons versus joining on dates at query time?

    Storing the key at load time makes queries simple and fast and fixes history as it was loaded. But backdated corrections to the address won't be reflected unless you reload. Joining on dates at query time is always correct against the latest history, but costs a range join on every query.

Dialect notes

  • snowflake: `ASOF JOIN customer_addresses a MATCH_CONDITION(r.order_date >= a.effective_date) ON r.customer_id = a.customer_id` replaces the correlated subquery. docs

Rolling 28-day active users for each day of December

SQLmediummid · senior20 mindataset: events
#rolling-distinct-counts#date-spine

Table: logins(user_id, login_ts)

For each day from 2024-12-01 to 2024-12-31, count the distinct users who logged in at least once during the 28 days ending on that day (the day itself and the 27 before it).

Output: activity_date, active_users_28d. Order by activity_date.

Hint 1

Most engines don't allow COUNT(DISTINCT …) as a window function. You need a join instead.

Hint 2

Join each day to the logins that fall inside its window.

Show solution
WITH days AS (
SELECT CAST(UNNEST(GENERATE_SERIES(DATE '2024-12-01', DATE '2024-12-31', INTERVAL 1 DAY)) AS DATE) AS activity_date
),
login_days AS (
SELECT DISTINCT user_id, CAST(login_ts AS DATE) AS login_date
FROM logins
)
SELECT d.activity_date, COUNT(DISTINCT l.user_id) AS active_users_28d
FROM days d
LEFT JOIN login_days l
ON l.login_date BETWEEN d.activity_date - 27 AND d.activity_date
GROUP BY d.activity_date
ORDER BY d.activity_date;

A sliding window of distinct users can't be built by adding daily counts: a user active on 5 of the 28 days would be counted 5 times. So each output day joins to the raw activity in its window and counts distinct users there.

Reducing logins to one row per user per day first shrinks the join a lot. At scale, the next steps are per-day HyperLogLog sketches merged over the window, or a per-user "last active date" table that turns the count into a range filter.

What a strong answer covers

  • Explains why summing daily actives over 28 days double-counts (weight 2)
  • Mentions a scalable approach (pre-aggregated user-days, HLL sketches) (weight 1)

Follow-ups

  • Compute this for every day of the year on 2 billion login rows. What do you precompute?

    Precompute one row per user per active day (deduplicated), or a daily bitmap or HyperLogLog sketch of users. Then a 28-day window unions 28 small daily sets or merges 28 sketches instead of rescanning 2 billion rows each day.

  • How do DAU / MAU ratios behave when you change the window from 28 to 30 days?

    A longer window counts more users, so MAU rises and DAU/MAU falls. 30-day windows also include a different number of weekends depending on the date, which adds day-of-week noise. 28 days contains exactly four of each weekday, which keeps the ratio stable.

Dialect notes

  • bigquery: `HLL_COUNT.MERGE` over daily `HLL_COUNT.INIT` sketches gives approximate rolling distinct counts cheaply. docs
  • snowflake: `HLL_ACCUMULATE` per day and `HLL_COMBINE` over the window are the approximate equivalent. docs

Average session length by plan

SQLeasyjunior10 mindataset: events
#aggregation#date-functions

Tables:

  • users(user_id, signup_date, country, plan)
  • sessions(session_id, user_id, started_at, ended_at, device)

For each plan, return the number of sessions and the average session length in minutes (rounded to 2 decimals).

Output: plan, sessions, avg_minutes. Order by plan.

Hint 1

Turn each session into a number of seconds, then average and divide by 60.

Show solution
SELECT u.plan,
COUNT(*) AS sessions,
ROUND(AVG(EPOCH(s.ended_at) - EPOCH(s.started_at)) / 60, 2) AS avg_minutes
FROM sessions s
JOIN users u ON u.user_id = s.user_id
GROUP BY u.plan
ORDER BY u.plan;

Convert the duration to seconds before averaging, then to minutes. Averaging whole minutes (DATEDIFF(minute, …)) would throw away up to 59 seconds per session, and in some engines it counts minute boundaries crossed, not elapsed time.

The join is safe from fan-out because each session has exactly one user.

Follow-ups

  • Some sessions have ended_at before started_at because of clock skew. How do you detect and handle them?

    Count them first: WHERE ended_at < started_at, by source and app version, to see whether it's widespread. Exclude them or clamp them to zero in the metric, and document the choice. Also report the excluded count, and ask the producers to fix the clocks (or use server-side timestamps).

  • Would you report mean or median session length to a product manager? Why?

    Usually the median, because session lengths are heavily skewed: a few very long sessions pull the mean up. Show the mean too if the total time matters, and ideally the distribution (p25, p50, p90).

Dialect notes

  • snowflake: `DATEDIFF('second', started_at, ended_at)`; avoid the 'minute' part, which counts boundaries crossed. docs
  • bigquery: `TIMESTAMP_DIFF(ended_at, started_at, SECOND)`. docs
  • sqlserver: `DATEDIFF(second, started_at, ended_at)`; it also counts boundaries crossed, so use seconds, not minutes. docs

Sessionize page views with a 30-minute timeout

SQLmediummid · senior20 mindataset: events
#sessionization#window-functions

Table: page_views(user_id, viewed_at, page)

A session is a run of page views by one user where each view comes no more than 30 minutes after the previous one. A gap of more than 30 minutes starts a new session. Exactly 30 minutes stays in the same session.

Output: user_id, session_count, avg_views_per_session (rounded to 2 decimals). Order by user_id.

Hint 1

Compare each view with the previous one for the same user (LAG).

Hint 2

Flag session starts with 1, then a running SUM of the flags numbers the sessions.

Show solution
WITH flagged AS (
SELECT user_id,
viewed_at,
CASE
WHEN LAG(viewed_at) OVER w IS NULL THEN 1
WHEN viewed_at - LAG(viewed_at) OVER w > INTERVAL 30 MINUTE THEN 1
ELSE 0
END AS is_session_start
FROM page_views
WINDOW w AS (PARTITION BY user_id ORDER BY viewed_at)
),
numbered AS (
SELECT user_id,
SUM(is_session_start) OVER (
PARTITION BY user_id ORDER BY viewed_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS session_no
FROM flagged
)
SELECT user_id,
COUNT(DISTINCT session_no) AS session_count,
ROUND(COUNT(*) * 1.0 / COUNT(DISTINCT session_no), 2) AS avg_views_per_session
FROM numbered
GROUP BY user_id
ORDER BY user_id;

Sessionization is "flag the starts, then cumulative-sum the flags". LAG finds the gap to the previous view; a gap over 30 minutes, or no previous view at all, is a start. The running sum turns the flags into session numbers 1, 2, 3, ….

Watch the boundary: the prompt says more than 30 minutes, so use >, not >=.

What a strong answer covers

  • Uses flag + running sum rather than a self-join to assign sessions (weight 2)
  • Handles the first view per user (LAG is NULL) and the exact-30-minute boundary (weight 1)

Follow-ups

  • Sessions must also end at midnight UTC. What changes?

    Start a new session also when the UTC date changes from the previous event: the new-session flag becomes gap > 30 min OR date(ts) <> date(prev_ts).

  • How do you sessionize a stream where events arrive up to 10 minutes late?

    Use event-time session windows with a watermark of at least 10 minutes in a stream processor (Flink, Spark): a session closes only when the watermark passes its last event plus the 30-minute gap. Late events can extend or merge sessions, so downstream must accept updates.

Dialect notes

  • snowflake: `DATEDIFF('minute', a, b)` counts minute boundaries crossed, not elapsed minutes. Compare `DATEDIFF('second', a, b) > 1800` instead. docs
  • bigquery: Use `TIMESTAMP_DIFF(viewed_at, prev_viewed_at, SECOND) > 1800`. docs

Top 3 products by revenue in each category

SQLeasyjunior · mid15 mindataset: ecommerce
#top-n-per-group#window-functions

Tables:

  • products(product_id, name, category, price)
  • orders(order_id, customer_id, order_date, status)
  • order_items(order_id, product_id, quantity, unit_price)

Revenue for a line item is quantity * unit_price. Count only orders with status = 'completed'.

For each category, return the 3 products with the highest revenue. If two products tie, the lower product_id ranks higher.

Output: category, product_id, revenue, revenue_rank. Order by category, then revenue_rank.

Hint 1

Aggregate revenue per product first, then rank inside each category.

Hint 2

Which ranking function gives exactly 3 rows per category even when there are ties?

Show solution
WITH product_revenue AS (
SELECT p.category, p.product_id, SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status = 'completed'
GROUP BY p.category, p.product_id
),
ranked AS (
SELECT category, product_id, revenue,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC, product_id) AS revenue_rank
FROM product_revenue
)
SELECT category, product_id, revenue, revenue_rank
FROM ranked
WHERE revenue_rank <= 3
ORDER BY category, revenue_rank;

Aggregate first, rank second. Ranking raw line items would rank rows, not products.

ROW_NUMBER with product_id as a tie-breaker gives exactly three rows per category and the same result every run. RANK would return more than three rows on ties, and DENSE_RANK could return many more. Pick one on purpose and say why in the interview.

Follow-ups

  • The business now wants ties included, even if that means 4 rows. What changes?

    Use RANK() (or DENSE_RANK()) instead of ROW_NUMBER(), and keep rank ≤ 3. RANK includes every product tied at 3rd place. DENSE_RANK would also keep more distinct revenue levels.

  • How would you get the same result without a window function?

    A correlated subquery: keep a product if fewer than 3 products in the same category have strictly higher revenue. It's slow on large tables, but it works in engines without window functions.

Dialect notes

  • snowflake: Use `QUALIFY revenue_rank <= 3` to filter on the window result without the extra CTE. docs
  • bigquery: `QUALIFY revenue_rank <= 3` works; it filters on window results, which run after GROUP BY and HAVING. docs
  • databricks: `QUALIFY` is supported in Databricks SQL. docs
  • sqlserver: No `QUALIFY`. Keep the ranking in a CTE or subquery and filter in the outer query, as above. docs

Further reading

Reconstruct what the dashboard showed at a past moment

SQLhardsenior · lead25 mindataset: payments
#bitemporal#deduplication#point-in-time-joins

Table: transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at). Each txn_id can have several copies; a copy is visible from its ingested_at.

An auditor asks: "What did our status breakdown look like at 2024-06-30 23:59:59, using only the data we had at that moment?"

Count transactions with txn_ts at or before the cutoff, by the status of their latest copy ingested at or before the cutoff.

Output: status, txn_count. Order by status.

Hint 1

There are two time axes, when it happened (txn_ts) and when we learned it (ingested_at). Filter both.

Show solution
WITH known_then AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
WHERE txn_ts <= TIMESTAMP '2024-06-30 23:59:59'
AND ingested_at <= TIMESTAMP '2024-06-30 23:59:59'
)
SELECT status, COUNT(*) AS txn_count
FROM known_then
WHERE rn = 1
GROUP BY status
ORDER BY status;

This is a bitemporal question: event time (txn_ts) and knowledge time (ingested_at). Filter on knowledge time before you dedup, so a transaction that settled on 1 July still shows as pending at the cutoff, which is what the dashboard really showed.

Deduplicating first and filtering after gives today's status for June transactions. It answers a different question and is the usual wrong answer.

Keeping every copy with its ingestion time (append-only) is what makes this reconstructable at all. If the pipeline had updated rows in place, the answer would be gone.

What a strong answer covers

  • Filters on ingestion time before deduplicating, and explains why the order matters (weight 3)

Follow-ups

  • Which table design lets you answer this for any cutoff cheaply (hint, valid_from / valid_to on ingestion time)?

    A bitemporal history table: each version of a transaction has known_from (its ingestion time) and known_to (when it was superseded). A cutoff query is then WHERE known_from <= cutoff AND (known_to > cutoff OR known_to IS NULL), a single range filter instead of a window over all copies.

  • How do Iceberg or Delta time travel relate to this, and where do they fall short?

    Time travel lets you query a table as of a past snapshot, which answers 'what did the table contain then' cheaply. It's limited by snapshot retention (old snapshots are expired to save storage), it reflects when data was committed rather than business time, and you can't correct the past. Model history explicitly if you need it long term.

Histogram of trip durations in 10-minute buckets

SQLeasyjunior10 mindataset: rides
#bucketing#aggregation

Table: trips(trip_id, driver_id, rider_id, city, requested_at, completed_at, status, fare)

For completed trips, compute the duration in minutes from requested_at to completed_at, then count trips per 10-minute bucket: [0, 10), [10, 20), and so on. Label each bucket by its start.

Output: bucket_start_min, trips. Order by bucket_start_min.

Hint 1

Bucket start = FLOOR(minutes / 10) * 10.

Show solution
SELECT CAST(FLOOR((EPOCH(completed_at) - EPOCH(requested_at)) / 60 / 10) * 10 AS INTEGER) AS bucket_start_min,
COUNT(*) AS trips
FROM trips
WHERE status = 'completed'
GROUP BY 1
ORDER BY 1;

Fixed-width buckets come from integer division: FLOOR(value / width) * width. Compute the duration in seconds first. Truncating to whole minutes before bucketing is fine here, but rounding (ROUND) instead of FLOOR would shift a 9.6-minute trip into the wrong bucket.

Empty buckets don't appear. If the chart needs them, join to a series of bucket starts.

Follow-ups

  • Make the buckets 0–5, 5–15, 15–30, 30+. What changes?

    Equal-width arithmetic (FLOOR(minutes / 10)) no longer works. Use a CASE expression or a join to a small buckets table with lower and upper bounds, and order by the lower bound so the labels sort correctly.

  • How would you pick bucket widths automatically for an unknown distribution?

    Use rules such as Freedman–Diaconis (width = 2 × IQR / n^(1/3)) or Sturges, use quantile buckets (each holding the same number of trips), or a log scale for long-tailed data. Cap the outliers into a final open bucket.

Decide insert, update or unchanged for an incremental load

SQLmediummid · senior25 mindataset: integration
#upserts#null-traps#deduplication#incremental-loads

Tables:

  • customer_feed(file_name, line_no, customer_code, full_name, email, country, updated_at): a month of raw daily files, all text. Some lines are invalid; one file was resent.
  • customers_target(customer_code, full_name, email, country, updated_at): the warehouse table before March's load. Some email values are NULL.

Before running a MERGE, you want to know what it will do. Using only valid feed lines (the code is non-blank after trimming, email contains @ and a dot after it with no spaces, country has exactly 2 characters, updated_at parses as YYYY-MM-DD HH:MM:SS), take the latest line per customer by updated_at. Compare it with the target on full_name, email and country:

  • insert: the customer isn't in the target.
  • update: at least one of the three columns differs.
  • unchanged: all three are the same.

Output: action, customers. Order by action.

Hint 1

Customer codes sometimes arrive with spaces around them. What happens to the join if you don't trim?

Hint 2

The target has NULL emails. What does NULL <> 'a@b.com' evaluate to, and what does that do to your update count?

Show solution
WITH valid AS (
SELECT TRIM(customer_code) AS customer_code, full_name, email, country,
STRPTIME(updated_at, '%Y-%m-%d %H:%M:%S') AS updated_at
FROM customer_feed
WHERE TRIM(customer_code) <> ''
AND regexp_full_match(email, '[^@ ]+@[^@ ]+\.[^@ ]+')
AND LENGTH(country) = 2
AND TRY_STRPTIME(updated_at, '%Y-%m-%d %H:%M:%S') IS NOT NULL
),
latest AS (
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_code ORDER BY updated_at DESC) AS rn
FROM valid
) v
WHERE rn = 1
)
SELECT CASE
WHEN t.customer_code IS NULL THEN 'insert'
WHEN l.full_name IS DISTINCT FROM t.full_name
OR l.email IS DISTINCT FROM t.email
OR l.country IS DISTINCT FROM t.country THEN 'update'
ELSE 'unchanged'
END AS action,
COUNT(*) AS customers
FROM latest l
LEFT JOIN customers_target t ON t.customer_code = l.customer_code
GROUP BY action
ORDER BY action;

This is the change detection inside every incremental load (an SCD type 1 merge). Three traps each change the answer:

  1. NULL comparisons. l.email <> t.email is NULL, not true, when the target email is NULL, so a customer whose email was finally captured is counted as unchanged and the fix never reaches the warehouse. IS DISTINCT FROM treats NULL as a comparable value. In engines without it, compare COALESCE(a, '') <> COALESCE(b, ''), or use a row hash that maps NULL to a fixed token.
  2. Untrimmed keys. ' C0123 ' doesn't match 'C0123', so it looks like a brand-new customer, and the merge would insert a duplicate.
  3. Deduplicate first. A month of files, a resent file and repeated lines mean several rows per customer. MERGE fails or behaves unpredictably when more than one source row matches a target row, so reduce to the latest valid row per key before merging.

Counting the actions before running the merge is also a cheap sanity check: an unexpected spike in updates or inserts usually means a key or format problem upstream.

What a strong answer covers

  • Uses NULL-safe comparison (IS DISTINCT FROM or equivalent) and explains the NULL trap (weight 3)
  • Trims keys and filters invalid lines before matching (weight 2)
  • Reduces to the latest row per key before comparing (required for MERGE) (weight 2)

Follow-ups

  • Comparing every column gets slow on a table with 80 columns. What do teams do instead?

    Compute a hash of the tracked columns (with NULLs mapped to a fixed token and a delimiter between values) on both sides and compare the hashes. Store the hash on the target row so each load only hashes the incoming rows.

  • How does this change if the target keeps history (SCD type 2)?

    An update no longer overwrites: it closes the current version (sets valid_to and is_current = false) and inserts a new version. Inserts create the first version; unchanged rows do nothing. The comparison is against the current version only.

Dialect notes

  • sqlserver: `IS DISTINCT FROM` is available in SQL Server 2022 and later; on earlier versions compare with `ISNULL` / `COALESCE` or `EXISTS (SELECT a EXCEPT SELECT b)`. docs
  • snowflake: `IS DISTINCT FROM` is supported, and `EQUAL_NULL(a, b)` is a NULL-safe equality function. docs

Daily settled volume in USD using the latest FX rate

SQLhardsenior · lead30 mindataset: payments
#as-of-joins#deduplication

Tables:

  • transactions(txn_id, account_id, txn_ts, amount, currency, txn_type, status, ingested_at). It contains replays: keep only the copy with the latest ingested_at per txn_id.
  • fx_rates(rate_date, currency, usd_rate): 1 unit of currency = usd_rate USD. Rates are published on business days only. There is no row for USD.

For each day, return the total amount of settled transactions (status = 'settled' on the latest copy) converted to USD. Convert each transaction with the most recent rate on or before its transaction date.

Output: txn_date, usd_volume (rounded to 2 decimals). Order by txn_date.

Hint 1

An equi-join on rate_date = txn_date loses every weekend transaction.

Hint 2

USD needs a rate of 1, not a missing join.

Show solution
WITH latest AS (
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY txn_id ORDER BY ingested_at DESC) AS rn
FROM transactions
) t
WHERE rn = 1
),
settled AS (
SELECT CAST(txn_ts AS DATE) AS txn_date, amount, currency
FROM latest
WHERE status = 'settled'
),
priced AS (
SELECT s.txn_date,
s.amount * CASE
WHEN s.currency = 'USD' THEN 1
ELSE (
SELECT f.usd_rate
FROM fx_rates f
WHERE f.currency = s.currency AND f.rate_date <= s.txn_date
ORDER BY f.rate_date DESC
LIMIT 1
)
END AS usd_amount
FROM settled s
)
SELECT txn_date, ROUND(SUM(usd_amount), 2) AS usd_volume
FROM priced
GROUP BY txn_date
ORDER BY txn_date;

There are three traps:

  1. Replays. Dedup first. Otherwise a replayed transaction is summed twice, and a stale pending copy can hide a settlement.
  2. Non-business days. Saturday's transactions need Friday's rate. That's an as-of lookup: the latest rate with rate_date <= txn_date. A correlated subquery is the portable form. Many engines also offer an ASOF JOIN, and a window-based alternative is to give each rate a valid_to with LEAD(rate_date) and range-join on it.
  3. The base currency. USD has no rate row. An inner join would silently drop all USD volume.

At scale, precompute a daily rate table filled forward to every calendar day, then do a plain equi-join.

What a strong answer covers

  • Uses the latest rate on or before the transaction date (handles weekends/holidays) (weight 2)
  • Dedupes replayed transactions before filtering and summing (weight 2)
  • Treats USD as rate 1 instead of dropping it (weight 1)

Follow-ups

  • Finance restates a rate for last Tuesday. Which outputs must be recomputed, and how does your pipeline know?

    Every output that used that rate: the converted rows from last Tuesday until the next rate, and the aggregates over them. The pipeline knows if the rate table carries a version or updated_at, and the converted rows store which rate (date or version) they used, so a changed rate triggers a rebuild of the affected partitions.

  • Would you store converted USD amounts in the fact table or convert at query time? Why?

    Store the amount in the original currency and the converted USD amount with the rate date used, for audit and fast queries. Then a restatement means reprocessing known partitions. Converting at query time is always current but slower, and makes historical reports change without notice.

Dialect notes

  • snowflake: `ASOF JOIN fx_rates f MATCH_CONDITION(s.txn_date >= f.rate_date) ON s.currency = f.currency` does the as-of lookup natively. docs

Week-1 retention by weekly signup cohort

SQLmediummid · senior25 mindataset: events
#retention-cohorts#date-functions

Tables:

  • users(user_id, signup_date, country, plan)
  • logins(user_id, login_ts)

A user's cohort is the week of their signup_date (weeks start on Monday). A user is retained if they logged in at least once between 7 and 13 days after signup_date, inclusive.

Output: cohort_week, cohort_size, retained_users, retention_rate, where retention_rate = retained_users / cohort_size rounded to 4 decimals. Include cohorts with zero retained users. Order by cohort_week.

Hint 1

Decide retained yes/no per user first, then aggregate per cohort.

Hint 2

Starting from logins drops users who never logged in. Start from users.

Show solution
WITH per_user AS (
SELECT u.user_id,
CAST(DATE_TRUNC('week', u.signup_date) AS DATE) AS cohort_week,
EXISTS (
SELECT 1 FROM logins l
WHERE l.user_id = u.user_id
AND CAST(l.login_ts AS DATE) BETWEEN u.signup_date + 7 AND u.signup_date + 13
) AS retained
FROM users u
)
SELECT cohort_week,
COUNT(*) AS cohort_size,
SUM(CASE WHEN retained THEN 1 ELSE 0 END) AS retained_users,
ROUND(AVG(CASE WHEN retained THEN 1.0 ELSE 0.0 END), 4) AS retention_rate
FROM per_user
GROUP BY cohort_week
ORDER BY cohort_week;

Pin the definition down before writing SQL: cohort = signup week, retained = any login on days 7–13. Most wrong answers come from a fuzzy definition, not from the SQL.

Start from users, not logins. Users who never came back still belong to the cohort size. Joining logins first and counting would drop them and inflate retention.

What a strong answer covers

  • States the retention window precisely (days 7–13 after signup) before writing SQL (weight 2)
  • Keeps users with no logins in the cohort size (weight 1)

Follow-ups

  • The newest cohorts haven't had 13 days yet. How do you keep them from looking like churn?

    Only report retention for cohorts that have had the full window (signup + 13 days ≤ today), and show the rest as NULL or 'not yet mature' instead of 0. Charts should visually separate immature cohorts.

  • Turn this into a full retention triangle (week 0 to week 8). What's the shape of the output?

    One row per cohort week and week number (0–8) with the retained users and the cohort size, which pivots into a triangle: older cohorts have all nine columns, newer ones fewer. Include the cohort size so percentages can be computed and weighted.

Dialect notes

  • bigquery: `DATE_TRUNC(signup_date, WEEK)` starts weeks on **Sunday**. Use `WEEK(MONDAY)` or `ISOWEEK` to match this question. docs
  • snowflake: The first day of the week for `DATE_TRUNC('week', …)` depends on the `WEEK_START` session parameter; set it, or don't rely on the default. docs

Design a batch lakehouse on AWS

System designmediummid · senior40 min
#aws#lakehouse#iam#cost

A retailer wants its first data platform on AWS. Sources: a PostgreSQL order database on RDS, a SaaS CRM with a REST API, and CSV files that stores upload daily. About 50 GB of new data a day; 3 years of history (around 40 TB). Consumers: finance dashboards by 07:00, analysts running ad-hoc SQL, and a data science team that wants raw history.

Design it on AWS: which services for ingestion, storage, processing, orchestration, serving, security and monitoring, and why. Say what you'd choose differently with a smaller team or budget.

Hint 1

Separate the layers (ingest, store, transform, serve) first, then pick a service for each. What does each choice cost when idle?

Hint 2

Who should be able to read raw customer data, and how would you enforce it at table and column level?

Show solution

Shape: land everything in S3 as the system of record, organize it into raw → cleaned → curated layers in an open table format, transform in batch, and serve SQL from the lake (and a warehouse if needed).

Ingestion

  • RDS PostgreSQL: change data capture with AWS DMS (full load plus ongoing changes) into S3, or a nightly incremental extract if minute-level freshness isn't needed. Read from a replica to protect the primary.
  • CRM API: a small scheduled job (Lambda, or a Glue Python shell job, or a container) with pagination, retries and a watermark, writing raw JSON to S3; or a managed connector if the budget allows.
  • Store CSV files: uploads to an S3 landing prefix; an event or schedule validates them, with a load log and rejects as in any file feed.

Storage: S3 with prefixes per layer and source, partitioned by date, Parquet in Apache Iceberg tables (ACID commits, schema evolution, time travel, MERGE for CDC), registered in the Glue Data Catalog. Lifecycle rules move old raw files to cheaper storage classes.

Processing: Glue Spark jobs (serverless, good for many daily jobs) for cleaning and CDC merges. Curated models are SQL, for example dbt running on Athena or on the warehouse. For heavy backfills of the 40 TB history, a transient EMR cluster with spot task nodes.

Orchestration: Amazon MWAA (managed Airflow) if the team knows Airflow or needs complex dependencies; Step Functions for simpler event-driven flows. Either way: idempotent tasks partitioned by date, retries, and an SLA alert for the 07:00 finance tables.

Serving

  • Athena for ad-hoc SQL on the lake (pay per TB scanned, so partitioning and Parquet matter).
  • Redshift (provisioned or serverless) for the finance dashboards if concurrency and latency need it, loading or querying the curated layer.
  • Data science reads raw and curated tables directly with Spark or Athena.

Security: separate dev and prod accounts; IAM roles per job with least privilege; Lake Formation for table, column and row permissions (PII columns restricted); KMS encryption; S3 gateway endpoints and private subnets; secrets in Secrets Manager; CloudTrail on.

Monitoring and cost: CloudWatch alarms on failures and duration; data quality checks and freshness per table; cost allocation tags per pipeline and Cost Explorer budgets; Athena workgroup scan limits.

Smaller team or budget: drop Redshift and serve from Athena; use Step Functions or a single scheduled container instead of MWAA; nightly incremental extracts instead of DMS; fewer, simpler Glue jobs. Bigger scale: streaming ingestion (Kinesis or MSK) and more workload isolation.

What a strong answer covers

  • Layers the design (ingest, store, transform, serve) with S3 as system of record and an open table format (weight 2)
  • Chooses suitable ingestion per source (CDC for RDS, API job with watermark, validated file landing) (weight 2)
  • Justifies processing, orchestration and serving choices with cost and team trade-offs (weight 3)
  • Covers security: account separation, least-privilege roles, Lake Formation, encryption, private networking (weight 2)
  • Covers monitoring, freshness SLAs and cost controls, and adapts the design to a smaller budget (weight 2)

Follow-ups

  • How would the same design look on GCP or Azure?

    Same layers, different services. GCP: Cloud Storage, Datastream for CDC, Dataproc or Dataflow, Cloud Composer, BigQuery for serving and governance through IAM and policy tags. Azure: ADLS Gen2, Data Factory for ingestion, Databricks or Synapse Spark, Data Factory or Databricks workflows, Synapse or Fabric for serving, Entra ID and RBAC for access.

  • Finance asks why the 07:00 tables were late twice last week. What would you look at?

    The orchestrator's task timeline for those days: which task started late or ran long, and whether it waited on a source (late DMS lag, a slow CRM API) or on compute (Glue capacity, a large backfill competing). Then fix that dependency or schedule, and alert earlier on the critical path.

Further reading

Replicate a production Postgres into the lakehouse with CDC

System designmediummid · senior · lead45 min
#cdc#lakehouse#schema-evolution

The orders service runs on Postgres: about 200 tables, the largest with 2 billion rows and 5,000 writes per second. Today a nightly SELECT * dump feeds the warehouse, and it now takes 9 hours and slows the primary.

Design a change data capture (CDC) pipeline that keeps lakehouse tables within 10 minutes of the source, without hurting production. Cover the initial load, deletes, schema changes and how you know the copy is correct.

Read the full worked design →

Hint 1

How do you take a consistent initial snapshot and then switch to the change stream without gaps or duplicates?

Hint 2

What happens to a downstream table when someone adds or renames a column?

Show solution

Postgres logical replication (a publication plus a replication slot) → Debezium → Kafka (one topic per table, keyed by primary key) → a merge job writes Iceberg/Delta tables: an append-only change log (_bronze) and a current-state table (_silver) maintained by MERGE on the primary key, ordered by the source LSN.

The main points: use an incremental snapshot so the initial load doesn't lock tables, and so snapshot and stream overlap safely (dedup by PK + LSN); deletes arrive as tombstones and become soft deletes or physical deletes by policy; watch replication slot lag, because a stuck consumer makes WAL fill the primary's disk; handle additive schema changes automatically and send breaking ones through a contract and review; prove correctness with row counts and checksums per table versus the source.

What a strong answer covers

  • Uses log-based CDC (WAL/logical replication) rather than query polling, and says why (weight 2)
  • Explains initial snapshot + stream handoff without gaps or duplicates (ordering by LSN/PK) (weight 3)
  • MERGE into current-state table plus an append-only change history (weight 2)
  • Handles deletes, and schema evolution (additive vs breaking) (weight 2)
  • Calls out replication slot / WAL growth risk on the primary and monitors lag (weight 2)
  • Reconciliation: counts/checksums vs source (weight 2)
  • Small-file compaction and MERGE cost at scale (weight 1)

Follow-ups

  • A developer runs an UPDATE on 300 million rows in one transaction. What happens to your pipeline?

    Debezium emits 300 million change events once the transaction commits, so the pipeline sees a burst: Kafka lag spikes, the merge into the lakehouse table becomes huge and slow, and the WAL may grow on the source while the connector catches up. Mitigate by scaling consumers, merging in batches, alerting on lag and WAL size, and asking for large updates to be batched or coordinated in advance.

  • The business wants "orders as they looked yesterday at 09:00". Which table answers it?

    A history table: either the raw change log (every version with its commit timestamp) or an SCD2 table built from it, queried with valid_from <= '... 09:00' < valid_to. Table time travel can also answer it if snapshots are kept that long.

Further reading

Design a clickstream pipeline from apps to the warehouse

System designmediummid · senior · lead45 min
#streaming-ingestion#event-modeling#late-arriving-data

Web and mobile apps emit about 50,000 events per second at peak (2–3 billion a day). Product analysts want dashboards that are at most 15 minutes behind, and data scientists want full history for modeling. Events can arrive days late from offline phones.

Design the pipeline from the SDK to analyst-ready tables. Cover ingestion, storage, transformation, data quality, backfills and cost.

Read the full worked design →

Hint 1

Separate the "land it safely" path from the "make it useful" path.

Hint 2

Which timestamp do you partition by, and what does that do to late events?

Show solution

SDK → collector API (validates against a schema registry, adds received_at) → Kafka (partitioned by user/device for per-user order) → a streaming sink writes raw Parquet/Iceberg partitioned by received hour → micro-batch transforms (every 5–15 minutes) dedup on event_id, type the common fields and produce fct_events partitioned by event date → sessions and daily aggregates downstream.

The main points: keep an immutable raw layer so anything can be replayed; make every step idempotent (dedup keys, overwrite-by-partition); reprocess a sliding window of the last N event dates for late data; enforce contracts at the collector and quarantine bad events rather than drop them; control cost with compaction, partition pruning, tiered retention, and by not streaming what only needs batch.

The full walkthrough is in the worked design.

What a strong answer covers

  • Clarifies requirements: volume, freshness SLA, late data window, consumers (weight 2)
  • Durable buffer (Kafka/Kinesis) and an immutable raw layer for replay (weight 3)
  • Idempotent processing: dedup on event_id, partition overwrite (weight 2)
  • Event time vs received time, and a reprocessing window for late events (weight 3)
  • Schema contracts and a quarantine path for invalid events (weight 2)
  • Cost controls: compaction, partition pruning, retention tiers (weight 1)
  • Says what changes at 10x volume (weight 1)

Follow-ups

  • The 15-minute SLA becomes 10 seconds for one fraud dashboard. What do you add, and what do you not change?

    Add a streaming path for that one dashboard: a stream processor reading the same Kafka topic and writing to a low-latency store, such as a real-time OLAP database. Keep the existing batch path, its SLA and the warehouse as the source of truth.

  • A producer bug sent 6 hours of events with the wrong user_id. Walk through the fix.

    Find the affected window and events (by producer version and time). Fix the producer, then correct the data: if the true user_id can be derived (from the session or device), rewrite the affected partitions. Otherwise quarantine or flag them. Reprocess downstream aggregates for those hours, and tell the consumers what changed.

Further reading

Cut a runaway warehouse bill

System designmediummid · senior · lead45 min
#cost#finops#performance

The company's cloud warehouse bill went from $40k to $150k a month in a year. Leadership wants it back under $80k within a quarter, without breaking the dashboards and models people rely on. You have read access to the warehouse's query history and billing views.

How do you find where the money goes, what do you change first, and how do you keep it from creeping back?

Read the full worked design →

Hint 1

Don't optimize anything until you can attribute cost to teams, warehouses, models and queries.

Hint 2

The biggest wins are usually things that shouldn't run at all, or run far more often than anyone needs.

Show solution

Measure first: attribute spend by compute cluster or warehouse, user/role, tool, dbt model and query pattern, using the warehouse's metering and query-history views. Tag queries (query tags, labels) so cost maps to an owner. Usually a short list of things explains most of the bill.

Then fix in order of return: stop what nobody uses (dead dashboards and models, duplicate pipelines); reduce frequency to what consumers need (hourly → daily); right-size compute (auto-suspend, smaller warehouses, separate workloads, concurrency settings); make the expensive queries cheaper (incremental models instead of full rebuilds, partition/cluster pruning, no SELECT *, pre-aggregations for dashboards); and set storage retention (time travel, staging tables).

Keep it down: budgets and alerts per team, cost dashboards with owners, guardrails (statement timeouts, maximum bytes billed, resource monitors), cost checks in code review for new models, and a monthly review of the top 20 queries.

The full walkthrough is in the worked design.

What a strong answer covers

  • Builds cost attribution (by warehouse, team, model, query) before changing anything (weight 3)
  • Removes unused or over-frequent workloads first (biggest, cheapest wins) (weight 2)
  • Right-sizes compute: auto-suspend, sizing, workload isolation (weight 2)
  • Makes expensive queries cheaper: incremental models, pruning, pre-aggregation (weight 2)
  • Adds guardrails and ownership so cost does not creep back (weight 2)
  • Protects consumers: changes validated, stakeholders told, rollback possible (weight 1)

Follow-ups

  • The finance team wants per-customer cost for your multi-tenant product. How would you allocate shared compute?

    Tag queries with the tenant (query tags or labels, or per-tenant warehouses or projects), then allocate compute by each tenant's share of measured usage: credits, bytes scanned or slot time. Allocate shared jobs proportionally to rows or data per tenant, and document the method so finance trusts it.

  • One team says their model "must" refresh every 5 minutes. How do you decide?

    Ask what decision changes within 5 minutes and what it's worth, then show the cost of each refresh frequency. Offer alternatives such as an incremental model, a streaming table for just the few fields that need freshness, or 15–30 minutes. Agree on an SLA and a budget, and let the owner choose knowing the cost.

A daily batch pipeline that can be backfilled safely

System designmediumjunior · mid · senior40 min
#batch#backfills#orchestration#idempotency

Every day at 02:00 a pipeline loads yesterday's orders from an API and a vendor SFTP drop, transforms them, and publishes daily_revenue for an 07:00 executive dashboard.

Last month a bug in the transform went unnoticed for 9 days, and fixing it took a week of manual reruns. Design the pipeline so that reruns and backfills of any date range are boring.

Read the full worked design →

Hint 1

What does running the same day twice do to the output?

Hint 2

How do you rerun 90 days without overloading the API or blocking today's run?

Show solution

Orchestrate with Airflow/Dagster, one run per logical date. Each task is a pure function of that date: extract only that date's window into a raw path that includes the date (raw/orders/dt=2024-05-01/), transform, and overwrite the output partition for that date. Never append. This makes every run idempotent: running a day twice gives the same result.

Backfills are just runs for past logical dates with limited concurrency (pools), lower priority than the daily run, and a rate limit on the source API. Prefer re-transforming from stored raw data, so the API isn't hit again. Publish via a write-audit-publish pattern: build into staging, run data quality checks (row counts versus source, revenue versus the previous day, nulls, duplicates), and swap or overwrite only if they pass, so the 07:00 dashboard never shows a half-loaded or broken day.

Add an SLA alert at 06:00, lineage so you know which downstream tables a backfill must touch, and a "data as of" note on the dashboard.

What a strong answer covers

  • Parameterizes everything by logical date (no "now()" inside tasks) (weight 3)
  • Idempotent writes: overwrite the partition for that date, never blind append (weight 3)
  • Keeps raw extracts so backfills re-transform without re-extracting (weight 2)
  • Backfill throttling: concurrency limits, priority below the daily run, source rate limits (weight 2)
  • Quality gate before publishing (write-audit-publish) and SLA alerting (weight 2)

Follow-ups

  • The transform depends on a dimension that has changed since then. Should a backfill use today's dimension or the historical one?

    Usually the historical version, so a backfill reproduces what the data meant at that time: join to an SCD2 dimension as of the event date. Use today's version only when the business explicitly wants restated history (for example a current org structure). Either way, decide it deliberately and document it.

  • How do you backfill a table that 30 downstream dbt models depend on?

    Backfill the upstream table in date-range batches, then rebuild downstream with lineage-aware selection (dbt build --select table+) for the same partitions. Schedule it outside the daily run's window, consider writing to a separate schema and swapping it in, and validate row counts before releasing.

Further reading

Design data quality and observability for a data platform

System designhardsenior · lead45 min
#data-quality#observability#slas#data-contracts#lineage

Your company's data platform has 60 sources (databases, SaaS APIs, event streams), about 400 dbt models and 30 executive dashboards. Last quarter the CEO found three data problems before the data team did. Leadership asks you to design how the platform detects, prevents and handles bad data.

Cover what you check and where, how alerts reach the right people without drowning them, how you stop bad data from reaching dashboards, and how you'd measure whether it's working.

Hint 1

Think in layers: at the source, at ingestion, in transformation, before publishing. What is each layer best at catching?

Hint 2

An alert with no owner gets ignored. How does each check know whom to notify?

Hint 3

Three of the main signals are freshness, volume and schema. What's missing from that list?

Show solution

1. Clarify and prioritize. Not all 400 models matter equally. Start from the 30 dashboards, trace their lineage back, and mark those models and sources tier 1 with an owner and an SLA (for example "finance revenue mart fresh by 07:00, complete, reconciled to the ledger"). Everything else gets lighter coverage.

2. Checks by layer.

Layer What it catches Examples
Producer / contract Breaking changes before they ship Schema registry compatibility, data contracts with owning teams, CI checks in producer repos
Ingestion Missing, late, malformed data Freshness per source, row-count and volume anomalies, schema drift, quarantine for invalid records
Transformation Logic and grain errors dbt tests on keys and relationships, contracts on public models, unit tests on tricky logic
Publish Wrong numbers reaching people Reconciliation (mart totals vs source of truth), metric anomaly checks on key KPIs, distribution checks

The five signals to monitor automatically: freshness, volume, schema, distribution (null rates, value ranges), and lineage to know the impact of any failure.

3. Stop bad data, don't just report it. Tier-1 pipelines use a circuit breaker: publish (swap the new partition or table in) only when the checks pass. Otherwise keep yesterday's data and mark the dashboard "stale since …". Write-audit-publish is the general pattern: write to staging, audit, then publish atomically. Stale-but-correct beats fresh-but-wrong for executive numbers.

4. Alerting people, not channels. Every check has an owner, from model ownership metadata. Alerts are routed by tier and severity: tier-1 errors page the on-call engineer, warnings go to the team channel, and owners of downstream dashboards are notified automatically using lineage. Deduplicate alerts (one incident, not 40 failing downstream tests), and review noisy checks monthly: fix, retune or delete them.

5. Incidents and communication. A status banner on affected dashboards, an incident channel, a runbook per tier-1 pipeline, and blameless post-incident reviews that add the check that would have caught it.

6. Measure it. Data incidents per month, share detected by the data team before consumers (the headline metric here), time to detect and time to resolve, SLA attainment per tier-1 dataset, and alert precision (alerts that led to action).

Build vs buy: dbt tests plus freshness checks and a simple anomaly detector cover a lot. Observability tools add automatic monitors, lineage and incident workflows across hundreds of tables. Choose based on team size and how much you'd otherwise build.

What a strong answer covers

  • Prioritizes by tiers/lineage from the critical dashboards, with owners and SLAs (weight 2)
  • Layers checks (contracts at source, ingestion monitors, transformation tests, publish-time reconciliation) (weight 3)
  • Blocks bad data from reaching dashboards (circuit breaker / write-audit-publish, stale-but-correct) (weight 3)
  • Routes alerts by owner and severity, uses lineage for impact, manages alert fatigue (weight 2)
  • Defines success metrics (detected-before-consumers rate, time to detect/resolve, SLA attainment) (weight 2)

Follow-ups

  • The circuit breaker blocked the finance mart at 06:30 and the CFO needs numbers at 08:00. What now?

    Follow the runbook: page the owner, show the dashboard as stale with a clear note, and find the cause. If it's a false alarm, override and publish with a record of who decided. If it's real, tell the CFO when correct numbers will be available. Afterwards, tune the check or fix the root cause.

  • How would you get 20 producer teams to adopt data contracts?

    Start with the few sources behind tier-1 data, make contracts cheap (a template, a schema registry check in their CI), and show the incidents they would have prevented. Make the contract a shared agreement with a named owner and change process, and tie it to the producers' own goals instead of imposing it.

GDPR delete across a data lake

System designhardsenior · lead45 min
#privacy#data-governance#lakehouse

The legal team says: "When a customer asks to be forgotten, we must erase their personal data everywhere within 30 days, and be able to prove it." The data platform has raw event files in object storage (Parquet and JSON, about 2 PB), lakehouse tables (Iceberg), a warehouse, ML training snapshots and backups. About 3,000 erasure requests arrive per month.

Design how erasure works end to end.

Read the full worked design →

Hint 1

Can you find every place one person's data lives? If not, that's the first problem.

Hint 2

Rewriting petabytes for each request doesn't scale. What can you batch, and what can you avoid storing at all?

Show solution

Know where the data is: a catalog of datasets tagged with PII columns and the subject key (customer_id, email hash). Without this inventory, erasure can't be proven.

Reduce what needs deleting: keep direct identifiers in a few governed tables. Elsewhere, use a pseudonymous key, and encrypt PII with per-customer keys (crypto-shredding: deleting the key makes all copies unreadable, including backups).

Process requests in batches: a request service records each request, then a weekly job deletes from every registered dataset. Use row-level deletes in lakehouse tables (Iceberg/Delta DELETE, followed by compaction and snapshot expiry so old files really disappear), DELETE in the warehouse, rewrite raw files partition by partition, and exclude or retrain affected ML snapshots per policy.

Prove it: an audit log per request (dataset, rows removed, timestamp), and verification queries that confirm zero rows remain. Retention rules for snapshots and time travel must be shorter than the legal deadline, or the deleted data stays readable in history.

What a strong answer covers

  • Starts with a data inventory: PII tagging and subject keys across all stores (weight 3)
  • Minimizes PII spread: pseudonymous keys, crypto-shredding for backups and copies (weight 2)
  • Batched deletes with lakehouse row-level deletes plus compaction and snapshot expiry (weight 3)
  • Handles time travel, backups and ML training data explicitly (weight 2)
  • Auditable: per-request log and verification that no rows remain (weight 2)

Follow-ups

  • An analyst exported a CSV of customer emails to their laptop last year. Is that your problem, and what controls would prevent it?

    Yes. The company is responsible for personal data wherever it ends up, including copies on laptops. Prevent it with access controls on PII columns (masking), restricted export permissions, data loss prevention tooling, audit logs of exports, and a policy plus training on handling personal data.

  • How do you erase someone from an aggregated table (for example daily revenue by country)?

    Aggregates with no individual identifiers usually aren't personal data, so they can stay. Check that small groups can't re-identify someone (a minimum group size), and if a table could, rebuild it from the erased source data.

Real-time metrics with late and out-of-order events

System designhardsenior · lead45 min
#stream-processing#watermarks#late-arriving-data

A delivery company computes "orders delivered per city per 5 minutes" for an operations wall and for courier bonuses. Courier phones buffer events when offline: 95% of events arrive within 30 seconds, 99.9% within 2 hours, and a few arrive the next day. Events from one courier can arrive out of order.

Design the streaming computation. The ops wall wants speed; bonuses must be exact.

Read the full worked design →

Hint 1

One pipeline can't be both instantly final and exactly right. What gives?

Hint 2

What does a watermark promise, and what happens to events behind it?

Show solution

Use event-time windows (5-minute tumbling, keyed by city) in Flink / Spark Structured Streaming, with a watermark of max event time minus 2 minutes. Each window emits an early result for the ops wall when the watermark passes, then updates (allowed lateness up to 2 hours) as late events arrive. The sink is an upsert keyed by (city, window_start), so corrections overwrite rather than duplicate.

Events later than allowed lateness go to a side output (late table), not to /dev/null. Bonuses don't come from the stream at all. A daily batch job recomputes the previous days exactly from the raw event log (including the late table), which is the source of truth. Ops reads the stream; payroll reads the batch.

State size grows with keys × windows × allowed lateness. That's the cost dial. Dedup on event_id inside the window, because offline phones resend.

What a strong answer covers

  • Uses event time (not processing time) windows and explains why (weight 3)
  • Explains watermarks and allowed lateness, and the speed/completeness trade-off (weight 3)
  • Upsert/retraction sink so updated windows correct earlier results (weight 2)
  • Side output for too-late events plus a batch recompute as the source of truth for money (weight 3)
  • Dedup of resent events, and state size as a cost driver (weight 1)

Follow-ups

  • The ops wall flickers because numbers change after they're shown. How do you present provisional data?

    Show the numbers as provisional, for example a lighter style or a '~' until the window's watermark passes, then mark them final. Or update less often (every 30 seconds) and show the time the data is complete up to. Set expectations so people know recent numbers can change.

  • A city has almost no traffic at night, so its watermark stalls. What happens, and how do you fix it?

    With a per-partition or per-key watermark, a quiet city's watermark doesn't advance, so its windows never close. Use an idle-source timeout so idle partitions don't hold back the watermark, or emit heartbeat events, or advance on processing time when no events arrive.

Further reading

Legacy (Teradata / Ab Initio) to cloud migration

System designhardsenior · lead45 min
#migrations#planning#validation

A bank runs 1,800 Ab Initio graphs and 6,000 Teradata SQL scripts that feed regulatory reports, finance and 400 BI dashboards. The Teradata contract ends in 18 months. Leadership has chosen a cloud warehouse plus dbt and an orchestrator.

Plan the migration: how you scope it, what moves first, how you prove the new system produces the same numbers, how you cut over, and what can derail it.

Read the full worked design →

Hint 1

Not everything should move. How do you find out what's actually used?

Hint 2

Same numbers has to be checked automatically, every day, for weeks. How?

Show solution

Inventory and cut: collect lineage and usage from query logs, scheduler metadata and job definitions. Map every job to its consumers, and retire what nobody reads. Typically a large share of legacy jobs are dead or duplicated.

Plan by domain, not by technology: migrate whole data products (for example deposits → finance reports) in waves, so each wave can be validated and cut over independently. Start with a valuable but non-regulatory domain to build the patterns (ingestion templates, dbt conventions, the testing harness), then do regulatory reports when the process is proven.

Translate, don't lift-and-shift blindly: automated SQL dialect conversion for the bulk, hand-rewrite of complex graphs, and a catalog of semantic differences (NULL handling, date/time zones, rounding, collation, implicit casts).

Prove parity: run old and new in parallel. A comparison harness checks row counts, key-level diffs and aggregates within tolerances every day, with every difference triaged. Cut over a domain only after N clean days, with sign-off from the data owners and a rollback plan. Decommission jobs as they are cut over.

Risks: scope creep ("while we're at it…"), hidden consumers (extracts, spreadsheets), key people leaving, regulators, and the deadline. Track burn-down per domain against the contract date.

What a strong answer covers

  • Inventory with usage/lineage to retire unused jobs before migrating (weight 3)
  • Sequences by business domain in waves, starting with a lower-risk domain to build patterns (weight 2)
  • Automated parallel-run comparison with tolerances and triage before each cutover (weight 3)
  • Handles dialect and semantic differences (NULLs, time zones, rounding, casts) (weight 2)
  • Cutover with sign-off, rollback and decommissioning; risks and deadline tracking (weight 2)

Follow-ups

  • Halfway through, the parallel run shows a 0.02% difference in a regulatory total. What do you do?

    Stop and investigate before going further: reproduce it, trace the difference down to the rows (rounding, NULL handling, timezone or sort-order differences are typical), and fix the new pipeline. For a regulatory total, explain and sign off any accepted difference with the business owner. Don't hide it.

  • How do you keep business teams from adding new jobs to the legacy system during the migration?

    Freeze the legacy system: new jobs need an approval, and the migration team offers to build new work directly in the cloud platform. Make the new platform the easier path, with templates and support, and track legacy changes so they can be added to the migration scope.

Multi-tenant SaaS analytics

System designhardsenior · lead45 min
#multi-tenancy#serving#data-security

A B2B SaaS product (about 4,000 customer companies, from 5-seat startups to 50,000-seat enterprises) wants an in-product analytics tab. Each customer sees dashboards about their own usage, with sub-second loads, fresh to within 15 minutes. A few enterprises want a daily export of their raw data to their own warehouse. One customer must never see another customer's data.

Design the data model, storage, serving layer and isolation.

Read the full worked design →

Hint 1

Where is tenant isolation enforced, and what happens if one query forgets a filter?

Hint 2

Small and large tenants have very different volumes. Does one design fit both?

Show solution

Ingestion and model: product events land per tenant (tenant_id on every record) through the usual event pipeline. Models are built once with tenant_id as the leading key of every table, plus pre-aggregated tables at the grains the dashboards use (tenant × day × feature).

Serving: in-product dashboards need predictable sub-second latency and high concurrency, which is a poor fit for a general warehouse. Serve from a real-time OLAP store (ClickHouse, Druid, Pinot) or a cache of pre-aggregates, partitioned or sorted by tenant_id. An API layer between the product and the store injects the tenant from the authenticated session.

Isolation in depth: the tenant comes from the auth token, never from the request; the API adds the tenant filter itself; row-level security in the store enforces it again; and automated tests try cross-tenant access. Very large or regulated tenants can get dedicated tables or clusters (the "noisy neighbor" and compliance answer).

Exports: a per-tenant daily export to the customer's cloud storage, or warehouse data sharing, filtered by tenant, with its own audit log.

What a strong answer covers

  • tenant_id as a first-class key in every table and pre-aggregates at dashboard grain (weight 2)
  • Chooses a low-latency, high-concurrency serving store (OLAP/cache) behind an API (weight 2)
  • Isolation in depth: tenant from auth, enforced by API and row-level security, tested (weight 3)
  • Handles noisy neighbors and big tenants (dedicated resources, partitioning) (weight 2)
  • Per-tenant exports or sharing with auditing (weight 1)

Follow-ups

  • The product team wants each customer to define custom metrics. What changes?

    Store metric definitions as data (a metric spec per tenant: measure, filters, dimensions), validated against a fixed set of allowed fields, and compile them to SQL with a semantic layer. Add query limits and caching, since custom metrics make query cost less predictable.

  • How do you charge back serving cost per tenant?

    Measure resource usage per tenant: tag queries with the tenant id, record credits or slot time and bytes scanned, add storage per tenant, and allocate shared costs proportionally. Use the result for pricing tiers or usage-based billing.

Design a reliable partner file ingestion pipeline

System designmediummid · senior40 min
#file-ingestion#reject-handling#idempotency#slas

You integrate with 25 external partners (banks, logistics providers, a payroll vendor). Each sends daily files over SFTP: CSV or fixed-width, some encrypted, each with its own layout, and they occasionally resend corrected files. Finance needs the data loaded by 07:00, and partners need to hear about bad records quickly.

Design the ingestion: from file arrival to loaded warehouse tables, including validation, rejects, duplicates, late or missing files and monitoring.

Hint 1

What is the first thing you do with a file before parsing it, so you can always reprocess it later?

Hint 2

How does the pipeline know a file is complete, is the right one, and hasn't been loaded already?

Hint 3

Which problems should stop a load, and which should only quarantine some rows?

Show solution

1. Land and preserve. Pick files up from SFTP and copy them unchanged, with their metadata, to immutable raw storage (object storage, partitioned by partner and business date). Decrypt into a separate, access-controlled area. Raw files are the source of truth for reprocessing and audits; keep them per your retention policy.

2. Register every file in a load log. Record partner, file name, business date (from the name or header), size, checksum, received time and status. The log drives everything else:

  • Duplicates: the same checksum means skip; a new version for an already-loaded date means replace that date's data atomically.
  • Completeness: wait for a done or manifest file, or a stable size, before processing; check header and trailer control counts.
  • Expected-file calendar: each partner's schedule says which files should arrive, so missing ones alert at the deadline rather than when someone notices.

3. Parse with layouts as configuration. A versioned layout per partner (positions or columns, types, formats, the effective date). Generic parsers read the config, so a new partner is new configuration rather than new code.

4. Validate in two tiers.

  • File-level (trailer mismatch, wrong date, unreadable): fail the whole file and alert. Loading part of a file publishes a misleading picture.
  • Row-level (bad formats, missing keys, unknown codes): write rejects to a quarantine table with file, line, reason and raw content; load the valid rows if the reject rate is under the partner's threshold, otherwise fail.

5. Load idempotently. Stage, then upsert by business key or overwrite the business-date partition, in one transaction. Re-running any file or date gives the same result, so resends and backfills are routine.

6. Close the loop.

  • Daily reject reports to each partner (automated email or portal) with line numbers and reasons.
  • Alerts on missing or late files, failures and reject-rate spikes, routed to the owning team, with an SLA dashboard per partner against the 07:00 target.
  • Runbooks for the common cases: resend, late file, layout change.

Security: PGP keys in a secrets manager, separate credentials per partner, PII masked or restricted in the raw zone, and access logged.

What a strong answer covers

  • Lands files unchanged in immutable storage before processing (weight 2)
  • Uses a load log with checksums for duplicates, resends and completeness (manifest/trailer), plus an expected-file calendar (weight 3)
  • Separates file-level failures from row-level rejects, with quarantine and thresholds (weight 3)
  • Loads idempotently (upsert or partition overwrite) so resends and backfills are safe (weight 2)
  • Monitors SLAs and reports rejects back to partners; handles keys and PII securely (weight 2)

Follow-ups

  • A partner changes their layout without warning and every row is rejected. What happens, and what should happen?

    The reject-rate threshold fails the file instead of loading nothing silently, and the owner is alerted with sample rejected lines. The fix is a new layout version with an effective date, then reprocessing the raw file from storage. Afterwards, agree on change notice with the partner and add a header-based layout check.

  • Finance asks to see exactly which file and line produced a number in their report. How do you support that?

    Carry lineage columns through the pipeline: source file id (from the load log) and line number on each staged row, and keep them in the warehouse tables or a link table. Combined with immutable raw files, any figure can be traced back to its original line.

Reconcile the internal payments ledger with processor settlements

System designhardsenior · lead45 min
#reconciliation#fintech#data-quality

A fintech records every payment in its own ledger (an event stream of payment state changes). Each night, three card processors and two banks send settlement files (CSV/SFTP, one of them an API) listing what they actually settled, with fees, FX and their own IDs.

Finance needs, by 08:00 each day: matched transactions, unmatched items on both sides with ageing, fee and FX differences, and a sign-off that totals tie out. Design the system.

Read the full worked design →

Hint 1

What's the matching key when the processor doesn't know your payment ID?

Hint 2

Unmatched isn't a failure state; it's a queue. What does it need?

Show solution

Ingest the ledger events (CDC or stream) and the processor files into an immutable raw zone with file-level metadata (source, file name, checksum, received_at), and reject duplicate files by checksum. Normalize every source into one canonical settlement schema (amount in minor units, currency, value date, processor reference, our reference if present). Matching runs in tiers: exact on reference ID, then on (amount, currency, card fingerprint, date ± 1 day), then fuzzy rules, each with a confidence and rule ID. Outputs are recon_matches, recon_breaks (with reason and age) and daily control totals per source that must tie out (ledger total = matched + unmatched ± fees/FX).

The main points: money as integers, never floats; idempotent re-runs per business date; files arrive late or twice, so the run is keyed by business date, not arrival; breaks form a workflow (owner, status, notes) and age-out alerts; everything is auditable (which rule matched what, which file version).

What a strong answer covers

  • Canonical schema across sources; money in minor units / decimals, not floats (weight 2)
  • Tiered matching (exact ID, then attribute-based, then fuzzy) with recorded rule/confidence (weight 3)
  • Control totals that must tie out, and a sign-off gate (weight 3)
  • Idempotent, re-runnable by business date; handles late and duplicate files (weight 2)
  • Breaks as a workflow with ageing and ownership (weight 2)
  • Audit trail: immutable raw files, file checksums, match lineage (weight 2)

Follow-ups

  • A processor resends yesterday's file with corrections. What gets recomputed, and how do you show finance what changed?

    Load the new file as a new version (keep the old one), rerun matching for that settlement date, and recompute that day's reconciliation and every later balance it affects. Produce a diff report (rows changed, matches gained or lost, amount differences) for finance before replacing the published result.

  • How would you measure and improve the auto-match rate over time?

    Track auto-match rate = auto-matched rows / total rows, per processor and day, on a dashboard. Review unmatched cases by reason (rounding, fees, timing, missing references), then add matching rules or fix upstream data for the biggest buckets, and measure again.

Real-time fraud features

System designhardsenior · lead45 min
#stream-processing#feature-engineering#ml-data

A payments company scores every card transaction for fraud before approving it. The model needs features such as "number of transactions on this card in the last 10 minutes", "amount spent on this card in the last 24 hours", "distinct merchants in the last hour" and "is this device new for this account?".

Scoring must take under 50 ms at p99, at 5,000 transactions per second at peak. Data scientists also need the same features, computed exactly the same way, for training on two years of history. Design the feature pipeline.

Read the full worked design →

Hint 1

The feature has to be ready before the transaction it describes is scored. What does that mean for the current transaction?

Hint 2

How do you guarantee training sees what the online model would have seen?

Show solution

Two paths, one definition: transactions flow through Kafka into a stream processor (Flink) that maintains sliding or hopping window aggregates per card, device and account in state, and writes the latest values to a low-latency online store (Redis, DynamoDB, Cassandra or a feature store's online tier). The scoring service reads features by key in a few milliseconds, combines them with request-time features computed from the current transaction itself, and calls the model.

Offline: the same feature definitions compute history over the event log for training, with point-in-time joins so each training example only sees feature values as of its timestamp. A feature store (Feast, Tecton, Databricks) or one shared code path for both paths prevents training/serving skew. Log the served feature vector with each score to train on what was actually served.

Key decisions: whether the current transaction is included in its own windows (decide explicitly; usually computed at request time); event time with a small watermark; exactly-once or idempotent state updates; TTLs on keys; fallbacks when features are missing or stale (the model must still answer within 50 ms).

What a strong answer covers

  • Separates online (low-latency store) and offline (training) paths from one feature definition (weight 3)
  • Streaming window aggregates in a stateful processor keyed by card/device/account (weight 2)
  • Point-in-time correct training data and logging of served features to avoid skew (weight 3)
  • Latency budget: request-time features, online store reads, fallbacks for missing/stale values (weight 2)
  • Addresses event time, late events and state size/TTL (weight 1)

Follow-ups

  • A new feature needs 90-day history. How do you backfill it into the online store without downtime?

    Compute the 90-day history offline in batch from the historical events, write it to the online store under the same keys (bulk load), and let the stream keep it current from a cut-over point. Overlapping by a little and making writes idempotent avoids gaps. Serve the feature only after it's verified, behind a flag.

  • How would you detect that an online feature has drifted from its offline definition?

    Log the online feature values at inference time, recompute the same features offline for the same entities and timestamps, and compare them (match rate, distribution difference). Alert when the mismatch exceeds a threshold. Sharing one feature definition for both paths also reduces drift.

Keep dashboards fast while loads and ad-hoc queries compete

System designhardsenior · lead40 min
#workload-management#performance#materialized-views#cost

Every morning between 08:00 and 10:00, executive dashboards on your cloud warehouse slow from 3 seconds to over a minute. During the same window, the overnight ELT is still finishing its last loads, about 40 analysts start running ad-hoc queries, and a data science team runs a large feature extraction.

Design how the warehouse should handle these competing workloads so dashboards meet a 5-second target, without simply buying a much bigger warehouse. Cover isolation, prioritization, what you'd precompute, and how you'd monitor it.

Hint 1

Are the dashboards slow because their queries got slower, or because they wait? How would you tell?

Hint 2

Which of these workloads needs to finish by 08:00, and which can wait or run elsewhere?

Hint 3

What can a dashboard read instead of scanning the 4-billion-row fact table every time?

Show solution

1. Diagnose before changing anything. From query history, split dashboard latency into queue time and execution time. Long queues mean contention for compute (concurrency slots, warehouse size); long execution with the same plan means resource sharing (cache, memory, I/O); a changed plan means a data or statistics problem. Also check whether ELT really should still be running at 08:00.

2. Isolate workloads.

  • Separate compute per workload where the platform allows it: in Snowflake, separate virtual warehouses for ELT, BI, ad-hoc and data science, each sized and auto-suspended on its own; in BigQuery, reservations and assignments per workload; in Redshift, workload management (WLM) queues with query priorities, and concurrency scaling for read bursts.
  • Give the BI workload priority and a reserved share; cap ad-hoc queries with timeouts and limits on the bytes they may scan; move the data science extraction to a separate cluster, a schedule outside business hours, or unloaded files in the lake.

3. Precompute what dashboards read.

  • Aggregate tables or materialized views at the grain the dashboards need (daily revenue by region and product), refreshed incrementally after the ELT, so dashboards read thousands of rows, not billions.
  • Result caching: identical queries on unchanged data return cached results (Snowflake persisted results, BigQuery cached results). Keep dashboard SQL stable so the cache hits.
  • A BI-tool extract or semantic-layer cache for the highest-traffic views.

4. Fix the schedule. Make the critical ELT finish earlier: start sooner, run independent models in parallel, make heavy models incremental, and publish the dashboard tables first. Set an SLA for "dashboard tables ready by 07:30" with an alert.

5. Monitor and control cost. Track per workload: p95 dashboard latency, queue time, credits or slot usage, and the share of dashboard queries served from aggregates or cache. Alert when p95 passes 5 seconds. Isolation can cost more if every warehouse runs all day, so use auto-suspend and right-size each one, and show the cost per workload.

Trade-off to state: separate compute gives the strongest isolation but adds cost and governance overhead; queues and priorities share one pool more cheaply but protect dashboards less. A small team often starts with priorities plus aggregates and isolates only the noisiest workload.

What a strong answer covers

  • Separates queue time from execution time to find the real cause (weight 2)
  • Isolates workloads (separate compute, queues/priorities, reservations) and protects BI (weight 3)
  • Precomputes with aggregate tables / materialized views and uses result caching (weight 3)
  • Fixes the ELT schedule and SLA, and monitors latency, queueing and cost per workload (weight 2)

Follow-ups

  • A materialized view keeps the dashboard fast, but refreshing it after every small load costs a lot. What are your options?

    Refresh on a schedule that matches the dashboard's freshness need instead of after every load, or replace it with an incrementally built aggregate table that only processes new partitions. Check whether the view's grain is finer than the dashboards actually use.

  • Analysts complain that the new ad-hoc limits block legitimate heavy queries. How do you handle it?

    Give a supported path instead of a blanket block: a larger ad-hoc warehouse or queue that users can request, scheduled heavy queries off-peak, or curated aggregate tables that answer common heavy questions. Review which queries hit the limits and fix the patterns (missing filters, SELECT *).

Further reading

Writing idempotent, backfillable Airflow DAGs

Toolsmediumjunior · mid · senior20 min
#airflow#orchestration#idempotency#backfills

A teammate's Airflow DAG loads "yesterday's" orders like this:

def load():
    day = datetime.now().date() - timedelta(days=1)
    rows = api.fetch(day)
    warehouse.insert("orders", rows)

It works every night, but rerunning a failed day or backfilling last month gives wrong data. Explain why, and how to write the DAG so any run can be retried or backfilled safely. Cover the Airflow features you'd use.

Hint 1

What date does this task process when you rerun last Tuesday's run today?

Hint 2

What does running it twice do to the table?

Show solution

Two bugs:

  1. It uses the wall clock. datetime.now() makes the task process "yesterday relative to when it runs", not the interval the run is for. A rerun of last Tuesday loads today's yesterday. Every backfill run loads the same day.
  2. It appends. insert on a retry or rerun duplicates the day's rows.

The fix: pure functions of the run's interval, plus idempotent writes.

  • Use the run's data interval: data_interval_start / data_interval_end (or the {{ ds }} template / logical_date in the context). Every run, including backfills and retries, then processes exactly its own window.
  • Overwrite that window: write to a partition for the date (or DELETE … WHERE day = ds + INSERT in one transaction, or MERGE on a key). Running a day twice gives the same result.
  • Land raw extracts under a path that includes the date, so reprocessing doesn't need to hit the API again.

Airflow features that help:

  • catchup=True with a start_date creates runs for missed intervals; airflow dags backfill -s … -e … (or the backfill feature in newer versions) reruns a range.
  • max_active_runs and pools limit how many backfill runs hit the source at once.
  • retries with retry_delay for transient failures, which is only safe because the task is idempotent.
  • Deferrable sensors to wait for upstream files without holding a worker slot.
  • Keep heavy work out of the DAG file's top level. It's parsed constantly by the scheduler.

What a strong answer covers

  • Identifies wall-clock time as the backfill/rerun bug and uses the data interval / logical date (weight 3)
  • Makes writes idempotent: overwrite the partition, delete+insert, or MERGE (weight 3)
  • Uses Airflow features correctly: catchup/backfill, max_active_runs or pools, retries (weight 2)
  • Mentions keeping raw extracts per date and avoiding top-level DAG code (weight 1)

Follow-ups

  • The task depends on a dimension table that changes over time. In a backfill, should it read today's version or the historical one?

    Normally the historical version, as of the run's logical date (data_interval_start), using an SCD2 or snapshot table. Then a backfill produces the same output the original run should have produced. Use today's version only if the business wants restated history.

  • How would you make a backfill of 90 days finish overnight without starving the daily run?

    Run the backfill in a separate DAG or with max_active_runs and pools limited, give the daily DAG a higher priority weight, and process in larger date chunks per task if the task supports it. Watch the warehouse load as well as Airflow's own concurrency.

Further reading

BigQuery partitioning, clustering and query cost

Toolsmediummid · senior20 min
#bigquery#partition-pruning#cost

On BigQuery's on-demand pricing, an analyst's dashboard query costs far more than expected:

SELECT * FROM analytics.events
WHERE DATE(event_ts) >= '2024-06-01' AND customer_id = 'C-42'
LIMIT 100;

events is 30 TB, partitioned by DATE(event_ts), not clustered. Explain how BigQuery bills this query, why it's expensive, and how you'd fix both the query and the table.

Hint 1

On-demand pricing charges for what, exactly?

Hint 2

Does LIMIT reduce the bytes read?

Show solution

Billing. With on-demand pricing BigQuery charges for bytes processed, meaning the data in the columns read across the partitions scanned. Not rows returned, not runtime. (Capacity pricing, billed in slots, is the alternative for steady heavy workloads.)

Why it's expensive:

  • SELECT * reads every column. BigQuery is columnar, so selecting only the 4 columns you need can cut cost by 10× or more.
  • LIMIT 100 doesn't reduce bytes scanned. The filter and scan happen first.
  • The date filter does prune partitions, but from June to today that may still be months of data. customer_id gives no pruning at all, because the table isn't clustered.

Fixes:

  1. Query: select only the needed columns, and filter on the partitioning expression with a tight range.
  2. Cluster the table by the columns most often filtered (for example customer_id, then event_name; up to 4 columns). Within each partition, BigQuery can then skip blocks that can't match, which helps selective filters like one customer a lot.
  3. Require partition filters (require_partition_filter = true) so nobody scans 30 TB by accident.
  4. For dashboards, build a pre-aggregated table or materialized view at the grain the dashboard needs, instead of querying raw events.
  5. Guardrails: set maximum bytes billed per query, and review the most expensive queries in INFORMATION_SCHEMA.JOBS regularly.

What a strong answer covers

  • Explains on-demand billing by bytes processed (columns × partitions), not rows (weight 3)
  • Calls out SELECT * and that LIMIT does not reduce cost (weight 2)
  • Proposes clustering by filtered columns and partition-filter enforcement (weight 2)
  • Adds structural fixes: pre-aggregated tables and cost guardrails (weight 2)

Follow-ups

  • When would you switch from on-demand to capacity (slot) pricing?

    When your on-demand spend is high and steady enough that reserved slots cost less, or when you need predictable spend. Look at your historical bytes processed and slot usage. Capacity pricing also lets you isolate workloads with reservations, but queries can queue when slots are busy.

  • Partition by ingestion time or by event time? What changes for late events?

    Ingestion-time partitioning puts late events in the partition of the day they arrived, so queries by event date must scan several partitions, and backfills are awkward. Event-time partitioning matches how users filter, but late events modify old partitions, so incremental models need a lookback window.

Further reading

Cloud networking for data engineers (VPCs, endpoints, NAT)

Toolsmediummid · senior20 min
#networking#aws#cost

Two problems on your AWS data platform:

  1. A new Glue job that reads from a PostgreSQL database on RDS (in a private subnet) fails with a connection timeout. The credentials are correct.
  2. The monthly bill shows a large "NAT Gateway" line. Most of it comes from EMR clusters in private subnets reading and writing several TB a day in S3.

Explain the networking concepts involved and how you'd fix both.

Hint 1

A timeout (rather than "authentication failed") tells you the packets never got an answer. What sits between the job and the database?

Hint 2

How does traffic from a private subnet reach S3, and is there a path that doesn't go through the NAT gateway?

Show solution

The concepts:

  • A VPC is a private network. Subnets are public (with a route to an internet gateway) or private (no direct inbound access from the internet).
  • Route tables decide where traffic goes. Security groups are stateful firewalls on each network interface: they allow specific inbound and outbound traffic.
  • A NAT gateway lets private resources reach the internet and public service endpoints; it is billed per hour plus per GB processed.
  • VPC endpoints let resources reach AWS services privately: gateway endpoints (S3 and DynamoDB, through route-table entries, no additional charge) and interface endpoints (PrivateLink, an elastic network interface in your subnet, billed hourly and per GB).

Problem 1: the Glue job times out. A timeout means the traffic is blocked or misrouted, not rejected by the database.

  • Glue needs a connection configured with the VPC, a subnet that can route to the database, and a security group. AWS Glue creates network interfaces in that subnet.
  • The database's security group must allow inbound traffic on port 5432 from the Glue job's security group.
  • The Glue security group needs a self-referencing inbound rule, because Glue's own components talk to each other.
  • The job's subnet also needs a route to S3 (a gateway endpoint or a NAT) for its scripts and temporary files.

Check these in order, testing reachability with the connection test or VPC Reachability Analyzer.

Problem 2: the NAT bill. Traffic from private subnets to S3 without an endpoint goes out through the NAT gateway and is charged per GB processed. Add an S3 gateway endpoint to the private subnets' route tables; S3 traffic then goes through the endpoint with no NAT processing charge, and you can restrict it with an endpoint policy. Do the same for DynamoDB if used. For other AWS services with heavy traffic, compare interface endpoint costs with NAT costs. Keep compute and buckets in the same region to avoid inter-region transfer charges.

What a strong answer covers

  • Explains VPC, subnets, route tables, security groups, NAT and endpoints (weight 2)
  • Diagnoses the timeout as network reachability: Glue connection subnet, DB security group inbound rule, self-referencing rule (weight 3)
  • Fixes the NAT cost with an S3 gateway endpoint and explains why it is cheaper (weight 3)
  • Mentions region alignment and interface endpoint trade-offs (weight 1)

Follow-ups

  • The security team requires that the lake bucket can only be reached from inside your VPC. How do you enforce it?

    Add a bucket policy that denies access unless the request comes through your VPC endpoint (an aws:SourceVpce condition), with exceptions for the admin roles you need, and an endpoint policy that only allows your buckets. Test carefully: it also blocks console and tool access from outside the VPC.

  • How would you find which jobs cause the most data transfer cost?

    Use cost allocation tags on clusters and jobs, Cost Explorer filtered by usage type (NAT processing, data transfer), and VPC Flow Logs to see which sources and destinations move the most bytes. Then fix the biggest flows first.

Further reading

Delta OPTIMIZE, Z-ordering and small files on Databricks

Toolsmediummid · senior20 min
#databricks#delta-lake#small-files#performance

A streaming job appends to a Delta table every minute. After three months, queries filtering on device_id and event_date are slow, and listing the table takes a long time. The table has 1.8 million files, most under 1 MB.

Explain why, and how OPTIMIZE, Z-ordering, liquid clustering and VACUUM help, including what each costs or risks.

Hint 1

How many files does a streaming job create per day if each micro-batch writes a few?

Hint 2

What does a reader need from file statistics to skip files?

Show solution

Why it's slow: the small-files problem. Every micro-batch commits new small files. Readers pay per file (opening it, reading the footer, tracking it in the transaction log), so a million tiny files make queries and metadata operations slow, even when the total data is modest.

OPTIMIZE compacts small files into larger ones (bin-packing). It's a regular maintenance job (for example nightly, or per partition), and it costs compute.

Data skipping and Z-ordering. Delta keeps per-file min/max statistics (on the first 32 columns by default) and skips files that can't match a filter. That only works if values are co-located. OPTIMIZE … ZORDER BY (device_id) rewrites files so rows with similar values of one or more columns sit together, which makes the min/max ranges narrow and skipping effective. It's a full rewrite of the affected data, and its benefit drops with every additional column.

Liquid clustering (CLUSTER BY) is the newer approach Databricks recommends for new tables. It replaces Hive-style partitioning and Z-ordering, clusters incrementally, and lets you change clustering keys without rewriting the table. For this table, cluster by event_date, device_id (or drop the date partitioning in favor of clustering).

At write time: optimized writes and auto compaction (or predictive optimization) reduce the number of small files a streaming job creates in the first place. Larger trigger intervals help too.

VACUUM deletes data files no longer referenced by the table (older than the retention period, 7 days by default). It saves storage, but removes time travel to versions older than that, and a too-short retention can break long-running readers. Don't lower it casually.

Order of work: turn on write-side compaction → schedule OPTIMIZE with clustering → VACUUM on a schedule with the default retention.

What a strong answer covers

  • Explains the small-files problem from frequent streaming commits (weight 2)
  • OPTIMIZE compaction plus data skipping via min/max stats; Z-order co-locates values (weight 3)
  • Mentions liquid clustering as the modern alternative and write-side optimizations (weight 2)
  • Explains VACUUM retention and its effect on time travel and readers (weight 2)

Follow-ups

  • How would you decide which columns to cluster by?

    Pick columns that are frequently used in selective filters or join keys and have high cardinality, usually one to four of them. Check query history for the most common predicates, and avoid columns already used for partitioning or ones that are rarely filtered on. Measure files skipped before and after.

  • What does this look like for an Iceberg table instead?

    Iceberg uses rewrite_data_files (compaction) with a sort order, including a z-order sort, set on the table. You also schedule snapshot expiration and orphan file removal, and partition transforms such as day(ts) or bucket(n, id) replace Hive-style partition columns.

Further reading

How dbt incremental models work, and when they go wrong

Toolsmediumjunior · mid · senior20 min
#dbt#incremental-models#late-arriving-data

Your fct_orders dbt model takes 40 minutes as a full table rebuild. You switch it to materialized='incremental'.

Explain how an incremental model works, what is_incremental() and unique_key do, which incremental strategies exist, and the ways an incremental model silently drifts from what a full refresh would produce.

Hint 1

What does the model's SQL look like on the first run versus later runs?

Hint 2

What happens to an order updated 3 days after it was first loaded?

Show solution

Mechanics. On the first run (or with --full-refresh), dbt builds the whole table. On later runs, is_incremental() is true and the model selects only new or changed rows, usually filtered against the existing table:

{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}

dbt then writes those rows into the existing table using an incremental strategy:

  • append: insert only. Fast, but duplicates rows if a key is reprocessed.
  • merge: upsert on unique_key. The common default on Snowflake, BigQuery and Databricks.
  • delete+insert: delete matching keys, then insert.
  • insert_overwrite: replace whole partitions (BigQuery, Spark). Great for date-partitioned facts.
  • microbatch (newer dbt versions): processes time-based batches and makes backfills by date range easy.

How it drifts from a full refresh:

  1. Late-arriving or updated rows. updated_at > max(updated_at) misses rows that arrive with older timestamps. Use a lookback window (updated_at > max - interval 3 days) together with merge / unique_key so reprocessing is idempotent.
  2. No unique_key with append: reprocessed rows are duplicated.
  3. Logic changes. Changing the SQL only affects new rows; old rows keep the old logic until a --full-refresh.
  4. Schema changes. New columns are ignored by default; set on_schema_change (append_new_columns, sync_all_columns or fail).
  5. Deletes in the source never reach an incremental model unless you handle them (soft-delete flags, or periodic full refreshes).

Good practice: test uniqueness on the key, compare row counts and key metrics against a periodic full refresh, and schedule a full refresh (for example weekly) for models whose logic can change.

What a strong answer covers

  • Explains first run vs incremental runs and the is_incremental() filter against {{ this }} (weight 2)
  • Names the strategies (append, merge, delete+insert, insert_overwrite) and when each fits (weight 2)
  • Handles late-arriving/updated rows with a lookback window plus unique_key (weight 3)
  • Mentions drift from logic/schema changes and deletes, and periodic full refresh or reconciliation (weight 2)

Follow-ups

  • The model is partitioned by order date and 2% of updates touch orders older than 30 days. Which strategy, and what lookback?

    Use merge (or delete+insert) on order_id with a lookback window, rather than insert_overwrite of only recent partitions, because old orders still change. The lookback should be based on updated_at, not order date, for example updated_at > max(updated_at) - 3 days. Add a periodic full refresh or a targeted rebuild for the rare very old updates.

  • How would you backfill 2 years of this model without one giant query?

    Backfill in date-range batches: use the microbatch strategy with --event-time-start and --event-time-end, or run with variables for the date range in a loop, one month at a time. Each batch is idempotent, so a failure only reruns that range.

Further reading

A testing strategy for a dbt project with dbt tests and contracts

Toolsmediummid · senior20 min
#dbt#data-quality#data-contracts#testing

Your dbt project has 300 models and almost no tests. Twice last quarter, bad data reached the finance dashboard: once a duplicated order inflated revenue, once an upstream team renamed a column and a model silently produced NULLs for a week.

How would you use dbt's features (data tests, unit tests, model contracts, source freshness, severity and CI) to stop this from happening again? What would you test first, and what would you deliberately not test?

Hint 1

Which of the two incidents would a unique test have caught, and which needs something that runs at build time instead?

Hint 2

With 300 models, where do tests give the most protection per minute of effort?

Show solution

Start where the incidents came from, then cover the critical path.

  1. Keys on every model: unique + not_null on the grain. This catches duplicate orders (the first incident) and fan-out joins. Use dbt_utils.unique_combination_of_columns for composite grains.
  2. Sources: freshness and schema. Declare sources with loaded_at_field and freshness (warn_after, error_after), and test source columns the models rely on (not_null, accepted_values). Freshness catches stalled loads.
  3. Model contracts (contract: {enforced: true}) on public, consumer-facing models: dbt checks column names and types at build time and fails the build if they don't match. Combined with not_null on the affected columns, the rename (the second incident) fails loudly on the first run instead of producing NULLs for a week. For the upstream team's side, agree a data contract (owned schema, change notice) with the producer.
  4. Business rules on marts: relationships between facts and dimensions, accepted_values on statuses, and custom singular tests such as "revenue ≥ 0" or "finance mart total equals the source ledger total" (reconciliation).
  5. Unit tests (dbt 1.8+) for tricky logic: fixed input rows → expected output, for things like SCD handling or currency conversion. They run in CI without production data.

Severity and blocking. Tests on keys and contracts are error and block downstream models (dbt build runs tests after each model, so a failure skips everything downstream, which acts as a circuit breaker for the dashboard). Noisier checks are warn, with warn_if / error_if thresholds. store_failures saves the failing rows for debugging.

CI: slim CI (dbt build --select state:modified+) runs changed models and their tests on every pull request, so a broken model never merges.

What not to test: don't put five generic tests on every column of every staging model. That's slow, noisy and ignored. Test grains, keys, the columns consumers use, and the business rules finance cares about. Every test should have an owner, and a failing test should mean someone acts.

What a strong answer covers

  • unique + not_null on every model grain (catches the duplicate-order incident) (weight 2)
  • Model contracts and/or not_null on consumed columns so schema changes fail at build time (the rename incident) (weight 3)
  • Source freshness, relationships/accepted_values and reconciliation tests on critical marts (weight 2)
  • Severity, blocking with dbt build, slim CI, and a focused scope (not testing everything) (weight 2)

Follow-ups

  • A test has failed with severity warn every day for two months. What do you do?

    A test nobody acts on is noise. Either fix the underlying data, make it an error with a real owner, adjust the threshold to what's actually acceptable, or delete it. Track alert fatigue: failing-but-ignored tests hide new failures.

  • How do dbt contracts differ from a data contract with the producing team?

    A dbt contract only checks a model's own output columns and types at build time, inside your project. A data contract is an agreement with the producing team about their data (schema, semantics, freshness, change process), enforced at their side or at ingestion, so breaking changes are caught before they reach you.

Further reading

ETL tools (Informatica, SSIS, Data Factory) and moving to ELT

Toolsmediummid · senior20 min
#etl-tools#migrations#incremental-loads

Your company runs about 300 Informatica PowerCenter and SSIS jobs that extract from operational databases and files, transform the data on the ETL server, and load a SQL Server warehouse. Leadership wants to move to a cloud warehouse with an ELT approach (load raw data first, transform with SQL in the warehouse, for example with dbt).

Explain how traditional ETL tools are structured, what "pushdown" means, how ETL and ELT differ in practice, and how you'd plan the migration.

Hint 1

Where does the transformation run in each approach, and what does that mean for scaling and cost?

Hint 2

What do these tools give you besides transformations (scheduling, error handling, lineage)? Something has to replace each of those.

Show solution

How the tools are structured. Traditional ETL tools are visual: you build data flows from sources, transformations and targets, then wrap them in control flows that handle ordering, retries and parameters.

  • Informatica PowerCenter: mappings (source → transformations → target) run by sessions, which workflows orchestrate.
  • SSIS: packages with a control flow (tasks, precedence) and data flows (sources, transformations, destinations).
  • Azure Data Factory: pipelines of activities (copy, data flow, stored procedure) with triggers, plus mapping data flows that run on managed Spark.

These tools also provide connectors, scheduling, error rows (reject outputs), logging and some lineage.

ETL vs ELT.

  • ETL: transformations run on the ETL engine's servers, row by row or in its own memory. That engine has to scale with your data, and it's licensed and operated separately.
  • ELT: raw data is loaded first and transformed with SQL inside the warehouse, which scales compute on demand. Transformations live as versioned SQL with tests and CI, and the raw data stays available for reprocessing.
  • Pushdown optimization is the middle ground: the ETL tool translates parts of a mapping into SQL that runs in the source or target database, instead of moving the rows through its own engine.

Planning the migration.

  1. Inventory and triage: list the jobs with their sources, targets, schedules, consumers and last run. Retire jobs nobody uses.
  2. Classify: some jobs are simple extract-and-load (replace with a managed ingestion or copy tool); most are transformation logic (rewrite as SQL models); a few have complex procedural logic (rewrite carefully, or keep temporarily).
  3. Land raw first: set up ingestion into the cloud warehouse with the same incremental logic (watermarks, CDC), so the old and new pipelines can run in parallel.
  4. Rebuild transformations as SQL models in layers (staging → intermediate → marts), adding tests that the old jobs never had.
  5. Replace the hidden features: scheduling and dependencies (an orchestrator), reject handling (quarantine tables and data tests), logging and alerting, lineage.
  6. Prove parity: run both pipelines side by side and compare row counts, sums and key metrics automatically, then cut over consumers in waves.

Watch out for: logic hidden in stored procedures, ETL tool expressions with different NULL or rounding behavior, and scheduler dependencies that live outside the ETL tool (for example Control-M or Autosys).

What a strong answer covers

  • Describes the structure of ETL tools (mappings/packages/pipelines, control vs data flow) (weight 2)
  • Contrasts ETL and ELT on where compute runs, scaling, versioning and reprocessing; explains pushdown (weight 3)
  • Plans the migration: inventory, classify, land raw, rebuild in SQL, parallel run and parity checks (weight 3)
  • Replaces what the tools did implicitly (scheduling, rejects, logging, lineage) (weight 2)

Follow-ups

  • A PowerCenter mapping uses a lookup with a cache and an update strategy. What does that become in SQL?

    The cached lookup becomes a join (usually a LEFT JOIN to the lookup table, with the same handling of misses), and the update strategy (insert, update, reject) becomes a MERGE or an incremental model with a unique key, plus a reject table for rows the strategy rejected.

  • When would you keep an ETL tool rather than move everything to ELT?

    When the transformation must happen before data lands (masking PII before it leaves a regulated network), when sources are niche systems that only the tool has connectors for, or when the team's skills and support contracts make a rewrite riskier than the benefit. Many teams keep the tool for extraction and do transformations in the warehouse.

Further reading

IAM and least privilege for data pipelines

Toolsmediummid · senior20 min
#iam#data-security#aws

A new AWS data platform has 30 pipelines (Glue jobs, Lambda functions and Airflow tasks) reading from and writing to S3, a Redshift cluster and a few RDS databases. Today they all use one IAM user's access keys, stored in a config file, with an AdministratorAccess policy "so nothing breaks".

Explain what's wrong, and how you'd redesign identity and access for the pipelines. How do you keep it least-privilege without blocking the team every week?

Hint 1

What's the difference between an IAM user with access keys and a role that a service assumes?

Hint 2

If one pipeline is compromised, what should it be able to reach?

Show solution

What's wrong:

  • Long-lived access keys in a config file can leak (repositories, logs, laptops) and never expire.
  • One identity for everything means no isolation and no useful audit trail: every action looks like the same user.
  • Administrator access means a bug or a leaked key can delete data, open buckets to the internet or create resources anywhere.

Redesign:

  1. Roles, not users. Each workload assumes an IAM role and gets temporary credentials automatically: Glue job roles, Lambda execution roles, and roles for Airflow workers (for example through the managed Airflow service's execution role or Kubernetes service accounts mapped to roles). No access keys on disk.
  2. One role per pipeline or domain, scoped to what it touches. A role for the orders ingestion job can read the source bucket prefix and write s3://lake/raw/orders/* only, use the specific KMS key, and write its Glue catalog table, and nothing else. Separate read and write; separate dev and prod accounts.
  3. Secrets in a secrets manager. Database passwords live in AWS Secrets Manager (with rotation) or come from IAM database authentication; the role is allowed to read only its own secrets.
  4. Guardrails above the roles: account separation per environment, organization-level policies (service control policies) that forbid things like public buckets or disabling logging, and bucket policies that require encryption and deny access from outside the organization.
  5. Data-level access for people and tools querying the lake: Lake Formation or the warehouse's grants for table, column and row permissions, rather than broad S3 access.

Keeping it practical:

  • Define roles and policies as code (Terraform), reviewed in pull requests, with a module per pipeline type, so a new pipeline gets a correct role by default.
  • Start from AWS-managed or broader policies in dev, then use IAM Access Analyzer to generate policies from actual activity and tighten them before production.
  • Log with CloudTrail and alert on denied calls and unusual activity.

What a strong answer covers

  • Identifies long-lived keys, a shared identity and admin permissions as the risks (weight 2)
  • Uses roles with temporary credentials per workload instead of access keys (weight 3)
  • Scopes each role to specific resources and prefixes; keeps secrets in a secrets manager (weight 2)
  • Adds guardrails (account separation, SCPs, bucket policies), data-level access, policies as code and least-privilege tooling (weight 2)

Follow-ups

  • A pipeline in the analytics account needs to read a bucket in the payments account. How do you grant it?

    Cross-account access: the payments account's bucket policy (and KMS key policy, if encrypted) allows a specific role from the analytics account, and that role has a policy allowing the read. Alternatively the pipeline assumes a read-only role in the payments account. Either way, grant only the needed prefix and actions.

  • After tightening permissions, a job fails with AccessDenied in production. How do you debug it quickly?

    Read the error: it names the action and resource. Check CloudTrail for the denied call, then the role's policies, any bucket or key policies, and organization policies, since an explicit deny anywhere wins. Fix with the narrowest grant, in code, and add the case to the dev environment so it's caught earlier next time.

Further reading

Iceberg vs Delta Lake vs Hudi

Toolshardsenior · lead25 min
#table-formats#lakehouse#architecture

Your company is building a lakehouse on object storage. Data engineers use Spark; analysts use Trino today, and the CFO wants the option to query the same tables from Snowflake later. One team does heavy upserts from CDC.

What problem do open table formats solve, what do Apache Iceberg, Delta Lake and Apache Hudi have in common, how do they differ, and which would you choose here?

Hint 1

What goes wrong if two jobs write Parquet files into the same folder at once?

Hint 2

The deciding factor is often the engines and catalog, not the file layout.

Show solution

The problem. A folder of Parquet files has no transactions. Concurrent writers corrupt each other, readers see half-written data, there's no reliable schema evolution, and updates mean rewriting folders by hand. Table formats add a metadata layer on top of the data files that defines exactly which files make up each version of a table.

What all three give you: ACID commits on object storage, snapshots and time travel, schema evolution, row-level updates and deletes (via copy-on-write or merge-on-read with delete files), and statistics for pruning.

How they differ (in broad strokes; all three move fast):

  • Apache Iceberg: metadata tree of snapshots, manifest lists and manifests. Hidden partitioning with transforms (days(ts), bucket(n, id)) and partition evolution without rewriting data. Very broad engine support (Spark, Flink, Trino, plus many warehouses including Snowflake and BigQuery) and a standard REST catalog. Built for multi-engine use.
  • Delta Lake: transaction log (_delta_log) of JSON commits plus checkpoints. Deepest integration with Spark and Databricks (OPTIMIZE, liquid clustering, change data feed). UniForm can expose Delta tables with Iceberg metadata for other engines.
  • Apache Hudi: designed first for upserts and incremental processing: record-level indexes, copy-on-write vs merge-on-read tables, and incremental queries ("give me what changed since commit X"). Strong for CDC-heavy ingestion.

Recommendation here: Iceberg as the default format. Spark, Trino and a future Snowflake all read and write it natively, and a REST catalog keeps engines from fighting over metadata. The CDC team's upserts work with Iceberg's merge-on-read deletes plus regular compaction. If that team's write volume proves Iceberg's MERGE costs too high, Hudi (or Delta) for that one ingestion layer is a defensible exception.

Things that matter more than the format: the catalog choice, a compaction and snapshot-expiry schedule (small files and orphaned files are where lakehouses rot), and access control.

What a strong answer covers

  • Explains the problem table formats solve (transactions/metadata over files) (weight 2)
  • Lists shared capabilities: ACID, snapshots/time travel, schema evolution, row-level changes (weight 2)
  • Differentiates them accurately (Iceberg hidden partitioning/multi-engine, Delta log/Spark, Hudi upserts/incremental) (weight 3)
  • Makes a recommendation driven by engines and catalog, and covers compaction/maintenance (weight 3)

Follow-ups

  • Two writers commit to the same Iceberg table at the same moment. What happens?

    Iceberg uses optimistic concurrency: both writers prepare their files, then each tries to atomically swap the catalog's metadata pointer. One wins. The other detects the conflict, re-checks whether its changes conflict with the new snapshot, and retries the commit, or fails if both modified the same data.

  • What maintenance jobs does a lakehouse table need, and what happens if you skip them?

    Compaction (small files), snapshot expiration, orphan file cleanup and, for Iceberg, manifest rewrites. Skip them and queries slow down (many files and manifests), and storage costs grow because old snapshots and unreferenced files are never deleted.

Further reading

Indexes in row stores vs columnar warehouses

Toolsmediummid · senior20 min
#indexes#columnar-storage#performance

Your team is moving reporting from SQL Server to a cloud columnar warehouse. A senior DBA asks: "Where do I create the indexes? Our reports depend on 40 of them."

Explain how indexes work in a row store like SQL Server or Postgres, why columnar warehouses mostly don't use them, what replaces them, and when SQL Server's own columnstore indexes fit in.

Hint 1

What does a B-tree index help you find, and what does a reporting query usually need instead?

Hint 2

What metadata does a columnar engine keep per block of data?

Show solution

Row stores and B-tree indexes. A row store keeps whole rows together. A B-tree index is a sorted structure on one or more columns that lets the engine seek directly to matching rows instead of scanning the table. It's ideal for selective lookups (WHERE order_id = 42, a customer's last 10 orders). A clustered index defines the table's physical order; nonclustered indexes are separate structures pointing to rows, and a covering index includes every column a query needs so the table isn't touched. The cost: every insert, update and delete must also maintain each index, so many indexes slow loads, and they take storage.

Why columnar warehouses don't need them. Reporting queries read many rows but few columns (sum revenue by region for a month). Columnar engines store each column separately and compressed, so a query reads only the columns it uses. Instead of indexes they keep min/max metadata per block or micro-partition (zone maps) and skip blocks that can't match: pruning. Physical layout does the job indexes did:

  • Sort or cluster large tables by the columns most used in filters (sort keys in Redshift, clustering keys in Snowflake and BigQuery, Z-ordering or liquid clustering on Delta).
  • Partition by date.
  • Distribute for joins in MPP engines.
  • Materialized views or aggregate tables for repeated heavy aggregations, and search optimization features for rare point lookups.

SQL Server columnstore indexes bring the columnar format into SQL Server itself: a clustered columnstore stores the whole table by column (the default in Azure Synapse dedicated pools), suited to large fact tables and analytics; a nonclustered columnstore can sit on a row-store table to serve analytic queries alongside OLTP.

For the migration: inventory the 40 indexes and the queries they serve. Most map to a sort or clustering key, a partition, or simply disappear because column scans with pruning are fast enough. Point lookups that remain need a different answer (search optimization, or serving them from an operational store).

What a strong answer covers

  • Explains B-tree seeks, clustered vs nonclustered/covering indexes, and their write cost (weight 2)
  • Explains columnar storage, compression and min/max pruning instead of indexes (weight 3)
  • Maps index use cases to sort/cluster keys, partitioning, distribution and aggregates (weight 2)
  • Knows SQL Server clustered vs nonclustered columnstore indexes and where they fit (weight 2)

Follow-ups

  • A table in SQL Server has 15 nonclustered indexes and the nightly load got 4× slower. What do you check?

    Index maintenance during the load: each insert updates all 15 indexes. Check which indexes are actually used (index usage statistics), drop unused ones, and for large loads consider disabling or dropping nonclustered indexes, loading, then rebuilding them. Also check fragmentation and whether a columnstore suits the table better.

  • When does a columnar warehouse still struggle, even with good clustering?

    Highly selective point lookups on a high-cardinality column that isn't the clustering key, very wide SELECT * queries, frequent single-row updates, and many small concurrent queries. Those suit an OLTP database, a key-value store, or the warehouse's search optimization and caching features.

Further reading

Kafka delivery guarantees, idempotent producers and exactly-once

Toolshardmid · senior · lead25 min
#kafka#delivery-semantics#idempotency

A payments team asks you: "Does Kafka guarantee exactly-once delivery? We consume payments, enrich each event and write it to payments_enriched, and a separate consumer writes payments_enriched into Postgres."

Explain at-most-once, at-least-once and exactly-once in Kafka, the producer and consumer settings involved, what exactly-once really covers, and how you'd make the Postgres write safe.

Hint 1

When does a consumer commit its offset relative to processing?

Hint 2

Exactly-once inside Kafka is not the same as exactly-once into an external database.

Show solution

The three semantics:

  • At-most-once: the consumer commits the offset before processing. A crash loses messages, but none are duplicated.
  • At-least-once: commit after processing. A crash between processing and commit reprocesses messages, so duplicates are possible. This is the common default.
  • Exactly-once: each message affects the output once, even with retries and crashes.

Producer side:

  • acks=all waits for all in-sync replicas. With min.insync.replicas=2 on the topic and replication factor 3, an acknowledged write survives a broker failure.
  • enable.idempotence=true (the default in recent Kafka versions) gives each producer an ID and sequence numbers, so retries don't create duplicates and per-partition order is kept.

Exactly-once inside Kafka (read → process → write): the enrichment job uses transactions (transactional.id). It writes output records and commits its consumer offsets in one atomic transaction. Downstream consumers set isolation.level=read_committed so they never see aborted writes. Kafka Streams turns this on with processing.guarantee=exactly_once_v2. So payments → payments_enriched can be exactly-once.

Into Postgres it's a different problem. Kafka transactions don't cover an external database. Options:

  1. Idempotent writes: at-least-once consumption plus an upsert keyed on payment_id (INSERT … ON CONFLICT (payment_id) DO UPDATE or DO NOTHING). A reprocessed message changes nothing. This is the usual answer.
  2. Store offsets in Postgres in the same database transaction as the data, and on startup seek to the stored offsets. That gives an atomic data-plus-offset commit.

Bottom line: exactly-once is a property of the whole pipeline. Use Kafka transactions between Kafka topics, and idempotency or transactional offset storage at the edges.

What a strong answer covers

  • Correctly ties at-most/at-least-once to commit-before vs commit-after processing (weight 2)
  • Producer durability and dedup: acks=all, min.insync.replicas, enable.idempotence (weight 2)
  • Explains transactions + read_committed for read-process-write exactly-once within Kafka (weight 3)
  • States that external sinks need idempotent upserts or transactional offset storage (weight 3)

Follow-ups

  • What does exactly-once cost in latency and throughput, and when would you not use it?

    Transactions add commit overhead and latency (consumers using read_committed wait for commits), and reduce throughput somewhat. Skip exactly-once when the sink is idempotent anyway (upserts by key), when you can deduplicate downstream, or when occasional duplicates don't matter, such as for metrics.

  • A consumer is stuck in a rebalance loop and keeps reprocessing the same batch. What settings would you look at?

    Processing takes longer than max.poll.interval.ms, so the consumer is kicked out and the batch replays. Lower max.poll.records, raise max.poll.interval.ms, or speed up processing. Also check session.timeout.ms and heartbeats, and consider cooperative rebalancing and static membership (group.instance.id).

Further reading

Kafka partitions, keys and ordering guarantees

Toolsmediummid · senior20 min
#kafka#ordering#partitioning

An orders topic has 6 partitions. Events for one order (created, paid, shipped) must be processed in order. Consumers in one group are falling behind, and someone proposes going to 24 partitions and 24 consumers.

Explain Kafka's ordering guarantees, how keys map to partitions, how consumer groups use partitions, and what can go wrong with the proposal.

Hint 1

Ordering is guaranteed within what, exactly?

Hint 2

What happens to the key-to-partition mapping when the partition count changes?

Show solution

Ordering. Kafka guarantees order only within a partition. Across partitions there's no global order.

Keys → partitions. The default partitioner hashes the record key and takes it modulo the partition count, so the same key always lands in the same partition, as long as the partition count doesn't change. To keep an order's events in sequence, use order_id as the key. Records without a key are spread across partitions, so their order is lost.

Consumer groups. Each partition is assigned to one consumer in a group at a time. Maximum parallelism equals the number of partitions: a 7th consumer on 6 partitions sits idle. Within a consumer, processing one partition sequentially preserves order. Handing records to a thread pool breaks it unless you parallelize by key.

Producer side. Retries can reorder writes. The idempotent producer (enable.idempotence=true) keeps per-partition order even with retries and several in-flight requests.

Problems with going 6 → 24 partitions:

  1. Remapping. hash(key) % 24 differs from % 6, so new events for an existing order may go to a different partition than its earlier events. During the switch, two consumers can process events of the same order concurrently and out of order. Mitigations: do it at a quiet time and drain lag first, or create a new topic with 24 partitions and migrate consumers, or make processing tolerant (version checks and idempotent state).
  2. Hot keys don't spread. One very busy key stays on one partition however many you add.
  3. The real bottleneck may be the consumer (slow database writes, per-record commits), not the partition count. Check lag per partition and processing time first.
  4. More partitions mean more open files, longer leader elections and more rebalancing, so don't over-provision.

What a strong answer covers

  • States ordering is per partition only, and keys by order_id to keep an entity ordered (weight 3)
  • Explains hash(key) mod partitions and one-partition-per-consumer parallelism (weight 2)
  • Identifies the remapping risk when the partition count changes, with a mitigation (weight 3)
  • Checks whether the consumer itself is the bottleneck, and notes hot keys (weight 1)

Follow-ups

  • A consumer processes records with a thread pool for speed. How do you keep per-order ordering?

    Route each record to a worker by hashing its order key, so one thread handles all events for an order, and commit offsets only up to the lowest offset that every worker has finished. Parallelism then comes from different keys, not from reordering one key.

  • How would you design keys for an event where both customer-level and order-level ordering matter?

    Kafka orders only within a partition, so pick the key at the level where ordering really matters. If both matter, key by customer: orders belong to customers, so customer-level ordering implies order-level ordering. The cost is hot partitions for very large customers.

Further reading

Read a query plan and find why a query is slow

Toolsmediummid · senior20 min
#query-plans#performance#partition-pruning

A finance dashboard query joins fact_sales (4 billion rows, partitioned or sorted by sale_date) to dim_customer (20 million rows) and dim_date, filters to the last 30 days, and aggregates revenue by region. It used to take 8 seconds; now it takes 6 minutes. Nobody changed the query.

Walk through how you'd use the query plan (EXPLAIN, or the warehouse's query profile) to find the cause. What would you look for, and what are the usual culprits?

Hint 1

Is the plan you're reading the estimated plan or what actually happened? Which one shows the difference between estimated and actual rows?

Hint 2

The date filter should read a tiny fraction of the fact table. How would the plan show whether it did?

Show solution

Get the real plan, not just the estimate. EXPLAIN shows the optimizer's estimated plan; EXPLAIN ANALYZE (Postgres, DuckDB) or the query profile (Snowflake, BigQuery execution details, an actual execution plan in SQL Server, Redshift's query summary views) shows what actually ran: rows per step, time per step, spills and data movement. Compare it with the plan from when the query was fast, if you have one.

Read it from the most expensive step outwards. Find the operators that took the most time, then check:

  1. Scan size and pruning. Partitions or blocks scanned versus total. If the 30-day filter scans most of the table, pruning broke. Usual causes: a function wrapped around the filter column (CAST(sale_date AS VARCHAR) LIKE ..., DATE_TRUNC(sale_date) = ...), a type mismatch forcing a conversion, or data no longer loaded in date order so min/max ranges overlap.
  2. Estimated vs actual rows. A large gap (estimated 10k, actual 50 million) means stale or missing statistics, and the optimizer picked the wrong join order or algorithm. Refresh statistics (ANALYZE, UPDATE STATISTICS), or check whether a recent load changed the data shape.
  3. Join algorithm and data movement. A broadcast of the big table instead of the small one, a redistribution (shuffle) of 4 billion rows, or a nested loop where a hash join was expected. In MPP warehouses, look for redistribution steps caused by mismatched distribution keys.
  4. Row explosion. A join whose output is much bigger than its inputs suggests a duplicated key in a dimension (for example two current rows per customer after a bad SCD load), which also makes the results wrong.
  5. Spilling. Hash tables or sorts spilling to disk point to memory pressure or an oversized intermediate result.
  6. Not the query at all. Queuing time versus execution time: if it waited 5 minutes in a queue, the problem is concurrency and workload management, not the plan.

Then fix the cause and confirm with the plan: rewrite the filter on the raw column, refresh statistics, deduplicate the dimension, re-cluster or re-sort, or adjust workload management. A good answer checks the plan again after the fix.

What a strong answer covers

  • Distinguishes estimated plan (EXPLAIN) from actual execution (EXPLAIN ANALYZE / query profile) (weight 2)
  • Checks scanned vs total partitions and names what breaks pruning (weight 2)
  • Compares estimated and actual rows and links gaps to statistics and join choices (weight 2)
  • Checks join algorithm, data movement, row explosion and spills; separates queue time from run time (weight 3)

Follow-ups

  • The plan shows estimated rows 12,000 and actual rows 48 million on the dimension join. What happened, and how do you fix it?

    The optimizer's estimate is badly off: usually stale statistics after a large load, or a real data problem such as duplicated keys in the dimension multiplying rows. Check the dimension's key uniqueness first (it would also make results wrong), then refresh statistics and confirm the plan changes.

  • How would you catch plan regressions before users notice?

    Track runtime and bytes or partitions scanned for important queries over time from the warehouse's query history, and alert on large changes. Run key dashboard queries in CI or after deployments against production-sized data, and keep statistics maintenance scheduled.

Further reading

Serverless vs cluster compute for data jobs

Toolsmediummid · senior15 min
#serverless#cost#aws#spark

Your team runs three kinds of AWS workloads:

  • About 200 small daily jobs, each processing 1–5 GB for 5–10 minutes.
  • One large nightly Spark job over 6 TB that runs for 3 hours.
  • Analysts running ad-hoc SQL on the lake a few times a day.

For each, would you use serverless options (Glue, Lambda, Athena, EMR Serverless) or provisioned clusters (EMR on EC2, a provisioned warehouse)? Explain the cost models and the trade-offs.

Hint 1

How are you billed when nothing is running, in each model?

Hint 2

What does a cluster give you that serverless doesn't, and when is that worth paying for?

Show solution

Cost models.

  • Serverless: pay per use: per second of capacity used (Glue DPUs, EMR Serverless), per request and duration (Lambda), or per data scanned (Athena). Nothing to pay when idle, no cluster to operate, but a higher unit price and less control. Some services have startup latency and limits (for example Lambda's maximum run time and memory).
  • Provisioned clusters: pay for instances while they run, whether busy or not. Lower unit cost when highly utilized, especially with spot or reserved capacity, plus full control of versions, instance types and tuning. But you pay for idle time and operate it yourself.

The three workloads.

  1. 200 small daily jobs: serverless. They're short and spread out, so a cluster would sit mostly idle. Glue or EMR Serverless for Spark-style jobs, or even a SQL engine or Lambda for the smallest. Watch per-job minimum billing and startup time, and batch tiny jobs together if overhead dominates.
  2. The 6 TB nightly job: either can work; it depends on utilization and tuning. A transient EMR cluster (created for the run, terminated after) with spot task nodes is often cheapest for a long, predictable, heavy job and lets you tune it. EMR Serverless is simpler to operate at a higher unit cost. Benchmark both on the real job.
  3. Ad-hoc analyst SQL: Athena (pay per TB scanned) when usage is light and data is partitioned and in a columnar format, so scans are small. If usage grows to many users all day, a warehouse with provisioned or capacity pricing becomes cheaper and more predictable.

General rule: serverless for spiky, small or unpredictable work, and when team time is scarce; provisioned for steady, heavy, well-understood workloads where utilization is high. Measure cost per job or per query, and revisit as usage changes.

What a strong answer covers

  • Explains both cost models (pay per use vs pay for running capacity) and idle cost (weight 3)
  • Chooses serverless for the many small jobs and explains why (weight 2)
  • Weighs a transient cluster (with spot) vs serverless for the large job, suggests benchmarking (weight 2)
  • Chooses Athena for light ad-hoc SQL with partitioning/columnar formats, and knows when a warehouse wins (weight 2)

Follow-ups

  • The Athena bill for ad-hoc queries tripled. What do you check first?

    Which queries scan the most data: look for missing partition filters, SELECT * on wide tables, and data stored as uncompressed CSV or JSON. Fix the layout (Parquet, partitions, compaction), add workgroup limits on data scanned per query, and teach the common patterns.

  • What are the risks of running the nightly job on spot instances?

    Spot capacity can be reclaimed, losing executors mid-job. Keep the core nodes on demand (they hold shuffle data and HDFS), use spot for task nodes, diversify instance types, and make the job restartable from checkpoints or by partition so an interruption doesn't mean starting over.

Further reading

Snowflake micro-partitions, clustering and pruning

Toolsmediummid · senior20 min
#snowflake#partition-pruning#performance#cost

A 9 TB Snowflake table events is loaded hourly in arrival order. Dashboards filter it by event_date and are fast. A new product query filters by account_id (about 2 million distinct values) and scans almost the whole table.

Explain micro-partitions and pruning, why the two queries behave so differently, and whether you'd add a clustering key. What would you check first, and what does clustering cost?

Hint 1

What metadata does Snowflake keep per micro-partition?

Hint 2

How is the table naturally ordered?

Show solution

Micro-partitions. Snowflake stores tables in immutable micro-partitions (roughly 50–500 MB of uncompressed data each) and keeps metadata per partition, including each column's min and max. A query with a filter skips every partition whose min/max range can't match. That's pruning.

Why the queries differ. Data is loaded hourly in arrival order, so it's naturally clustered by time: each partition covers a narrow range of event_date and pruning works well. account_id values are scattered across all partitions, so almost every partition's min/max range contains any given account, and nothing is pruned.

What to check first. In the query profile, compare partitions scanned with partitions total. Run SYSTEM$CLUSTERING_INFORMATION('events', '(account_id)') to see overlap and depth for that column.

Options:

  • Clustering key, for example CLUSTER BY (event_date, account_id) or with an expression. Automatic Clustering then reorganizes partitions in the background. That costs credits continuously, especially on a table with constant inserts, and can undo the natural time ordering if you pick the wrong key order. Worth it for very large tables queried often with selective filters that don't match load order.
  • Search Optimization Service suits highly selective point lookups (WHERE account_id = …) on high-cardinality columns better than clustering does, and is billed separately.
  • A separate table or materialized view ordered by account, if only one workload needs it.
  • Make sure the query actually filters on the raw column (wrapping it in a function or casting it can defeat pruning).

Don't cluster small tables, or tables already pruning well. Measure the credits spent against the query time saved.

What a strong answer covers

  • Explains micro-partitions with min/max metadata and pruning (weight 2)
  • Explains natural clustering by load order vs scattered account_id (weight 2)
  • Checks partitions scanned vs total and clustering information before acting (weight 2)
  • Weighs clustering keys (and their ongoing credit cost) vs search optimization for point lookups (weight 3)

Follow-ups

  • Clustering costs are higher than expected. How do you find out which tables are responsible?

    Query the AUTOMATIC_CLUSTERING_HISTORY view (account usage) to see credits by table, and compare that cost with query savings for each table. Then reconsider tables with heavy churn or poor clustering-key choices, or suspend clustering on them.

  • How does this compare to BigQuery clustering or Delta Z-ordering?

    BigQuery clustering sorts data within partitions by up to four columns and re-clusters automatically at no extra charge. Delta Z-ordering is a manual OPTIMIZE job that co-locates data for several columns, and liquid clustering is the newer incremental option. All three aim to skip files or blocks using min and max statistics.

Further reading

Spark partitioning vs bucketing for joins

Toolsmediummid · senior20 min
#spark#partitioning#bucketing

Every night a Spark job joins transactions (2 TB, keyed by account_id) with accounts (200 GB) and aggregates per account. Both tables are written by your team. Someone suggests partitionBy("account_id") on both tables to speed up the join.

Explain the difference between partitioning and bucketing on write, why the suggestion is a bad idea, and what you'd do instead.

Hint 1

How many directories and files does partitioning by a high-cardinality column create?

Hint 2

What would let Spark skip the shuffle of a sort-merge join?

Show solution

Partitioning on write (df.write.partitionBy("col")) creates one directory per distinct value. Queries that filter on that column skip the other directories (partition pruning). It's ideal for low-cardinality filter columns such as event_date.

Why partitionBy("account_id") is bad: with millions of accounts you get millions of directories and tiny files. Listing and opening them dominates the job, metadata (the metastore or table-format manifests) explodes, and the join still has to shuffle. Partitioning helps filtering, not joining.

Bucketing (bucketBy(n, "account_id") with saveAsTable) hashes rows into a fixed number of buckets per partition and records that in the table metadata. When both sides are bucketed (and optionally sorted) on the join key with the same number of buckets, Spark can join bucket i to bucket i directly: no shuffle for the sort-merge join, and aggregations by the key avoid an exchange too. That suits a join that repeats every night on the same key.

Caveats:

  • Bucketing needs a metastore-backed table (saveAsTable) and Spark's bucket semantics. Other engines may ignore it, and table formats handle it differently (Iceberg has a bucket partition transform; Delta favors clustering and Z-ordering instead of Hive-style bucketing).
  • Bucket counts must match. Changing them means rewriting the table.
  • Writes are slower because data must be shuffled into buckets, so the saving only pays off if the table is read and joined often.

Other options to consider first: partition both tables by date and join only the new date's transactions with accounts; broadcast a filtered, projected accounts if it fits; and let AQE optimize the shuffle.

What a strong answer covers

  • Explains partitionBy = directory per value, good for low-cardinality filters (weight 2)
  • Identifies small files/metadata explosion from partitioning by a high-cardinality key (weight 2)
  • Explains bucketing: same key and bucket count on both sides avoids the shuffle (weight 3)
  • States bucketing caveats (metastore, fixed counts, write cost, engine support) and alternatives (weight 2)

Follow-ups

  • How would you choose the number of buckets?

    Aim for bucket files of a healthy size (roughly 100 MB–1 GB) at the expected data size: the table size divided by the target file size, rounded to a number that fits your cluster's parallelism. Both tables in the join need the same count (or a multiple, in some engines), and changing it later means rewriting the table.

  • The data moves to Iceberg. What replaces bucketing there?

    Iceberg's bucket(n, account_id) partition transform, and Storage Partitioned Joins in Spark 3.3+, which can skip the shuffle when both tables share compatible bucket partitioning. Sort orders and compaction help as well.

Further reading

Spark shuffles, data skew and how to fix them

Toolsmediummid · senior25 min
#spark#performance#data-skew

A Spark job joins events (3 TB) to users (40 GB) on user_id, then aggregates by country. In the Spark UI, 199 of 200 tasks in the join stage finish in 2 minutes; one task runs for 70 minutes and spills to disk.

What is happening, why, and what would you try, in order?

Hint 1

What is special about the key that one task is processing?

Hint 2

Which side of the join is small enough to avoid a shuffle?

Show solution

What's happening: the join and the aggregation are wide transformations, so Spark shuffles rows by key across spark.sql.shuffle.partitions partitions (200 by default). One partition got far more rows than the others: data skew. Typical causes are a hot key (a bot user, a default user_id = 0, or many NULL keys) that all hash to the same partition. That single task does most of the work and spills because its data doesn't fit in memory.

Fixes, roughly in order:

  1. Look at the key distribution (groupBy(user_id).count(), ordered descending). Often the hot key is junk: filter NULL or sentinel keys before the join.
  2. Adaptive Query Execution (AQE). spark.sql.adaptive.enabled (on by default in recent Spark) with spark.sql.adaptive.skewJoin.enabled splits skewed partitions into smaller tasks automatically, and coalesces tiny shuffle partitions.
  3. Broadcast the small side if it fits: a broadcast hash join sends users to every executor and removes the shuffle of events entirely. 40 GB is too big to broadcast, but if you only need a few columns, or only active users, the projected or filtered side may fit (spark.sql.autoBroadcastJoinThreshold, or a broadcast() hint).
  4. Salting for a genuine hot key: add a random salt 0..N-1 to the skewed key on the big side, replicate the matching rows on the small side N times, join on (key, salt), then aggregate.
  5. Handle hot keys separately: join the few hot keys with a broadcast and the rest normally, then union.
  6. Tune spark.sql.shuffle.partitions to the data size (AQE can do it). It helps overall spread, but not a single hot key.

Also check: that skew isn't coming from the aggregation instead (use a two-stage aggregation), and that executors have enough memory to avoid spills on normal partitions.

What a strong answer covers

  • Explains shuffle for wide transformations and identifies one oversized partition as skew (weight 2)
  • Checks the key distribution and filters junk/null hot keys first (weight 2)
  • Uses AQE skew join handling and/or broadcast join, with conditions (weight 3)
  • Explains salting (or isolating hot keys) for genuine skew (weight 2)

Follow-ups

  • After salting, the job is faster but produces more rows than before. What did you forget?

    You replicated the small side once per salt value but joined on the original key only, not on (key, salt), so each big-side row matched all N copies. Join on both the key and the salt so every row matches exactly one copy, then aggregate by the original key.

  • How would you spot skew automatically in production jobs?

    Use Spark task metrics: compare the max to the median task duration and shuffle-read bytes per stage. Alert when the ratio is high (for example max > 5× median), using the Spark event logs or a listener. AQE skew-join logs and spill metrics are also signals.

Further reading

Managing data infrastructure with Terraform

Toolsmediummid · senior20 min
#infrastructure-as-code#aws#data-security

Your data team's cloud resources (buckets, Glue jobs and catalog databases, IAM roles, a Redshift cluster, Kafka topics) were created by hand in the console over two years. Dev and prod differ in ways nobody can list, and last month someone deleted a prod bucket policy by mistake.

How would you bring this under Terraform? Cover how Terraform works (state, plan, apply), how you'd structure it for several environments, how changes get reviewed and applied, and what you would not manage with it.

Hint 1

Terraform has to know which real resource each block in your code refers to. Where does it keep that, and who else can read it?

Hint 2

The resources already exist. How do you adopt them without recreating them?

Show solution

How Terraform works. You declare resources in configuration. Terraform keeps a state file that maps each resource block to the real object it manages. terraform plan compares configuration, state and reality and shows what would change; terraform apply makes those changes. Because the plan is explicit, reviewers see "1 to change, 0 to destroy" before anything happens.

State is critical, so treat it carefully:

  • Store it in a remote backend (for example an S3 bucket with locking, or Terraform Cloud), never on a laptop, so the team shares one state and two applies can't run at once.
  • State can contain sensitive values (initial passwords, tokens) in plain text, so restrict and encrypt the backend, and keep real secrets in a secrets manager instead.
  • Split state by environment and by area (networking, data platform, warehouse), so one change can't touch everything and plans stay fast.

Adopting existing resources: write configuration that matches each resource, then import it into state (an import block or terraform import), and run plan until it shows no changes. Do it in small batches, highest-risk resources first (IAM and bucket policies). Then lock down console write access in prod so drift doesn't return.

Structure: reusable modules (a "pipeline" module creating its bucket prefix, Glue job, role and alarms; a "dataset" module for a catalog database and permissions), and one root configuration per environment that calls them with different variables. Dev and prod then differ only where the variables say so.

Workflow: every change is a pull request. CI runs format and validation checks, then plan, and posts the plan for review. apply runs from CI after approval, with prod applies gated. Schedule a regular plan to detect drift.

What not to manage with Terraform:

  • Data itself (table contents, files) or schema migrations that change data; use the pipeline and migration tools for those.
  • Short-lived runtime resources that jobs create on their own.

Be careful with resources whose deletion loses data: use prevent_destroy on prod buckets and databases, and read any plan that says "destroy".

What a strong answer covers

  • Explains state, plan and apply, and why state maps configuration to real resources (weight 2)
  • Uses a remote, locked, access-controlled backend and treats state as sensitive; splits state (weight 2)
  • Imports existing resources until plan shows no changes; prevents console drift (weight 2)
  • Uses modules plus per-environment configuration, a PR-based plan/apply workflow, and protects data-bearing resources (weight 3)

Follow-ups

  • A plan shows Terraform will destroy and recreate the prod Redshift cluster because of a renamed parameter. What do you do?

    Don't apply. Find out why it forces replacement (a changed immutable attribute or a renamed resource address). If it's a rename in code, use a moved block (or state mv) so Terraform knows it's the same resource. If the attribute really requires replacement, plan a migration with a snapshot and downtime window instead. Adding prevent_destroy to such resources makes this fail safely.

  • How do you handle a secret, such as a database password, that a Terraform-created resource needs?

    Don't put it in variables files or code. Generate or store it in a secrets manager and reference it, or let the service manage the password itself, and restrict who can read the state, since resource attributes may still record it.

Further reading