CareerGuide 36 of 37
Career guide · Guide 36 of 37
50 Scenario-Based Data Engineering Interview Questions and Answers
50 scenario-based data engineering interview questions with sample answers: failed pipelines, late data, duplicates, backfills, migrations and design.
On this page
These 50 scenario-based questions cover incidents, late-arriving data, duplicates, backfills, cost spikes, migrations and system design scenarios with concrete numbers. They are grouped from beginner (freshers) to advanced (experienced). Each question has one clear answer in plain words, with an example where it helps and the mistakes interviewers watch for.
Question list
Show all 50 questions
- Ingest from a REST API with strict rate limits
- Daily vendor files over SFTP arrive in inconsistent formats
- Source and target row counts don’t match
- A business user says a dashboard number is wrong
- The driver crashes with OOM after a collect()
- Reprocess a single corrupted partition
- Should this request be batch or streaming?
- Daily reports are off because of time-zone handling
- A rerun double-counted revenue
- PII found in the raw zone and application logs
- Object storage costs grow 20% a month
- The business wants hourly instead of daily refresh
- Set up testing and CI for a brand-new pipeline
- Upstream API was down for two days; how do you recover?
- The nightly pipeline failed at 3 AM; executive dashboards refresh at 7 AM
- Late-arriving events are making daily aggregates wrong
- Duplicates discovered in a production fact table
- A Snowflake dashboard query takes 3 minutes; target is 10 seconds
- Upstream added and renamed columns without notice (schema drift)
- Snowflake cost doubled overnight
- Databricks bill spiked 60% this month
- Recurring SLA breaches on a critical pipeline
- The data lake has millions of tiny files
- Kafka consumer lag keeps growing
- Out-of-order events in a streaming aggregation
- A join on customer_id is skewed by one huge customer (See also Q264)
- An incremental load silently missed records
- Airflow tasks stuck in queued state
- Auditors need lineage and a data catalog
- Migrate orchestration from Airflow to a managed service
- A hot partition in a Kafka topic
- Source sends full daily dumps; detect only the changes
- Share data with an external partner securely
- A MERGE into a large table runs for hours
- Design the dimensional model for e-commerce orders
- A pipeline gets slower every month
- Make KPIs consistent across three BI tools
- Backfill two years of history without breaking production
- A Spark job went from 40 minutes to 4 hours
- Design a real-time clickstream pipeline (50k events/sec)
- CDC from a PostgreSQL OLTP database into the warehouse
- Migrate an on-prem Oracle/Teradata warehouse to the cloud
- SCD Type 2 on a 500-million-row customer dimension
- Fulfil a GDPR deletion request across lake, warehouse and backups (See also Q85)
- Design a data platform from scratch for a growing startup
- Multiple jobs writing to the same table cause conflicts
- Build a data quality framework for 200 tables
- Merge customer data after an acquisition (entity resolution)
- Build point-in-time-correct training data for an ML model
- Add multi-region disaster recovery to the platform
Beginner scenario-based questions (freshers)
1. Ingest from a REST API with strict rate limits
Scenario:
You need daily data from a SaaS API: 2 M records, a maximum of 100 records per page, a rate limit of 10 requests per second, and a daily quota of 50,000 requests. It supports updated_since filtering and cursor pagination. The full history is 30 M records, and data must be loaded by 07:00.
Answer:
“First the math: 2 M changed records at 100 per page is 20,000 requests, about 35 minutes at a safe 9 requests per second, and 40% of the daily quota. Fine. The 30 M-record history needs 300,000 requests, so I’d either ask the vendor for a bulk export or backfill over 6–7 days within the quota, alongside the daily incremental. The extractor is a Python job: updated_since with a 15-minute overlap, cursor pagination with a checkpoint after each page, a token-bucket limiter, and retries only on 429 and 5xx, honouring Retry-After. Pages land as raw JSON in S3 by date, then a COPY and MERGE on id into the warehouse, which is idempotent, so overlaps and reruns don’t duplicate. Starting at 05:00 leaves a margin before 07:00, and I’d alert if quota use passes 80% or the run isn’t done by 06:15.”
Approach:
- Do the math:
- Daily changes: if 2 M records are updated per day, that’s 20,000 pages, which takes 2,000 seconds (about 33 minutes) at 10 requests per second. It fits the 50,000 quota.
- Initial history: 30 M records is 300,000 requests, so about 6 days at the quota. Plan a phased backfill, or ask the vendor for a bulk export.
- Incremental:
updated_since = last_watermark - overlap (15 min). Store the watermark after a successful load. - Pagination: follow the cursors until done, and guard against loops (see API ingestion with pagination (offset, cursor, next-link)).
- Rate limiting: a token bucket at 9 requests per second for a safety margin. Honour
Retry-Afteron 429. Exponential backoff with jitter for 5xx (see Retries with exponential backoff and rate limiting). - Checkpointing: persist the cursor per page, so a crash resumes mid-run.
- Land the raw pages as JSON in object storage partitioned by run date, then load to the warehouse and MERGE on ID.
- Quota monitoring: track requests used, and alert near 80%.
Learn more: Working with APIs in Python: Pagination, Retries and Rate Limits
2. Daily vendor files over SFTP arrive in inconsistent formats
Scenario:
Twelve vendors drop daily CSV and Excel files on an SFTP server. Problems include changing column orders and names, different delimiters, mixed date formats (DD/MM vs MM/DD), occasional missing files, and duplicate re-uploads. Finance relies on the data by 09:00.
Answer:
“I’d separate transport from parsing. A job polls SFTP every 15 minutes and copies new files to S3 under raw/vendor=X/dt=YYYY-MM-DD/ with a SHA-256 checksum, so byte-identical re-uploads are skipped. Each vendor has a YAML config: filename pattern, delimiter, encoding, a header-name mapping to our canonical columns, the date format, and the expected arrival time. The parser maps columns by header name, so reordering doesn’t matter, and an unknown or missing required column fails that file with a clear message. Rows failing validation go to quarantine, and the vendor gets an automatic report. Loads replace the vendor-day partition, so a corrected re-upload simply overwrites. If a file hasn’t arrived by 08:00, we alert and finance sees which vendors are missing. Onboarding a new vendor or format change becomes a config PR, not new code.”
Approach:
- Land the raw files: copy everything from SFTP to object storage under
vendor/date/immutably, recording a checksum (for duplicate detection) and the arrival time. - Configure each vendor: expected filename pattern, file type, delimiter, encoding, a header mapping (vendor column to canonical column), the date format, required columns, and the expected arrival window.
- Parse and validate: apply the config, map headers by name (not by position), parse dates with the vendor-specific format, validate rows (see Coding: validate records and split good from bad), and quarantine bad rows.
- Duplicates: skip files with identical checksums. For re-uploads with changes, replace that vendor-day partition (idempotent).
- Missing or late files: alert if not received by the window end, and publish with a “vendor X missing” flag.
- Load into canonical staging tables, then transform.
- Vendor management: share a file spec. Send automated rejection reports to vendors.
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Hard-coded parser per vendor | Quick initially | Code change for every format tweak |
| Config-driven parser | Scales to many vendors | Upfront framework effort |
| Managed file ingestion (Auto Loader, Snowpipe) | Incremental, scalable | Still need per-vendor mapping |
| Vendors push to API instead | Structured | Requires vendor capability |
3. Source and target row counts don’t match
Scenario:
A nightly load copies orders from a MySQL source into the warehouse. Monitoring shows the source has 1,204,331 rows for yesterday, and the target has 1,198,870, a difference of 5,461 (0.45%). The business asks whether reports are wrong.
Answer:
“I’d first check we’re comparing like with like. The source count uses MySQL server time (UTC), and the target counts by order_date in the business timezone. Recounting the target in UTC narrows the gap to 3,102. Then I’d bucket by hour, and the gap is concentrated at 23:50–00:10 UTC. Our extract runs at 00:05 with updated_at < run_start, and long transactions committed after that with earlier timestamps were skipped and never picked up, a classic watermark gap. An anti-join of IDs confirms the missing rows all have updated_at within the last 15 minutes before the extract. The fix is a lookback overlap on the watermark (re-read the last 30 minutes) with MERGE on order_id, then a backfill of the last 7 days. I’d add a daily reconciliation check of counts and sums of amount per day in UTC, alerting above 0.01%. To the business: yes, yesterday’s revenue was understated by about 0.25%, corrected by noon.”
Approach:
- Make sure both counts measure the same thing: the same definition of “yesterday” (timezone), the same filters (soft-deleted rows, test orders), and the counts taken at a comparable point in time.
- Narrow it down: compare counts by hour or by ID ranges to find where the gap sits.
- Find the missing keys: export the source IDs for the gap window and anti-join them against the target (or compare hash buckets).
- Typical causes:
- Timezone boundary (orders between 00:00 and 05:30 local).
- Late commits after the extract watermark (see An incremental load silently missed records).
- Rows rejected by validation or quarantine.
- Filters in the transformation.
- Dedupe that removed real rows.
- A failed batch.
- Hard deletes in the source.
- Fix and backfill the root cause, and reprocess the window.
- Prevent: automated reconciliation (counts and sums per day) with tolerances and alerts.
Trade-offs:
| Check | Catches | Cost |
|---|---|---|
| Row counts | Missing/extra rows | Cheap |
| Sums of key measures | Value corruption | Cheap |
| Key-level anti-joins | Exact missing records | Moderate |
| Row hash comparison | Any column difference | Higher |
4. A business user says a dashboard number is wrong
Scenario:
The VP of Sales messages you: “The dashboard says 1,240 new customers last month, but my team counted about 1,400 in Salesforce. Which is right? I’m presenting tomorrow.”
Answer:
“I’d reply quickly that I’m on it and will have an answer this afternoon, and ask how her team counted: from Salesforce opportunities marked closed-won in March? Then I’d trace our metric. The dashboard uses new_customers from the semantic layer, defined as accounts whose first paid invoice is in the month. Reproducing her number from Salesforce data gives 1,398 closed-won deals. The difference: 118 deals closed in late March but invoiced in April, and 40 duplicate account records for the same customer. Neither is a pipeline bug, just two definitions. I’d send her a short note with both numbers, what each means, and the reconciliation table, and suggest that for a sales presentation ‘closed-won deals’ might be the better metric. We could add it to the dashboard, clearly labelled. I’d also put both definitions into our metric glossary and ask the CRM admin to merge the duplicate accounts.”
Approach:
- Acknowledge and clarify: what exactly did they count (accounts, contacts, opportunities won)? Which date field (created vs closed-won)? Which filters (region, test accounts)?
- Trace the metric: dashboard → semantic model or SQL → mart → staging → source. Find the definition: “new customers = accounts with their first paid invoice in the month”.
- Reproduce both numbers: query the mart for 1,240, and query the Salesforce data for about 1,400 using their definition.
- Explain the gap: for example, Salesforce counts closed-won opportunities (including deals not yet invoiced, 120 of them) plus duplicate accounts (40). Or there’s a real bug, such as a missing region or broken join.
- Resolve: if it’s a definition difference, explain it clearly and offer both metrics, properly labelled. If it’s a bug, fix it, backfill and tell people.
- Prevent: a documented metric definition, a semantic layer, and a glossary.
Trade-offs:
| Response | Pros | Cons |
|---|---|---|
| “Our number is right” | Fast | Damages trust; may be wrong |
| Full reconciliation with explanation | Builds trust, finds real bugs | Takes time |
| Change metric to match user | Pleases user | Inconsistent definitions elsewhere |
| Centralised metric definitions | Prevents recurrence | Requires governance effort |
5. The driver crashes with OOM after a collect()
Scenario:
A PySpark job reads 150 M customer records, filters them, calls .collect() to loop in Python and build an export CSV, and crashes with java.lang.OutOfMemoryError (or “Total size of serialized results is bigger than spark.driver.maxResultSize”). Someone proposes raising driver memory to 64 GB.
Answer:
“collect() moves all 150 M rows into the driver JVM, then into Python objects, so even 64 GB may not be enough, and we’d be processing on one machine anyway. I’d ask what the loop does. Here it formats rows and writes a CSV, which Spark can do directly: df.select(...).write.option('header', True).csv('s3://exports/customers/2026-03-01/'), executed in parallel by the executors. If the consumer needs a single file, I’d check the size. For a few GB, coalesce(1) after the heavy work, or merging part files afterwards. For huge outputs I’d agree on multiple files with a manifest. If the loop calls an external API per row, I’d use foreachPartition, so each executor opens one client and batches requests. Raising driver memory treats the symptom. The fix is keeping data distributed.”
Approach:
- Explain the cause:
collect()pulls every row into the driver’s memory, as Python objects, which is even larger. The driver is a single machine. - Ask why it’s collected: usually to write a file, call an API, or compute something that Spark can do itself.
- Replace it:
- Writing files:
df.write.csv(...)from the executors, in parallel, withcoalesce(n)if they want fewer files, or a single file for small results. - API calls:
foreachPartitionwith batched calls and rate limits. - Computations: use Spark aggregations, and only collect small results.
- Inspection:
limit(n)/take(n)/show. - Iterating locally:
toLocalIterator()streams partitions to the driver one at a time (it’s still slow, but bounded memory).
- Writing files:
- Explain why raising memory is the wrong default: it’s expensive, the data will grow again, and it’s still single-threaded processing.
Trade-offs:
| Option | Use | Caveat |
|---|---|---|
df.write |
Files/tables | Multiple files by default |
foreachPartition |
External sinks | Need idempotency, rate limits |
toLocalIterator |
Must process on driver | Slow; sequential |
toPandas() on aggregated result |
Small results | Still bounded by driver memory |
Learn more: Spark Memory, Executor Sizing and Cluster Tuning
6. Reprocess a single corrupted partition
Scenario:
The sales fact table, partitioned by sale_date, has corrupted data for 2026-03-14: a bug doubled discount values. Other days are fine. Dashboards for that day show wrong margins. The bug is fixed in code, and raw data for that day is still available.
Answer:
“I’d first confirm the blast radius. The bug shipped on the 14th and was fixed on the 15th, so only that day’s partition is affected, and lineage shows it feeds the daily margin mart and the March monthly rollup. Because the job is parameterised by date and writes with replaceWhere sale_date = '2026-03-14', I can rerun just that date with the fixed code, and the replacement is atomic, so readers see either the old or new partition. Then I’d rebuild the downstream daily margin for the 14th and the March rollup. I’d verify discount totals against the POS source for that day, check that margins look normal, and run the tests. Then I’d tell finance the 14th’s margins were corrected and by how much. Finally, I’d add a test that discount never exceeds the gross amount, which would have caught this before the dashboard.”
Approach:
- Confirm the scope: only 2026-03-14? Check neighbouring days and the deployment window of the bug.
- Find the downstream dependencies: aggregates, marts and extracts built from that partition (lineage).
- Reprocess atomically: rerun the job for
sale_date = 2026-03-14with the fixed code, replacing the partition (replaceWhere,INSERT OVERWRITE PARTITION, delete+insert in a transaction). - Rebuild the downstream partitions and aggregates for that date (weekly and monthly rollups that include it).
- Verify: discount totals against the source, margin sanity checks, and tests.
- Communicate: the corrected numbers and any reports that used the bad data.
- Prevent: a test or range check on discounts, for example
discount <= gross_amount.
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Partition replace | Precise, fast | Requires partitioned, parameterised jobs |
| Full table rebuild | Simple | Expensive, slow |
| In-place UPDATE fix | Quick for simple bugs | Diverges from code logic; harder to audit |
| Time travel restore | Instant rollback | Only if a good prior version exists; doesn’t apply fix |
Learn more: Idempotency in Data Pipelines
7. Should this request be batch or streaming?
Scenario:
The marketing team asks for a “real-time” campaign performance dashboard. Data comes from ad platform APIs (which update hourly), web events (streaming), and CRM conversions (nightly export). Today the dashboard refreshes daily.
Answer:
“I’d ask marketing what they’d do differently with real-time data. Usually the answer is ‘pause underperforming campaigns during the day’, which needs hourly or 15-minute freshness, not seconds. Then I’d point out the source limits: ad platforms update spend hourly and CRM conversions arrive nightly, so the dashboard can’t be fresher than that, whatever we build. My proposal is an hourly micro-batch for ad spend and impressions, web engagement metrics every 15 minutes from the event stream we already have, and conversions daily, with each tile showing its ‘as of’ time. That’s achievable with scheduled incremental jobs or a 15-minute triggered pipeline, at a fraction of the cost and on-call burden of a full streaming architecture. If they later need conversion attribution within minutes, we’d revisit with the CRM team about streaming conversions.”
Approach:
- Ask what decision the data drives and how quickly: pausing a failing campaign within an hour? Daily budget allocation?
- Check the source freshness limits: ad APIs are hourly and CRM is nightly, so true real-time is impossible for conversion metrics.
- Define the freshness SLA per metric: spend and impressions hourly, web engagement every 5–15 minutes if needed, conversions daily.
- Pick the simplest architecture that meets it:
- Hourly micro-batch for ad spend.
- Web events through streaming ingestion with 5–15 minute aggregation (or a continuous pipeline).
- Conversions daily, with clearly labelled latency.
- Estimate the cost: streaming infrastructure and on-call vs scheduled jobs.
- Communicate: the dashboard shows a “data as of” time per metric.
Trade-offs:
| Option | Latency | Cost/complexity | Fit |
|---|---|---|---|
| Daily batch | 24h | Lowest | Current state; too slow |
| Hourly/15-min micro-batch | 15–60 min | Low | Matches sources and decisions |
| Full streaming | Seconds | High (infra, on-call) | Not justified by sources |
| Hybrid (stream web, batch others) | Mixed | Medium | Good if web metrics matter most |
Learn more: Batch vs Streaming Data Pipelines
8. Daily reports are off because of time-zone handling
Scenario:
A retailer operates in India (IST, UTC+5:30) and the US (several time zones). Daily sales reports group by DATE(order_ts), where order_ts is stored in UTC. Store managers in India say their daily totals don’t match the till, and US West Coast managers say late-evening sales show up on the next day.
Answer:
“The data is stored correctly in UTC, but DATE(order_ts) gives the UTC date, while a store manager in Mumbai thinks in IST, five and a half hours ahead. Sales from 00:00 to 05:30 IST land on the previous day, and a Los Angeles sale at 9 PM PST is already the next day in UTC. I’d add an IANA timezone to dim_store and compute a local_business_date column in the fact table with CONVERT_TIMEZONE('UTC', store_tz, order_ts)::date. Using IANA zones rather than fixed offsets handles US daylight saving correctly. Store-level reports group by local_business_date. For company-wide totals, finance picks a convention, say headquarters time, and we label it on the dashboard. I’d backfill the column for the last two years, add tests with orders at 23:59 and 00:01 local and on DST change days, and tell store managers when their numbers will match the till.”
Approach:
- Confirm: timestamps are stored in UTC (good). The reports take the UTC date, which is wrong for local business days.
- Define the business day: the store-local calendar date, possibly with a trading-day cut-off (for example a business day running 04:00 to 04:00 for late-night stores).
- Add the store timezone (IANA zone, such as
Asia/KolkataorAmerica/Los_Angeles) todim_store. - Compute
local_business_datein the fact table:CONVERT_TIMEZONE('UTC', store_tz, order_ts)::date, which handles DST automatically. - Recompute the history for the affected period, and update reports to group by
local_business_date. - Handle global reports: decide whether company-wide daily totals use UTC days or headquarters’ timezone, and document it.
- Test: cases around midnight and DST transitions (see datetime and time zones with zoneinfo).
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Store local timestamps only | Easy local reporting | Hard global comparisons; DST ambiguity |
| UTC + computed local date (recommended) | Correct both ways | Need store tz dimension |
| Fixed offsets (+05:30) | Simple | Wrong for DST regions |
| Convert in BI tool | No pipeline change | Inconsistent across tools |
Learn more: Time-Series SQL: Date Buckets, Calendars, YoY, MoM and Rolling Metrics
9. A rerun double-counted revenue
Scenario:
A daily job failed halfway through loading fct_payments. The on-call engineer reran it, and revenue for that day doubled on dashboards. The job does INSERT INTO fct_payments SELECT ... FROM staging WHERE payment_date = :run_date, with no transaction around the steps.
Answer:
“The job appends rows for the date, so any rerun after a partial or complete insert duplicates them. That’s why revenue doubled. I’d fix the data first: delete all fct_payments rows for that date and reload from staging once inside a transaction, then check that the daily total matches the payment provider’s settlement report. Then I’d make the load idempotent. Either wrap it as BEGIN; DELETE FROM fct_payments WHERE payment_date = :d; INSERT ...; COMMIT;, or use a MERGE on payment_id, so running it once or five times gives the same result. I’d add a uniqueness test on payment_id that fails the pipeline before dashboards refresh, plus a daily reconciliation check. The rerun then becomes the standard recovery action in the runbook, with no manual cleanup.”
Approach:
- Fix the data first: delete the run date’s rows and reload them once, or dedupe by
payment_idkeeping one copy. Verify against the source. - Explain the cause: the first attempt inserted part or all of the rows before failing (or failed after the insert), and the rerun inserted them again.
- Redesign for idempotency:
- Delete+insert in one transaction for the run date:
BEGIN; DELETE ... WHERE payment_date = :d; INSERT ...; COMMIT;. - Or MERGE on
payment_id. - Or a partition overwrite (
INSERT OVERWRITE,replaceWhere).
- Delete+insert in one transaction for the run date:
- Add tests: a uniqueness test on
payment_id, and a reconciliation of daily totals with the source. - Runbook: reruns are safe by design, and on-call doesn’t need special steps.
Trade-offs:
| Pattern | Pros | Cons |
|---|---|---|
| Delete+insert by partition | Simple, deterministic | Must cover full partition scope |
| MERGE on key | Handles late updates | Needs reliable unique key |
| Partition overwrite | Atomic in table formats | Partition-aligned loads only |
| Dedupe downstream | Quick patch | Hides root cause, costs on every read |
Learn more: Idempotency in Data Pipelines
10. PII found in the raw zone and application logs
Scenario:
A security scan finds full credit card numbers and customer emails in (a) raw JSON files in the data lake (2 years, readable by 120 engineers) and (b) application and pipeline logs shipped to a log platform with 90-day retention. Compliance asks for remediation within 2 weeks.
Answer:
“I’d treat it as a security incident. Within the hour, lock down the affected lake prefixes and log indices to the incident team, and inform security and compliance, because card data has regulatory implications. Then scope it with a pattern scan: 16-digit sequences that pass Luhn, and email regexes, across the lake, tables, derived datasets and log indices. For the lake, a remediation job rewrites the affected JSON files, replacing PANs with tokens or masked values, deletes the old object versions, and vacuums any table versions. For logs, we purge the affected indices or use the platform’s delete API. The real fix is upstream: the checkout service should send the payment provider’s token, never the card number, and we’d add a logging filter that redacts PAN and email patterns before logs leave the service. Going forward, I’d run weekly automated classification scans, apply masking policies by tag, and add a CI check that blocks PAN-like test data.”
Approach:
- Contain immediately: restrict access to the affected lake prefixes and log indices to a small incident group. Notify security and compliance. Card data may trigger PCI DSS obligations.
- Scope: use classification scans (pattern detection for PANs with a Luhn check, and emails) to find every affected location: files, tables, derived datasets, logs, backups.
- Remediate the lake: rewrite the affected files with the card numbers removed or tokenised (keep only the last 4 digits if needed). Delete the originals, including object versions, then purge table versions (VACUUM or time travel limits).
- Remediate the logs: delete or redact the affected log entries if the platform allows it. Otherwise reduce retention or purge the indices.
- Fix the sources:
- The application should never send full PANs. Tokenise with the payment provider.
- Log redaction filters in the logging libraries.
- Schema rules rejecting PAN-like values.
- Ongoing: automated classification scans, tag-based masking policies, least-privilege access, and PII-free logging standards.
Learn more: Protecting PII in Data Pipelines: Masking, Hashing, Tokenisation and Encryption
11. Object storage costs grow 20% a month
Scenario:
The data lake bucket grew from 400 TB to 830 TB in four months, and the S3 bill grows about 20% a month. Nobody knows what’s taking the space. The lake holds raw landing files, Delta tables, Spark checkpoints, temporary job outputs, and old exports.
Answer:
“I’d pull an S3 Inventory report and group it by top-level prefix and object age. That usually explains it in an hour. Here it shows 280 TB of non-current versions (versioning was on with no expiration rule), 150 TB of Delta tables never vacuumed after daily MERGEs, 60 TB of tmp/ outputs from failed jobs, and 90 TB of 3-year-old raw JSON nobody reads. Fixes: a lifecycle rule expiring non-current versions after 14 days, and aborting incomplete multipart uploads after 3 days. Weekly VACUUM, or predictive optimisation, on Delta tables with 7-day retention. A 7-day expiry on tmp/. Transitioning raw data older than 90 days to Glacier Instant Retrieval, with expiry after the agreed retention (say 2 years, confirmed with compliance). That should cut storage by about half, and growth becomes predictable. I’d also require owner tags per prefix and send a monthly storage report per team.”
Approach:
- Measure:
- S3 Storage Lens or Inventory reports grouped by prefix, storage class and age.
- Count non-current object versions (versioning can silently double storage).
- Typical culprits:
- Delta or Iceberg tables never vacuumed, or with snapshots never expired.
- Versioned buckets without non-current version expiration.
- Temp and scratch outputs never cleaned up.
- Duplicate raw copies.
- Uncompressed CSV or JSON in the raw zone.
- Old checkpoints.
- Incomplete multipart uploads.
- Actions:
- VACUUM and expire snapshots on the table formats.
- Lifecycle rules: transition raw data to Infrequent Access or Glacier after 30–90 days, expire temp prefixes after 7 days, expire non-current versions after N days, abort incomplete multipart uploads.
- Compress or convert raw data to Parquet when it’s reprocessable.
- Delete unused datasets after confirming with their owners.
- Govern: tag buckets and prefixes by owner, set retention policies per data class, and report monthly.
Learn more: Cloud Data Cost Optimisation and FinOps for Data Engineers
12. The business wants hourly instead of daily refresh
Scenario:
The sales operations team wants their pipeline dashboard refreshed hourly instead of daily. The current daily pipeline takes 90 minutes, mostly full rebuilds of 120 dbt models, on a Medium Snowflake warehouse. Sources are Salesforce (synced by Fivetran every 6 hours) and an internal Postgres database.
Answer:
“First I’d check feasibility: Salesforce only syncs every 6 hours, so we’d raise the Fivetran sync to hourly for the 5 objects the dashboard uses, which is a modest cost increase. Then I’d scope it. The dashboard exposure depends on 22 of the 120 models, so only those need hourly runs. Three of them are large full rebuilds, and I’d make them incremental with a 2-hour lookback and merge on IDs. An hourly job from 08:00 to 20:00 runs dbt build --select +exposure:sales_pipeline_dashboard on a Small warehouse, about 4–6 minutes per run, while the nightly full build stays as is. Cost is roughly 12 short runs a day, a few extra credits per day plus the connector cost, which I’d present to the business with the SLA: ‘dashboard data no older than about 75 minutes during business hours’. Then I’d add freshness monitoring on the dashboard sources.”
Approach:
- Clarify: which metrics need hourly refresh (probably a few dashboard tiles, not all 120 models)? Working hours only?
- Upstream freshness: Fivetran syncs Salesforce every 6 hours, so increase the sync frequency (cost implications) or the “hourly” request is meaningless for Salesforce data.
- Scope: select the models that feed the dashboard (
+exposure:sales_pipeline_dashboard), perhaps 25 models. - Make them incremental where large, so each run processes an hour of changes.
- Schedule: hourly during business hours for that selection, with the full nightly build unchanged.
- Estimate the cost: hourly runs at about 5 minutes on a Small warehouse vs the current daily cost, plus the Fivetran sync cost increase.
- SLA: for example, data at most 75 minutes old during 08:00–20:00.
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Run whole project hourly | Simple | Expensive, slow |
| Subset + incremental | Targeted, cheap | More scheduling configs |
| Dynamic tables with target lag | Declarative freshness | Platform-specific; cost per refresh |
| Keep daily, add intraday “flash” metrics | Minimal change | Two definitions risk |
13. Set up testing and CI for a brand-new pipeline
Scenario:
You’re building a new pipeline: a Python extractor from a partner API, landing in S3, loaded into Snowflake, and transformed with dbt (about 30 models). The team has no existing CI. You need to set up testing and deployment practices before the first production release in 6 weeks.
Answer:
“In 6 weeks I’d set up a minimal but solid foundation. In week one, a repo with a GitHub Actions workflow: ruff and mypy on the Python extractor, pytest unit tests with responses mocks covering pagination, 429 retries and malformed payloads, and Pydantic models acting as the contract for API responses. For dbt: SQLFluff, PK and relationship tests on every model, unit tests on the two models with tricky business logic, and source freshness on the landing tables. CI runs on every PR: lint, then unit tests, then dbt build --select state:modified+ --defer into a per-PR schema in Snowflake, with results posted on the PR. On merge, CD builds the extractor container and the orchestrator picks up the new dbt code for the next prod run. Prod runs use a service account with key-pair auth, and developers can’t write to prod. After launch, freshness and test failures alert our channel. Later I’d add data diffing against prod for refactors.”
Approach:
- Repository and branching: one repo with
extractor/,dbt/and infra, using trunk-based development with PRs. - Python extractor:
- Linting and formatting (ruff), type checks (mypy).
- Unit tests with pytest for parsing, pagination and retry logic, using mocked HTTP (see pytest fixtures and parametrize, Mocking external services in tests).
- A contract test validating sample API responses against a schema (Pydantic models).
- dbt:
- SQL linting (SQLFluff).
- Unit tests for complex logic, and data tests (PK unique and not_null, relationships, accepted values).
- Source freshness.
- Slim CI with deferral to prod (see Slim CI with state:modified and
--defer).
- Environments: dev (personal schemas), CI (per-PR schema), and prod (service accounts only).
- CI pipeline (on PR): lint, unit tests,
dbt build --select state:modified+in the CI schema, and test results posted to the PR. - CD (on merge): build and push the extractor image, then
dbt buildin prod through the orchestrator. Infra changes go through Terraform plan and apply with approval. - Post-deploy monitoring: freshness, row counts, test failures, and alerts to the team channel.
Learn more: Testing Data Pipelines and CI/CD for Data
14. Upstream API was down for two days; how do you recover?
Scenario:
A partner’s API was unavailable from Friday 18:00 to Sunday 20:00. Your hourly ingestion job failed 50 times, and the dashboards show a gap for the weekend. The API is back, with normal rate limits (10 requests per second). The weekend volume is roughly 3× a normal day because of a promotion.
Answer:
“Because our extractor uses a watermark (updated_since = the last successful run minus overlap), the next successful run would try to fetch the whole weekend at once. That’s probably too big for one run, so I’d pause the hourly schedule and run a dedicated backfill. I’d split Friday 17:00 to now into hourly windows, fetch each with pagination and our 9-requests-per-second limiter, land the raw pages, and MERGE on IDs, with a checkpoint per window. Weekend volume is about 6 normal days’ worth, so at 9 requests per second that’s roughly 3 hours, within the daily quota. Then I’d rebuild Friday-to-Sunday partitions downstream, re-enable the hourly job, and confirm counts against the partner’s own reports. Stakeholders get a note in the morning: weekend data restored by 11:00, numbers final after reconciliation. Afterwards, I’d make the job auto-chunk large catch-up windows, and group repeated failures into a single incident alert.”
Approach:
- Confirm the API is healthy and that it can serve historical windows (
updated_sinceback to Friday). - Stop the alert storm: pause the hourly job, or make it skip while a backfill runs, so the two don’t compete.
- Plan the backfill:
- Window: Friday 17:00 (with overlap) to now.
- Estimate requests: about 3× a normal day for 2 days, which is roughly 6 days of normal volume. Check the time this takes at 10 requests per second, and the daily quota.
- Run it in chunks (by hour) with checkpoints. Use idempotent loads (MERGE on IDs), so overlap is harmless.
- Prioritise: load the data critical dashboards need first, if the API supports filtering, for example orders before marketing events.
- Downstream: rebuild the affected partitions and aggregates for the weekend dates.
- Communicate: the gap, the expected time to full recovery, and which numbers are provisional.
- Improve:
- Automatic catch-up logic (the watermark-based job naturally catches up after outages, if it’s built incrementally).
- Alert deduplication (one incident, not 50 alerts).
- An upstream status integration.
Learn more: Working with APIs in Python: Pagination, Retries and Rate Limits
Intermediate scenario-based questions
15. The nightly pipeline failed at 3 AM; executive dashboards refresh at 7 AM
Scenario:
You’re on call. At 03:05 you’re paged: the nightly finance_daily Airflow DAG (ingest 40 tables from Postgres and Salesforce → dbt build of ~300 models on Snowflake, normally 01:00–04:30) failed in the stg_salesforce__opportunities model. The CFO’s revenue dashboard refreshes at 07:00 and is used in an 08:00 leadership meeting.
Answer:
“First I’d acknowledge the page and check blast radius: the lineage shows the failed staging model feeds fct_revenue and the CFO dashboard exposure, and because we use dbt build, the downstream models were skipped, so yesterday’s numbers are still intact. I’d post a short update in the incident channel within 10 minutes with the next update time. The log shows invalid identifier 'AMOUNT__C': Salesforce renamed a field overnight. That’s deterministic, so retrying won’t help. I’d map the renamed column in the staging model, push a reviewed hotfix, and run dbt build --select stg_salesforce__opportunities+ --target prod, prioritising +exposure:cfo_revenue. That chain takes about 40 minutes, so we’d finish around 04:30, well before 07:00. I’d then reconcile total pipeline value against Salesforce’s report. Afterwards I’d add a source schema check that alerts on missing columns before the build, and propose a change-notification agreement with the Salesforce admin team.”
Trade-offs:
| Option | When | Trade-off |
|---|---|---|
| Full rerun of DAG | Small DAGs | Wastes time/credits; may miss SLA |
| Repair/retry failed subtree | Most cases | Requires idempotent tasks |
| Serve stale data with banner | Fix impossible in time | Transparent but delays decisions |
| Hotfix in prod directly | Never without review | Speed vs risk; use expedited PR |
Learn more: Data Pipeline Observability Fundamentals
16. Late-arriving events are making daily aggregates wrong
Scenario:
A mobile app sends events to Kafka, which land in a lakehouse table (~300 M events/day). A daily job computes daily_active_users and revenue_by_day at 02:00 UTC for the previous day. About 3% of events arrive 1–72 hours late (phones offline), so yesterday’s numbers keep changing in the source, but the aggregates never update. Finance reports a 2.5% mismatch with the payments system.
Answer:
“I’d first quantify lateness from ingested_at - event_ts. Say 99.9% arrive within 72 hours. Then I’d change the job from ‘process yesterday’ to ‘process the event dates touched by anything ingested since the last run, limited to the last 4 days’. For each affected date I recompute the whole day from the event table, which is essential for distinct counts like DAU, and atomically replace that date’s partition. So a late event from 3 days ago correctly updates that day. Revenue gets the same treatment, and reconciliation with payments then matches within the window. I’d add a is_final flag (event_date < today − 3) so finance knows which days are settled, and a monitor counting events arriving more than 72 hours late. A weekly job reprocesses 14 days as a safety net. If this were streaming, I’d use watermarks of about 72 hours for the stateful aggregation, or keep streaming for low-latency provisional numbers and batch for the final correction.”
Approach:
- Measure lateness. Plot the distribution of
ingested_at - event_ts. If p99 is 48 h and p99.9 is 70 h, that sets the window you need to cover. - Keep both timestamps on every event (event time and ingestion time).
- Incremental selection by ingestion time: each run finds the event dates touched by newly ingested rows.
- Recompute the affected days fully. Don’t add deltas to aggregates like distinct users. Use partition replacement (
replaceWhere,insert_overwrite,delete+insert) for those dates. - Bound the work with a lookback of, say, 3 days in daily runs, plus a weekly 14-day correction run.
- Communicate finality. Label days within the window as provisional in dashboards, and mark them final after 72 h.
- Monitor the events arriving beyond the window, and alert if they’re non-zero.
Learn more: Spark Structured Streaming: Triggers, Watermarks and Exactly-Once
17. Duplicates discovered in a production fact table
Scenario:
An analyst finds that fct_orders (1.2 B rows, Snowflake, incremental dbt model) has about 180,000 duplicated order_ids from the last 10 days. Revenue dashboards are overstated by about 0.8%. The model uses an append strategy, and the upstream Fivetran connector had a resync on day 1 of that window.
Answer:
“I’d confirm the scope first: 180k duplicated order IDs, all ingested after the connector resync on the 3rd, as exact copies with different _fivetran_synced values. The model appended every incoming row and had no PK test, so nothing caught it. I’d clone fct_orders as a backup, which is instant in Snowflake, then fix the model to incremental_strategy='merge' with unique_key='order_id' and a dedupe in the source CTE keeping the latest sync. For remediation I’d run a delete+insert of the 10 affected order dates from the cleaned staging model inside one transaction, and verify zero duplicates and revenue matching the source system per day. Then I’d add unique/not_null tests on order_id. Since we run dbt build, a failure blocks the downstream marts. I’d also send finance a short note explaining the 0.8% restatement for those dates, with before and after numbers.”
Approach:
- Quantify: how many keys, which dates, and whether the duplicates are exact copies or differ in some columns.
- Find the cause. Here, an append strategy plus a connector resync re-sent rows. Check for missing
unique_keyand missing PK tests. - Contain: pause the job or fix the strategy so it doesn’t get worse. Tell the dashboard owners.
- Remediate:
- Option A: switch to merge with
unique_key='order_id'and do a targeted rebuild of the 10 affected days (delete+insert by date). - Option B: a one-off dedupe of the affected window with
QUALIFY ROW_NUMBER(), keeping the latest_fivetran_synced, in a transaction. - Take a zero-copy clone first, for rollback.
- Option A: switch to merge with
- Verify: a unique test passes, and revenue reconciles to the source.
- Prevent:
uniqueandnot_nulltests on the PK (withdbt build, so they block downstream), merge or delete+insert strategy, and a source-level duplicate monitor. - Communicate: share the restatement notice with the corrected figures and the time window.
Learn more: Fact Tables: Measures, Snapshots and Late-Arriving Facts
18. A Snowflake dashboard query takes 3 minutes; target is 10 seconds
Scenario:
A Tableau dashboard queries fct_sales (4 B rows, 1.2 TB) joined to three dimensions, filtered by the last 90 days and a region, grouped by week and product category. It runs on a Medium warehouse, takes about 3 minutes, and 60 sales managers open it every morning at 08:30, causing queuing.
Answer:
“I’d start with the Query Profile. It shows the table scan reading 85% of micro-partitions even though we only want 90 days, so pruning isn’t working. The SQL from Tableau filters on DATE_TRUNC('week', sale_ts), and the table is loaded by late batch jobs, so date ordering is poor. First fix: filter on a raw sale_date column, and add clustering on sale_date. That alone took the query to about 25 seconds in a test. But the dashboard only needs about 50,000 aggregated rows, so the real fix is a dynamic table at week × category × region with a 1-hour target lag, which queries in about 1 second. For the 08:30 rush I’d make the BI warehouse multi-cluster (max 3) rather than upsizing, and route the dashboard to it. Cost-wise, the dynamic table refresh is a few credits a day, far less than 60 three-minute queries on a Medium warehouse every morning.”
Approach:
- Query Profile: partitions scanned vs total (pruning), the most expensive operators, spill, and join explosion.
- Pruning: the date filter should prune heavily. If
sale_dateisn’t well clustered (data loaded out of order), clustering depth is poor. CheckSYSTEM$CLUSTERING_INFORMATION. - Query shape: filters applied in BI as functions on columns (
DATE_TRUNCin WHERE) or casts can prevent pruning. Check the generated SQL. - Pre-aggregate: the dashboard only needs week × category × region. A dynamic table or materialized view at that grain shrinks 4 B rows to about 50 k.
- Concurrency: the 08:30 spike needs a multi-cluster warehouse (min 1, max 4), not a bigger size.
- Caching: the result cache helps identical queries. Tableau extracts or live connections affect this.
- Measure cost: clustering credits plus dynamic table refresh vs warehouse savings.
Learn more: Snowflake Micro-Partitions, Clustering and Search Optimization
19. Upstream added and renamed columns without notice (schema drift)
Scenario:
A product team’s microservice writes JSON events to S3, ingested hourly by Auto Loader into a Databricks bronze table, then transformed by dbt into silver and gold. Yesterday they renamed price to unit_price and added discount_pct. Bronze ingestion kept working, but silver now shows NULL prices for 18 hours of data and the revenue dashboard dropped by 40%.
Answer:
“I’d immediately mark the revenue dashboard as degraded and tell finance. Since bronze stores the raw events, nothing is lost. I’d update the silver model to coalesce(unit_price, price), add discount_pct, and reprocess the last 24 hours of partitions with an idempotent replaceWhere. Revenue is back within an hour or two. The bigger problem is that this was silent. Bronze correctly evolved the schema, but nobody tested that price was populated. I’d add a not_null test with an error threshold on silver price, plus a null-rate anomaly monitor. Longer term, I’d agree a data contract with the product team: a JSON Schema in their repo, with CI that flags breaking changes, and a rule that renames ship both fields for two weeks with notice in our channel. On our side, contracted silver models fail loudly instead of producing NULLs.”
Approach:
- Contain: stop or flag downstream publishing (or mark the dashboard degraded). Notify consumers.
- Short-term fix: map both names in silver,
coalesce(unit_price, price) AS unit_price, and adddiscount_pct. Then reprocess the 18 affected hours from bronze. Bronze kept the raw data, so it’s replayable. - Why it was silent: bronze evolution added the new column, and silver selected
price, which was now NULL. There was no test on the null rate. - Detection:
not_nulltests, or null-rate anomaly checks on critical columns.- Auto Loader
_rescued_dataand schema-change notifications. - Schema diff alerts on bronze.
- Prevention:
- A data contract (schema registry or JSON Schema) with CI checks in the producer repo.
- Deprecation windows: send both fields for N days.
- Contract-enforced silver models (see Model contracts).
- Communicate, and do a post-mortem with the producer team.
20. Snowflake cost doubled overnight
Scenario:
Your Snowflake account normally consumes about 400 credits a day. Yesterday it used 820. Finance noticed this morning. There are 25 warehouses, 3,000 dbt models, Fivetran, BI tools, and a new data science team onboarded last week.
Answer:
“I’d query METERING_DAILY_HISTORY first. It shows the extra 420 credits are warehouse compute, not serverless. WAREHOUSE_METERING_HISTORY points at DS_WH, which went from about 10 credits a day to 380, starting at 14:00. QUERY_HISTORY for that warehouse shows a new data scientist ran a notebook that re-ran a cross-join-heavy feature query every 15 minutes, and someone resized the warehouse to 2X-Large to ‘make it faster’. I’d contact the user, cancel the scheduled loop, resize back to Medium, and confirm auto-suspend is 60 seconds. To prevent a repeat, I’d put a resource monitor on DS_WH at 50 credits a day that notifies at 80% and suspends at 100%, set a 1-hour statement timeout, and remove MODIFY rights on warehouses from non-admin roles. A daily cost-anomaly alert on WAREHOUSE_METERING_HISTORY would also catch this hours earlier. Then I’d pair with the DS team to rewrite the feature query incrementally.”
Approach:
- Break it down by service:
METERING_DAILY_HISTORYgives warehouse vs serverless (Snowpipe, auto-clustering, MVs, search optimisation, serverless tasks, AI functions) vs cloud services. - If warehouses:
WAREHOUSE_METERING_HISTORYby warehouse and hour. Find the spike’s warehouse and time. - Drill into queries:
QUERY_HISTORY/QUERY_ATTRIBUTION_HISTORYfor that warehouse and window, grouped by user, role, query tag and query hash. Look for the top credit consumers. - Typical culprits:
- A warehouse resized to X-Large and never reverted.
- Auto-suspend disabled.
- A runaway query or loop (a BI refresh every minute).
- A new data science notebook scanning huge tables.
- A full refresh of big dbt models.
- Reclustering after a big data change.
- Serverless features enabled broadly.
- Contain: suspend or resize the offending warehouse, cancel runaway queries, and talk to the owner.
- Prevent:
- Resource monitors per warehouse with suspend actions.
- Budgets.
STATEMENT_TIMEOUT_IN_SECONDS.- Auto-suspend of 60 seconds.
- Query tags for attribution.
- A separate warehouse for data science.
- Anomaly alerts.
Learn more: Snowflake Cost Optimization: Credits, Right-Sizing and Storage Costs
21. Databricks bill spiked 60% this month
Scenario:
The monthly Databricks bill rose from $120k to $192k. You have 8 workspaces, about 600 jobs, many interactive clusters, SQL warehouses, Lakeflow pipelines, and some model serving. Cloud VM costs, billed separately by AWS, also rose 45%.
Answer:
“I’d run a month-over-month diff on system.billing.usage by billing_origin_product and usage_metadata. It shows three drivers. All-purpose compute up $35k, mostly two always-on clusters used to schedule 40 notebooks. A Lakeflow pipeline switched to continuous mode for a demo and never switched back, $18k. And a new model-serving endpoint with scale-to-zero disabled, $12k. The cloud VM increase lines up with the always-on clusters. Fixes: move the 40 notebooks to serverless jobs, revert the pipeline to triggered every 30 minutes, and enable scale-to-zero on the dev endpoint. That gets us back near $125k. Then guardrails: a compute policy requiring auto-termination of 60 minutes or less and team tags, budget alerts per workspace at 80% of forecast, and a weekly report of the top 20 cost movers to team leads.”
Approach:
- Attribute:
system.billing.usagejoined withlist_prices, grouped by SKU, workspace, job, warehouse, cluster and tags. Compare this month with last month. - Find the movers: the top increases by product (ALL_PURPOSE, JOBS, SQL, DLT/pipelines, MODEL_SERVING, serverless).
- Common waste patterns:
- All-purpose clusters running scheduled jobs.
- Clusters without auto-termination.
- Continuous pipelines that only need hourly freshness.
- Oversized SQL warehouses with long auto-stop.
- Jobs whose runtime regressed (skew, small files).
- Model-serving endpoints that don’t scale to zero.
- Cloud cost side: VM hours (classic compute), storage growth (no VACUUM), and cross-region egress.
- Fix:
- Move jobs to job or serverless compute.
- Policies (auto-termination, max workers, required tags).
- Triggered pipelines.
- Right-size warehouses.
- VACUUM and predictive optimisation.
- Govern: budgets with alerts, tag enforcement, and a monthly FinOps review per team.
Trade-offs:
| Lever | Savings | Risk |
|---|---|---|
| Serverless jobs | Removes idle/startup waste | Higher per-DBU rate for long steady jobs |
| Spot instances | Large VM savings | Preemption for long stages |
| Photon | Faster → fewer hours | Higher DBU rate; benchmark |
| Triggered vs continuous | Big for sparse data | Higher latency |
| Aggressive auto-termination | Cuts idle | Slower dev restarts |
Learn more: Cloud Data Cost Optimisation and FinOps for Data Engineers
22. Recurring SLA breaches on a critical pipeline
Scenario:
A daily risk-reporting pipeline must deliver by 06:00. It missed the SLA 9 times in the last 30 days, typically finishing between 06:20 and 07:10. It depends on 4 upstream sources (one external vendor file arriving between 00:30 and 04:00), runs 180 dbt models, and shares a Snowflake warehouse with ad-hoc analysts.
Answer:
“I’d pull 30 days of run metadata and upstream arrival times. In 6 of the 9 misses, the vendor file arrived after 03:30, and our DAG started at a fixed 02:00, waiting on a sensor, then ran everything serially after. In the other 3, the job queued for 25–40 minutes behind analyst queries on the shared warehouse. So: give the pipeline its own warehouse, which removes the queueing. Restructure the DAG so everything not dependent on the vendor file runs at 00:30. When the file lands, run only the vendor-dependent critical path to the risk report, about 35 minutes after tuning two slow models to incremental. That gives a worst-case finish around 04:45 even with a 04:00 arrival. I’d add an alert at 04:15 if the file hasn’t arrived, so we can warn risk managers early, and raise a contractual SLA with the vendor for 03:00 delivery. We’d track SLO attainment weekly.”
Approach:
- Collect timing data for 30 days: upstream arrival times, job start and end, per-model durations, warehouse queuing.
- Correlate the misses with causes. For example, 6 of 9 misses had the vendor file arriving after 03:30, and 3 had warehouse queuing during analyst batch queries.
- Critical path: which models determine the end time? Optimise those, and run the rest after the deadline.
- Fixes:
- Event-driven start on file arrival instead of a fixed schedule (sensors, file-arrival triggers).
- Dedicated warehouse for the pipeline, so there’s no analyst contention, or multi-cluster.
- Split the DAG: the critical-path subset (
+exposure:risk_report) runs first. Non-critical marts follow. - Incremental models for the heavy parts.
- Vendor SLA: negotiate an earlier delivery, or a partial file plus a correction.
- Monitoring: predicted completion time alerts (“at current pace you’ll miss 06:00”), plus upstream arrival alerts.
- SLO and communication: define the SLO (for example 06:00 on 95% of days), publish the status page, and give business users an early warning when a miss is likely.
Learn more: Data Pipeline Observability Fundamentals
23. The data lake has millions of tiny files
Scenario:
An S3 data lake table events (Parquet, Hive-partitioned by date/hour/country) has 14 M files averaging 60 KB, for 800 GB in total. Spark queries spend minutes listing files, Athena queries time out, and S3 request costs rose to $3k/month. Ingestion writes every minute from a streaming job.
Answer:
“The layout is the problem. Partitioning by date, hour and country gives about 4,800 partitions a day, and a writer committing every minute puts several files into each. At 800 GB total we should have a few thousand files, not 14 million. I’d change the streaming job to a 5-minute trigger, repartition by date before writing, and drop hour and country as partition columns. Then I’d convert the table to Delta, partitioned by date only and clustered by country, or use Iceberg with day partitioning. A one-off compaction job rewrites each historical day into roughly 512 MB files, about 1,600 files in total. Going forward, auto-compaction plus nightly OPTIMIZE keeps files healthy, and VACUUM removes the replaced files after 7 days. Query planning drops from minutes to seconds, and the S3 GET and LIST costs fall by orders of magnitude.”
Approach:
- Root cause:
- 24 hours × 200 countries × 1,440 writes per day, with several tasks each, means huge fan-out.
- The
hourandcountrypartitions are too fine for 800 GB.
- Fix the writer:
- A longer trigger (5–15 minutes).
- Fewer output files per micro-batch (coalesce or repartition by partition column, optimized writes).
- Coarser partitioning (date only).
- Adopt a table format (Delta or Iceberg) for atomic compaction, metadata-based planning (no listing), and clustering instead of deep partitioning.
- Compact the history: a one-off job rewriting each day into files of about 256 MB–1 GB, then ongoing scheduled compaction (OPTIMIZE, Iceberg
rewrite_data_files). - Clean up: remove the old small files after a retention period (VACUUM, expire snapshots).
- Verify: file count, average size, query planning time, S3 request costs.
Trade-offs:
| Fix | Pros | Cons |
|---|---|---|
| Periodic compaction only | Quick | Problem recurs; compaction cost |
| Fix writer + coarser partitions | Root cause fixed | Requires pipeline change |
| Table format (Delta/Iceberg) | Atomic compaction, metadata pruning | Migration effort; reader compatibility |
| Longer trigger | Fewer files | Higher latency |
Learn more: Delta Lake Performance: OPTIMIZE, Z-Ordering, VACUUM and Liquid Clustering
24. Kafka consumer lag keeps growing
Scenario:
A consumer group processing payments (24 partitions) into a database falls further behind each day. Lag grew from about 0 to 40 M messages over a week. Producer throughput rose from 5k to 12k messages per second after a new market launch. The consumers do per-message enrichment API calls and single-row database inserts.
Answer:
“First I’d check lag per partition. It’s growing evenly across all 24, so it’s throughput, not skew. Each message does a synchronous enrichment call and a single-row insert, about 25 ms per message, so a consumer handles roughly 40 per second, and 24 consumers about 1,000 per second against 12,000 coming in. Adding consumers alone can’t fix that, because we’re capped at 24 by partitions. I’d restructure processing: poll batches of 500, enrich with a cached lookup (the enrichment data changes daily, so we can preload it), and write with batched inserts or COPY. That pushes each consumer to thousands per second. As an immediate mitigation, I’d raise topic retention from 7 to 14 days, so lag doesn’t turn into data loss while we deploy. After the fix, lag should drain within hours. I’d add alerting on lag above 5 minutes of traffic, and consider increasing partitions to 48 for headroom as the market grows.”
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| More consumers | Easy | Capped at partition count |
| More partitions | More parallelism | Key→partition remap; ordering changes for keys |
| Batching | Huge throughput gains | Larger retry units |
| Async enrichment | Overlaps I/O | Complexity, rate limits |
| Stream processor (Spark/Flink) | Scalable, batching built in | New platform to operate |
Learn more: Data Pipeline Observability Fundamentals
In depth: Consumer lag keeps growing. How do you diagnose and fix it?
25. Out-of-order events in a streaming aggregation
Scenario:
IoT sensors send temperature readings through Kafka. A Spark streaming job computes 5-minute average temperatures per device for alerts. Network issues cause readings to arrive up to 20 minutes out of order, and some devices buffer for hours. Alerts sometimes fire on incomplete windows, and the averages differ from the batch-computed truth.
Answer:
“The alerts fire on incomplete windows because the job either uses processing time or has too short a watermark. I’d make sure windows use the device event timestamp, then set the watermark from the measured lateness. Since 99% of readings arrive within 15 minutes, a 20-minute watermark in append mode emits each 5-minute window once, with most data present. For alerting, a 20-minute delay may be too slow, so I’d run update mode for a fast provisional signal: alert only if the average is above the threshold and at least, say, 80% of expected readings are in. Then a final check confirms once the window closes. Readings that arrive hours late are dropped by streaming state, but they still land in the raw Delta table, and a nightly batch job recomputes the affected windows for reporting accuracy. I’d also reject readings with timestamps in the future and flag devices with clock drift.”
Approach:
- Use event time (the sensor timestamp), not arrival time, for windows.
- Measure the lateness distribution: say 99% of readings arrive within 15 minutes, and a long tail within hours.
- Set the watermark (for example 20 minutes) with append mode, so each window is emitted once, after it’s mostly complete. Or use update mode for provisional results.
- Alerting logic: decide whether alerts need complete windows. Critical alerts might use provisional results (update mode) with a confidence flag. Reporting uses finalised windows.
- Very late data (beyond the watermark) is dropped from streaming state. Capture it with a separate path, the raw table, plus periodic batch corrections of affected windows.
- Clock issues: devices with bad clocks need sanity checks (reject future timestamps, or correct with an ingestion-time offset).
Learn more: Spark Structured Streaming: Triggers, Watermarks and Exactly-Once
26. A join on customer_id is skewed by one huge customer (See also Q264)
Scenario:
A B2B marketplace’s nightly Spark job joins line_items (3 B rows) with customer_contracts (40 M rows) on customer_id. One enterprise customer accounts for 22% of line items. The join stage shows 1,999 tasks finishing in 1–2 minutes and one task running 95 minutes before failing with executor OOM.
Answer:
“One task with 95 minutes and OOM, while the rest finish in 2 minutes, is skew. The top-keys query confirms customer ‘C-1001’ has 660 M line items. AQE skew handling should split that partition, so I’d check it’s enabled and tune skewedPartitionThresholdInBytes if the partition is just under the threshold. If AQE isn’t enough, the cleanest fix here is isolating the hot key. That customer has only about 300 contract rows, so I’d filter line_items for C-1001 and broadcast-join them with its contracts. Spark then spreads those 660 M rows across all tasks with no shuffle on the skewed key. The remaining customers go through the normal sort-merge join, and I union the two results. The stage drops to a few minutes. I’d make the hot-key list dynamic, computed from yesterday’s top keys, and add a monitor on key concentration, so the next big customer doesn’t surprise us. Adding executors wouldn’t help, because one key always goes to one task.”
Approach:
- Confirm the skew: top-N key counts and that task’s shuffle read size.
- Check AQE: is skew-join handling enabled? Do the thresholds trigger (factor 5, 256 MB)? Is the join type supported?
- Can the other side be broadcast? At 40 M rows it’s probably too large. Can it be filtered to active contracts first?
- Isolate the hot key:
- Split
line_itemsinto the hot customer and everything else. - Join the hot customer’s rows to its few contract rows with a broadcast, which is tiny for one customer.
- Join the rest normally, then union the results.
- Split
- Or salt the hot key with N buckets and replicate the matching contract rows N times.
- Validate: results are identical to a reference (row counts), and the runtime improves.
Learn more: Spark Partitions, Shuffles and Data Skew
27. An incremental load silently missed records
Scenario:
An hourly job loads changed rows from a MySQL orders table using WHERE updated_at > :last_max_updated_at, then sets the new watermark to max(updated_at) of the batch. A monthly audit found about 0.2% of orders missing in the warehouse, all with updated_at values close to batch boundaries.
Answer:
“The pattern updated_at > max(updated_at) assumes rows become visible in timestamp order, which isn’t true. A transaction can stamp updated_at at 10:59:58 and commit at 11:00:05, after our extract read the table, and the next run starts after 10:59:59, so that row is skipped forever. I’d change the extraction to re-read a 15-minute overlap, updated_at >= watermark - 15 minutes, and MERGE on order_id, so re-reading is harmless. The watermark becomes the extract start time minus the overlap, not the max value seen. That covers long transactions up to 15 minutes, and I’d check the longest transaction durations in MySQL to size it. Longer term, I’d move to binlog-based CDC with Debezium or a managed connector, which captures every committed change in commit order. For the missing 0.2%, I’d backfill by comparing order IDs for the last 90 days and loading the gaps, then add a daily reconciliation of counts per day.”
Approach:
- Explain the failure modes:
- Late commits: a transaction starts at 10:59:58 (and sets
updated_atthen) but commits at 11:00:05, after the 11:00 extract has already read up to 10:59:59. The next run uses> 10:59:59, so the row is missed forever. - Equal timestamps at the boundary with strict
>, when several rows share the max timestamp and some weren’t visible yet. - Application clock skew across servers.
- Timestamp precision truncation (seconds vs microseconds).
- Late commits: a transaction starts at 10:59:58 (and sets
- Fix:
- Overlap: select
updated_at >= last_watermark - 15 minutes, and MERGE on the PK (idempotent), so duplicates are harmless. - Watermark as of the extract start minus a safety margin, not the max seen.
- Or switch to log-based CDC (binlog), which captures commits in order (see CDC from a PostgreSQL OLTP database into the warehouse).
- Overlap: select
- Repair: backfill the gap with a reconciliation, comparing IDs over the audit window.
- Detect: daily count and sum reconciliation per day (see Source and target row counts don’t match).
Learn more: Incremental Loading, Watermarks, Late Data and Backfills
28. Airflow tasks stuck in queued state
Scenario:
On a self-managed Airflow deployment (CeleryExecutor or KubernetesExecutor, about 400 DAGs), many tasks sit in “queued” for 30+ minutes every morning between 02:00 and 04:00, and some DAG runs miss their SLAs. The worker nodes show low CPU.
Answer:
“Low worker CPU with many queued tasks means tasks aren’t being handed to workers, so I’d check the limits layer by layer. In this case core.parallelism was 32, sized for the original setup, while 6 Celery workers with concurrency 16 offered 96 slots, so at most 32 tasks ran globally. Also, 150 DAGs were scheduled exactly at 02:00. Scheduler metrics showed DAG file parsing taking 90 seconds per loop, because several DAG files called a database at import time. Fixes: raise parallelism to match worker capacity (about 128 with 8 workers), move the import-time database calls into tasks or into cached Variables, and stagger schedules or switch dependent DAGs to asset-based triggers. I’d also check that the default_pool isn’t throttling, and add a pool for the Snowflake-heavy tasks so they don’t overload the warehouse. After the changes, queued time dropped from 30 minutes to under 1 minute. I’d alert on p95 queued duration.”
Approach:
- Concurrency settings, checked layer by layer:
core.parallelism(global running task slots).max_active_tasks_per_dag/max_active_runs_per_dag.- Pools (default pool 128 slots, custom pools exhausted?).
- Celery
worker_concurrency× number of workers. - Kubernetes namespace quotas or pod pending reasons.
- Queue mismatch: tasks assigned to a Celery queue that no worker listens to stay queued forever.
- Scheduler health: scheduler loop time, DAG parsing time (heavy top-level code in DAG files), the number of schedulers, and metadata database performance (connections, locks).
- Kubernetes: pods pending because of insufficient node capacity, image pull delays, resource requests too large, or cluster autoscaler lag.
- Workload shape: 400 DAGs all scheduled at 02:00 create a thundering herd. Stagger schedules, or use data-aware or asset-triggered scheduling.
- Fix and monitor: adjust the limits, add workers or autoscaling (KEDA for Celery), and track queued-time metrics.
Learn more: Airflow Executors, Pools and Scaling
In depth: Airflow is slow and tasks sit in scheduled or queued. How do you find the bottleneck?
29. Auditors need lineage and a data catalog
Scenario:
An insurance company’s auditors want to know, for 25 regulatory reports, where every number comes from, who can access the underlying data, and what changed in the last 12 months. The current state is undocumented pipelines across Snowflake, dbt, Airflow and some Python scripts. The audit is in 10 weeks.
Answer:
“I’d focus on the 25 reports, not the whole estate. Most logic is already in dbt, so I’d add exposures for each report and generate lineage from the dbt manifest. For the Snowflake side, ACCESS_HISTORY confirms which tables each report’s queries actually read, and who accessed them. The few Python scripts feeding two reports I’d either instrument with OpenLineage or port into dbt models. Porting is better long term. All of this goes into a catalog, Snowflake Horizon here since we’re mostly on Snowflake, or DataHub if we need cross-platform coverage, with owners, descriptions and PII tags. For change evidence, our Git history shows every reviewed change to those models over 12 months, linked to deployments. Each report gets an audit pack: lineage diagram, metric definitions, data quality tests, access list, change log. After the audit, CI requires exposures and owners for any regulatory model, so we don’t scramble next year.”
Approach:
- Scope: list the 25 reports and their source tables. Trace backwards only what’s needed first.
- Use native lineage:
- dbt manifest and docs for model lineage, with exposures for the reports (see Exposures).
- Snowflake
ACCESS_HISTORYand object dependencies, or Unity Catalog lineage. - OpenLineage from Airflow for task-level lineage.
- Fill the gaps: Python scripts outside dbt need manual documentation or instrumentation (OpenLineage integration), or should be migrated into dbt.
- Catalog: choose a tool (Snowflake Horizon, Unity Catalog, DataHub, Atlan, Collibra) to ingest the metadata, then add owners, descriptions and classification tags.
- Access evidence: role grants and access history for the in-scope tables (who queried them).
- Change evidence: Git history and PR reviews for transformation code, deployment logs, and schema change logs.
- Package it: per report, a lineage diagram, metric definitions, owners, controls (tests), access list, and change log.
Learn more: Data Governance, Lineage and Data Mesh Explained
30. Migrate orchestration from Airflow to a managed service
Scenario:
A team runs self-hosted Airflow 2.x on VMs with 250 DAGs. Upgrades are painful, the scheduler crashes monthly, and two engineers spend about 30% of their time on Airflow operations. Leadership asks you to evaluate migrating to a managed option (MWAA, Astronomer, Cloud Composer, or native Lakeflow Jobs / Snowflake tasks), and to execute it in 4 months.
Answer:
“Since most of the 250 DAGs orchestrate across Postgres, S3, Snowflake and APIs, I’d stay in the Airflow paradigm and move to managed Airflow rather than rewrite into a platform-native scheduler. I’d shortlist MWAA and Astronomer based on our cloud, networking and Airflow 3 support. Month 1: inventory operators, plugins and connections; fix DAGs with heavy top-level code or local-disk dependencies; move connections to a secrets backend; and build the dependency image. A compatibility test runs every DAG’s parse and a dry run in the new environment. Months 2–3: migrate in four waves, starting with low-risk internal DAGs. Each DAG is paused on the old cluster and unpaused on the new one at a run boundary, so nothing double-runs, with quick rollback by swapping back. Month 4: the critical finance DAGs, with extra monitoring, then decommission the VMs. Success criteria: no missed SLAs during migration, and ops time down from 30% to under 5%.”
Approach:
- Inventory: DAGs, operators and providers used, custom plugins, connections and variables, schedules, SLAs, and dependencies on the VM environment (local files, system packages).
- Options:
- Managed Airflow (MWAA, Astronomer, Composer): minimal code change, same paradigm.
- Platform-native (Lakeflow Jobs, Snowflake tasks, dbt platform jobs): less ops and tighter integration, but a rewrite and potential lock-in, and cross-system orchestration is weaker.
- Decide using the criteria:
- Compatibility with existing DAGs.
- Cross-system needs.
- Cost: managed fees vs the engineers’ time.
- Security and networking (private connectivity to sources).
- Upgrade path (Airflow 3 support).
- Prepare: move secrets to a secrets backend, remove top-level code and local file dependencies, and package dependencies (
requirementsor images). - Migrate in waves: low-risk DAGs first. Run in parallel with the destinations writing to separate targets, or in a shadow mode, then cut over by pausing the old DAGs.
- Decommission the old infrastructure, and document runbooks.
Learn more: What Is Data Orchestration? Orchestration vs Scheduling vs ETL
31. A hot partition in a Kafka topic
Scenario:
The order_events topic has 32 partitions keyed by merchant_id. One large merchant produces 40% of all events, so partition 7 receives about 13 times the average traffic. Its consumer lags for hours during sales, while the other consumers are idle. Ordering per order must be preserved.
Answer:
“Keying by merchant_id means all of the big merchant’s events go to one partition, so one consumer does 40% of the work. I’d first confirm what ordering we actually need. For order processing it’s per order, not per merchant. Then the fix is to key by order_id, which spreads the merchant’s events evenly across all 32 partitions while every event of a given order still lands in the same partition, in order. Because changing the key remaps partitions, I’d create order_events_v2 keyed by order_id, switch the producers, and have consumers drain v1 to the end before reading v2, so there’s no reordering for in-flight orders. If some downstream logic did need per-merchant ordering, I’d handle that in a stream processor that aggregates per merchant from the evenly distributed topic. Afterwards, per-partition lag dashboards would show balanced load.”
Approach:
- Clarify the ordering requirement: is it per order (
order_id) or per merchant? Usually per order or per customer, not per merchant. - Re-key: use
order_id(or a compositemerchant_id + order_id) as the message key, which spreads the large merchant across all partitions while keeping per-order ordering. - If per-merchant ordering is truly needed: split hot merchants into sub-streams (
merchant_id + bucket, where bucket is a hash oforder_idmod N) and accept ordering per bucket. Or give the big merchant a dedicated topic with more partitions. - Migration: changing keys changes partition assignment. Do it with a new topic version (
order_events_v2), dual-write or migrate the producers, then switch the consumers at a known offset or time. Consumers must tolerate the transition. - Consumer side: if the consumer aggregates per merchant, use a stateful stream processor that handles the redistribution correctly.
- Monitor: per-partition throughput and lag dashboards.
Learn more: Kafka Topics, Partitions and Consumer Groups
32. Source sends full daily dumps; detect only the changes
Scenario:
A legacy ERP exports a full daily CSV of the products table (40 M rows, 120 columns, ~25 GB). There’s no updated_at column and no CDC. Downstream needs an SCD2 dimension and a change feed for a search index. Loading and fully reprocessing everything daily takes 3 hours.
Answer:
“Without timestamps or CDC, I’d diff snapshots. Each day the CSV is loaded into a staging Delta table, and I compute row_hash = sha2(concat_ws('||', coalesce(col1, '∅'), ...)) over the 120 business columns, normalising whitespace and case where appropriate. A full outer join with yesterday’s current-state table on product_id classifies inserts, updates (hash changed) and deletes (missing today). Typically only about 1–2% of rows change, so the change table is small. That change set drives the SCD2 merge for dim_product and is published to the search index, so neither reprocesses 40 M rows. A safety check stops the run if today’s row count is more than 5% below yesterday’s, because a truncated export would look like a million deletes. The whole diff takes minutes instead of hours. On Databricks, AUTO CDC FROM SNAPSHOT implements exactly this pattern declaratively.”
Approach:
- Load today’s dump into staging (Parquet or Delta conversion first, for speed).
- Compute a row hash of the business columns (normalised, NULL-safe) per primary key.
- Compare with yesterday’s snapshot (or the current state table) by full outer join on the key:
- Key only in today: insert.
- Key in both, hash differs: update.
- Key only in yesterday: delete (if the dump is guaranteed complete).
- Produce a change table (op, key, columns,
snapshot_date), then apply it to SCD2 (see SCD Type 2 on a 500-million-row customer dimension) and publish it to the search indexer. - Guard against bad dumps: if the row count drops by more than X%, stop. A truncated file would otherwise look like mass deletes.
- Retention: keep N days of snapshots for reprocessing.
- Tools: Databricks
AUTO CDC FROM SNAPSHOT, dbt snapshots (check strategy), or plain SQL hash diffs.
Learn more: CDC Patterns and Failure Modes
33. Share data with an external partner securely
Scenario:
A retailer must share daily sell-through data (store × SKU × day, about 50 M rows per year) with 30 suppliers. Each supplier may only see its own products, without customer PII. Some suppliers use Snowflake, some Databricks, and some only want CSV files. Today this happens through emailed spreadsheets.
Answer:
“I’d build one curated, PII-free partner_sell_through table and expose it through secure views with a row access policy driven by a supplier-entitlement table. Each supplier only sees rows for its own SKUs. For the Snowflake suppliers, that’s a direct share or private listing per supplier account, which gives live data, no copies, and access I can revoke instantly. Databricks suppliers get the same data via Delta Sharing, or, if we’re Snowflake-only, via a reader account or Iceberg-based sharing. The CSV-only suppliers get a nightly export job writing per-supplier encrypted files to their own SFTP folder or object-storage prefix, generated from the same filtered views so the logic is identical. Everything is documented in a data dictionary, with a 30-day notice policy for schema changes, and access logs reviewed monthly. When a supplier contract ends, we revoke their share or credentials the same day.”
Approach:
- Curate a share-ready dataset: aggregated, with no PII, and documented columns. Store it in a dedicated schema.
- Row-level isolation: a supplier-entitlement mapping table plus secure views or row access policies filtering by the consumer’s account or identity. Or separate views per supplier.
- Mechanisms:
- Snowflake consumers: Secure Data Sharing or listings (no copies, live data; see Secure Data Sharing and reader accounts).
- Databricks or open consumers: Delta Sharing (see Delta Sharing). Snowflake-to-non-Snowflake via reader accounts is an option too.
- File-only consumers: scheduled exports to per-supplier SFTP or object storage prefixes with short-lived credentials or signed URLs, encrypted.
- Contracts and legal: a data-sharing agreement, usage terms, and retention.
- Operations: freshness SLAs, a schema change policy, monitoring of consumption, and audit logs of access.
- Revocation: remove grants or the share immediately when a contract ends.
Trade-offs:
| Mechanism | Pros | Cons |
|---|---|---|
| Native sharing (Snowflake/Delta Sharing) | Live, no copies, revocable | Consumer platform dependency |
| File exports | Universal | Copies proliferate; harder revocation |
| API | Controlled, real-time | Build and maintain API |
| Clean rooms | Joint analysis without raw access | More complex setup |
Learn more: Snowflake Data Sharing, Reader Accounts and the Marketplace
34. A MERGE into a large table runs for hours
Scenario:
A nightly MERGE upserts about 5 M changed rows into fct_events (8 B rows, 3 TB) on Snowflake (or Delta). It now runs for 3+ hours on a Large warehouse. The MERGE condition is ON t.event_id = s.event_id. Most changes affect the last 7 days, but some updates reach back up to 60 days.
Answer:
“The MERGE joins on event_id only, so Snowflake can’t prune and scans all 8 B rows to find matches. I’d first compute the minimum event_date in the source batch, 60 days back at worst, and add AND t.event_date >= :min_date to the ON clause. With the table clustered by event_date, that prunes about 95% of the table. I’d also check the batch: typically 80% of the 5 M rows are new events that never existed, so I’d insert those directly and MERGE only the roughly 1 M real updates, after deduping by event_id. With pruning and a smaller MERGE, it should drop from 3 hours to around 10–15 minutes. If updates are spread across too many dates for pruning to help, delete+insert per affected date can be cheaper than a row-level MERGE. I’d validate the result with counts per date and a uniqueness test on event_id.”
Approach:
- Profile: the target scan reads most micro-partitions or files, because
event_idis random relative to the physical layout. - Add a pruning predicate: include
t.event_date >= :min_source_date(computed from the source batch) in the ON clause, or useincremental_predicatesin dbt (see Incremental strategies by adapter (append, merge, delete+insert, insert_overwrite, microbatch)). - Cluster the target by
event_date(or liquid clustering onevent_dateandevent_id), so the date predicate prunes well. - Narrow the source: dedupe to one row per key, and remove rows identical to the target (hash compare) to shrink the MERGE.
- Split the work:
- Most of the 5 M rows may be brand-new events. Append those, and MERGE only the true updates.
- Or delete+insert per affected date partition for the dates in the batch.
- Databricks specifics: deletion vectors, Photon and low-shuffle MERGE reduce the rewrite cost (see MERGE INTO for upserts and its performance).
- Measure partitions scanned, bytes written and duration before and after.
Learn more: Delta Lake MERGE, Change Data Feed and Streaming
35. Design the dimensional model for e-commerce orders
Scenario:
An e-commerce company wants analytics on orders: revenue by product, category, customer segment, channel, promotion and day. They also want returns analysis, an order funnel (placed → shipped → delivered), and customer lifetime value. Sources: orders, order lines, payments, shipments, returns, products (with category changes), customers (segment changes), and promotions.
Answer:
“I’d start with grain. The core is fct_order_line, one row per order line, because revenue by product and promotion needs line-level detail. It carries quantity, gross, allocated discount, tax and net amounts in transaction currency and USD, with keys to the date (order date), customer, product, promotion, channel and geography dimensions. Order-level discounts are allocated to lines proportionally, so sums add up. For the funnel, an accumulating snapshot fct_order_fulfillment has one row per order, with placed, paid, shipped and delivered timestamps and lag measures, updated as status changes. Returns get their own fct_return_line, linked to the original order line, so net revenue equals sales minus refunds. dim_customer and dim_product are SCD2, because segment and category changes must not rewrite history, and the facts use the surrogate key valid at order time. dim_date plays multiple roles. CLV is a derived mart over facts per customer. Unknown-member rows handle late dimension data.”
Approach:
- Business processes: ordering, payment, fulfilment and returns.
- Facts:
fct_order_line(grain: one row per order line), a transaction fact with quantity, gross, discount, tax and net amounts.fct_order_fulfillment(grain: one row per order), an accumulating snapshot with timestamps for placed, paid, shipped and delivered, plus lag measures.fct_return_line(grain: one row per returned line), with the reason and refund amount.- Optionally
fct_payment(one row per payment) for split payments.
- Dimensions:
dim_date(role-playing: order date, ship date, delivery date).dim_customer(SCD2 on segment).dim_product(SCD2 on category and price tier).dim_channel,dim_promotion,dim_geography.
- Keys: surrogate keys, with the fact rows referencing the dimension version valid at order time.
- Derived marts: daily revenue aggregates and a customer LTV table built from facts.
- Edge cases:
- Multi-currency (store the original and converted amounts).
- Order-level discounts allocated to lines.
- Cancelled orders (a status column or a separate fact).
- Late-arriving dimensions, handled with unknown members.
Learn more: Star, Snowflake and Galaxy Schemas and the Grain
36. A pipeline gets slower every month
Scenario:
A daily customer analytics pipeline took 25 minutes a year ago. It now takes 2 hours 40 minutes, growing about 15% a month. Data volume grew 2× in the same period. No major code changes. It runs on Spark (or Snowflake) with mostly full-table rebuilds.
Answer:
“Runtime growing 6× while data grew 2× suggests the work scales with total history, or worse. I’d chart runtime per stage over 12 months. In this case, three models dominate: a full rebuild of customer_metrics that recomputes lifetime aggregates from all orders every day, a join between events and a growing session table without date pruning, and a table with 40,000 small files from daily appends. Fixes: make customer_metrics incremental by maintaining lifetime totals and adding each day’s delta, recomputing only the customers with new activity. Add a date filter so the events-sessions join only touches the last 2 days. Compact the small-file table, with auto-compaction going forward. That brings runtime back to around 30 minutes, and future growth tracks daily volume instead of total history. I’d add a monthly trend report and an alert if runtime exceeds 60% of the SLA window, so we catch the next regression early.”
Approach:
- Profile the trend: runtime per step over months. Which steps grew faster than the data?
- Typical causes:
- Full rebuilds over ever-growing history: cost grows with total size, not daily volume.
- Joins against growing tables without pruning.
- Window functions over all history (running totals since day one).
- Small files and metadata growth (see The data lake has millions of tiny files).
- Unvacuumed tables with many versions.
- Skew growth (big customers getting bigger).
- Shared warehouse contention growing over time.
- Fix:
- Convert large steps to incremental processing (see Incremental models and is_incremental()).
- Partition or cluster for pruning.
- Incremental or state-based computations for cumulative metrics (keep running totals and add the daily delta).
- Compaction and maintenance schedules.
- Plan capacity: project the runtime against the SLA based on the growth rate, and set alerts when the runtime crosses thresholds.
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Scale compute | Immediate | Cost grows with data; masks inefficiency |
| Incremental redesign | Sustainable | Engineering effort; correctness care |
| Archive cold history | Smaller working set | Access patterns for history change |
| Pre-aggregated snapshots | Fast reads | Additional storage, refresh logic |
Learn more: Spark Partitions, Shuffles and Data Skew
37. Make KPIs consistent across three BI tools
Scenario:
Finance uses Power BI, marketing uses Tableau, and product uses Looker. “Active customers”, “net revenue” and “churn rate” differ across the three by 3–12%. Each tool has its own calculated fields over the same Snowflake marts. Leadership wants one number per KPI within one quarter.
Answer:
“This is half governance, half engineering. I’d first document how each tool calculates the three KPIs. For example, Tableau’s ‘net revenue’ excludes refunds issued after month-end, and Looker’s ‘active customers’ counts free trials. Then I’d get finance and product leadership to agree one definition for each, with an owner. For implementation, I’d define the metrics once in the dbt Semantic Layer (or Snowflake semantic views, if we standardise on Snowflake) on top of the existing marts. Power BI and Tableau connect through the semantic layer integrations, and for Looker we’d map the LookML measures to the same definitions, or point it at certified metric tables generated from the semantic layer. Every dashboard tile showing these KPIs gets migrated and labelled ‘certified’. We’d publish a reconciliation showing old vs new numbers and why. Changes to definitions then require a PR approved by the metric owner, so they can’t drift again.”
Approach:
- Inventory the definitions of each KPI in every tool, and document the differences (filters, time grain, currency, treatment of refunds and trials).
- Agree on definitions with the business owners: a metric council or the finance owner for financial KPIs. Write them up in a glossary with a name, formula, grain, filters, owner and version.
- Choose where the logic lives:
- Semantic layer (dbt Semantic Layer/MetricFlow, Cube, AtScale, LookML as a hub, Snowflake semantic views, Databricks metric views) queried by all the tools.
- Or certified metric tables (pre-computed KPIs at common grains) in Snowflake that all tools read directly.
- Implement: metrics as code with tests. Reconcile the old and new numbers, and explain the differences.
- Migrate the dashboards: replace tool-specific calculated fields with references to the semantic layer or certified tables. Badge certified dashboards.
- Govern: changes go through PR plus owner approval, and usage of non-certified calculations is monitored.
- Communicate: a changelog and a “why your number changed” note.
Learn more: Modern Data Modeling: Streaming Models, Semantic Layers and dbt
Advanced scenario-based questions (experienced)
38. Backfill two years of history without breaking production
Scenario:
A new business rule changes how net_revenue is calculated. You must recompute two years (730 days) of a 6 B-row fact table on Databricks, partitioned by order_date, while daily production loads keep running, dashboards stay available, and the backfill budget is about $8k of compute.
Answer:
“I’d avoid touching the live table during the backfill. I’d create fct_orders_v2 with the new logic and backfill it month by month using a Lakeflow Job For-each task over 24 months, concurrency 4, on a dedicated job cluster with spot workers. Each month writes with replaceWhere on its date range, so any month can be rerun safely, and a control table records status and row counts. Timing one month first gives me the real cost. If it’s around $250 per month, 24 months comes to roughly $6k, within budget. Meanwhile the daily job writes the current day to both tables, so v2 doesn’t fall behind. Validation per month compares row counts and recomputes revenue under the old rule from v2 to make sure only the intended change happened. Finance signs off on the deltas for a sample of months. Cutover is a view swap (fct_orders → v2) done in a quiet window, with the old table retained for a month for rollback.”
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| In-place partition rewrite | No extra storage | Consumers see mixed logic mid-backfill |
| Shadow table + swap | Clean cutover, easy rollback | Double storage temporarily, dual writes |
| Full rebuild in one job | Simple | One failure restarts everything; huge cluster |
| Effective-dating the rule (no backfill) | Cheapest | History inconsistent with new definition |
Learn more: Incremental Loading, Watermarks, Late Data and Backfills
39. A Spark job went from 40 minutes to 4 hours
Scenario:
A nightly PySpark job on Databricks joins orders (2 TB) with customers (60 GB) and promotions (200 MB), aggregates, and writes to Delta. It ran in 40 minutes for months. Last week it jumped to 4 hours. No code changed, but a platform team upgraded the runtime version, and marketing launched a promotion with one partner account generating huge volume.
Answer:
“I’d open the Spark UI for last month’s run and last night’s. The bad run’s join stage has 799 tasks finishing in about 2 minutes, and one task running 3.5 hours with 300 GB of shuffle read. That’s skew, and it lines up with the partner promotion: one customer_id now has 25% of orders. I’d also check the plan diff, because the runtime upgrade could change the join strategy. Promotions was still broadcast, fine. The fix is to make sure AQE skew-join handling is enabled and tuned, which splits the oversized partition automatically. If that’s not enough, because the skewed side is an aggregation, I’d salt the hot key or process it separately, then union. I’d also filter rows with NULL customer IDs out of the join. After the fix the job ran in 45 minutes. To catch this earlier, I’d add a job duration warning at 1.5× the median, plus a daily top-keys report on the join column.”
Approach:
- Compare a good run with a bad run: input sizes, the runtime version, the cluster config and the physical plans (
explain, the SQL tab). - Find the slowest stage. Is the task duration distribution skewed (one task taking hours), or is everything slower evenly?
- Check the hypotheses:
- Skew from the partner account: one task with huge shuffle read.
- Plan regression after the upgrade: a broadcast join became a sort-merge join, or AQE settings changed.
- Data growth or small files: the input file count exploded.
- Spill or GC from memory pressure.
- Cluster: autoscaling capped, or spot losses.
- Fix the top cause: AQE skew join, salting or isolating the hot key, a broadcast hint for promotions, file compaction.
- Re-measure, then add a duration alert and a regression check.
Learn more: Spark Partitions, Shuffles and Data Skew
40. Design a real-time clickstream pipeline (50k events/sec)
Scenario:
Design a pipeline for web and app clickstream: a peak of 50,000 events per second (about 4 B events/day, ~1 KB each, ~4 TB/day raw). Requirements: real-time dashboards (active users per minute, with under 1 minute of latency), sessionised data for analysts by the next morning, 13 months of retention, GDPR deletes, and a budget-conscious team of 5 engineers.
Answer:
“At 50k events per second of about 1 KB, that’s around 50 MB/s at peak, so I’d use managed Kafka with 64 partitions keyed by session_id, enough for ordering per session and parallelism with headroom. A Structured Streaming job on job compute reads Kafka, validates against the schema registry, sends bad events to a DLQ topic, dedupes by event_id within a 2-hour watermark, and writes silver Delta every 60 seconds with optimized writes and auto-compaction. A second small stream computes active users per minute with HyperLogLog-style approximate distinct counts and a 5-minute watermark, written to a small Delta table the dashboard polls, which gives roughly 1–2 minutes end to end. Sessionisation and marts run as an hourly batch with dbt, which is simpler to backfill. User IDs are pseudonymised at ingest, with the mapping in a restricted table, so a GDPR delete means deleting the mapping plus targeted deletes. With five engineers I’d lean on managed services and serverless where possible, and keep a single processing engine to limit operational load.”
Trade-offs:
| Choice | Option A | Option B | Notes |
|---|---|---|---|
| Stream engine | Spark Structured Streaming | Flink | Spark aligns with lakehouse batch; Flink lower latency, richer state |
| Real-time serving | Delta table + BI polling | Druid/Pinot/ClickHouse | OLAP engine for sub-second, high-concurrency |
| Distinct users | Exact (state heavy) | Approximate (HLL) | Approx is cheaper; state bounded |
| Sessionisation | Streaming stateful | Batch hourly | Batch easier to correct/backfill |
| Kafka | Self-managed | Managed | Managed reduces ops for small team |
41. CDC from a PostgreSQL OLTP database into the warehouse
Scenario:
The orders service runs PostgreSQL 16 (2 TB, 120 tables, ~3,000 writes per second at peak). Analytics currently runs nightly SELECT * dumps that take 5 hours and slow the primary database. The business wants data in Snowflake within 15 minutes, deletes reflected, and no impact on the OLTP workload.
Answer:
“I’d replace the dumps with log-based CDC using Debezium’s PostgreSQL connector, which reads the WAL through a logical replication slot. That adds very little load compared with full scans. Debezium does an initial incremental snapshot table by table without locking, then streams inserts, updates and deletes into Kafka topics keyed by primary key, with Avro schemas in a registry. The Snowflake Kafka connector lands changes with Snowpipe Streaming into a raw changes table per entity, in seconds. A dynamic table, or a task every 5 minutes, dedupes to the latest change per key by LSN and MERGEs into the current-state tables. Deletes become soft-delete flags, so downstream incremental models see them. The biggest operational risk is replication slot lag filling the primary’s disk, so I’d alert on slot lag and set max_slot_wal_keep_size. I’d also make sure every table has a primary key or a defined replica identity, and run daily count reconciliations per table.”
Trade-offs:
| Option | Pros | Cons |
|---|---|---|
| Debezium + Kafka | Open, flexible, multi-consumer | Kafka + Connect ops burden |
| Managed ELT (Fivetran etc.) | Fast to set up, low ops | Per-row cost; less control |
| Query-based incremental (updated_at) | Simple | Misses deletes; load on source; clock issues (see Airflow executors: Local vs Celery vs Kubernetes) |
| Warehouse-native connectors (Openflow, Lakeflow Connect) | Integrated governance | Feature coverage varies |
Learn more: CDC Patterns and Failure Modes
42. Migrate an on-prem Oracle/Teradata warehouse to the cloud
Scenario:
A bank runs a 40 TB Teradata warehouse with about 3,500 tables, 1,200 BTEQ and stored-procedure jobs, and 400 BI reports. The data centre contract ends in 14 months. Target: Snowflake (or Databricks), with dbt for transformations. The regulators require reports to stay identical through the migration.
Answer:
“I’d start with a 6-week assessment: pull 90 days of Teradata query logs to see which of the 3,500 tables and 400 reports are actually used. Typically a third can be retired, which shrinks scope. Then I’d group the rest into about 6 domain waves and pilot with one, say retail deposits. Data moves by bulk export to S3 and COPY for history, plus daily incremental extracts during the parallel run. For code, I’d run an automated converter for DDL and simple SQL, but rewrite the complex BTEQ and stored procedures as dbt models with tests, rather than translating procedural code line by line. Every table gets automated validation: counts, sums of numeric columns, and hash comparisons on keys. Every regulatory report is compared field by field. Each wave runs in parallel through at least one month-end, and the business signs off before cutover. A rollback plan keeps Teradata read-only for 60 days after each wave. With 14 months, I’d aim to finish migration by month 11, leaving buffer.”
Approach:
- Assess:
- Inventory objects, jobs, dependencies and usage (query logs to find unused tables, often 30–40%).
- Classify the complexity of each object.
- Map out security and regulatory needs.
- Plan the waves by business domain, starting with a low-risk but meaningful domain as a pilot. Define the target architecture (raw → staging → marts, RBAC, environments, CI/CD).
- Move the data:
- Historical bulk export to cloud storage, then COPY.
- Incremental sync (CDC, or delta extracts) during the parallel run.
- Convert the code:
- Automated tools (SnowConvert, other converters) for DDL and SQL.
- Refactor stored procedures and BTEQ into dbt models and orchestrated jobs.
- Don’t lift and shift bad patterns blindly.
- Validate:
- Row counts and checksums per table.
- Column-level aggregates.
- Report-level comparisons.
- Automated diff tooling (audit_helper, data-diff).
- Parallel run: at least one full month-end close, with signed-off reconciliations.
- Cut over: repoint BI, freeze the legacy system, keep a rollback plan, then decommission.
- People: training, a runbook, and support during hypercare.
43. SCD Type 2 on a 500-million-row customer dimension
Scenario:
A telecom maintains dim_customer with SCD2 history: 500 M rows total, about 80 M current. A daily CDC feed delivers roughly 2 M changed customers. Today’s MERGE-based SCD2 job takes 3.5 hours on Snowflake and occasionally creates two “current” rows for a customer. The SLA is 1 hour.
Answer:
“The double-current rows suggest the MERGE either ran on a batch with duplicate keys or the update and insert weren’t atomic. And 3.5 hours suggests we’re scanning all 500 M rows. I’d restructure it. First, dedupe the 2 M changes to one row per customer by source sequence, and compute a row_hash over the tracked columns. Second, join only against current rows. I’d cluster dim_customer by (is_current, customer_id), so the 80 M current rows prune well, or maintain a separate dim_customer_current table. Then, in one transaction, I’d expire changed current rows and insert new versions with valid_from = change_ts. Unchanged hashes are skipped, which is usually 30–50% of CDC rows. Tests assert exactly one current row per customer and no overlapping ranges. This pattern typically drops the runtime to 15–30 minutes. For out-of-order changes I’d use the source sequence as valid_from and, if a late change predates the current version, route it to a correction process rather than complicate the daily path.”
Approach:
- Diagnose the slowness: the Query Profile probably shows a full scan of 500 M rows for the MERGE join, and change detection comparing every column.
- Restrict the work:
- Join the changes only to current rows (
is_current = TRUE), clustered byis_current, customer_id, or kept in a separate current table. - Pre-compute a hash diff (
row_hash) of the tracked attributes, so you compare one column.
- Join the changes only to current rows (
- Dedupe the feed: latest change per customer per batch, ordered by source sequence.
- Atomic two-step in one transaction:
- UPDATE the current rows to set
valid_toandis_current = FALSEwhere the hash differs. - INSERT the new versions.
- Or use a single MERGE with a “union of changes” staging trick.
- UPDATE the current rows to set
- Invariants: test one current row per key, no overlapping intervals, and
valid_from < valid_to. - Late changes: if an older change arrives, decide whether to insert it into history by splitting intervals (complex), or treat it as a correction (simpler, documented).
- Consider tooling: dbt snapshots (state-compare based), Lakeflow AUTO CDC (sequence-aware), or a dynamic-table approach.
Learn more: Slowly Changing Dimensions: Types 0 to 6
44. Fulfil a GDPR deletion request across lake, warehouse and backups (See also Q85)
Scenario:
A customer invokes the right to erasure. Their data exists in: raw JSON files in S3 (7 years), Delta bronze, silver and gold tables, Snowflake marts, Kafka topics (7-day retention), ML feature tables, BI extracts, and nightly backups. The legal deadline is 30 days. You get about 200 such requests per month.
Answer:
“I’d treat this as a repeatable workflow, not a one-off, since we get 200 a month. Step one is resolving the person’s identifiers through our identity table. Then our PII-tagged catalog and lineage give the list of tables holding those identifiers. An orchestrated job runs deletes per system: Delta tables with DELETE, then REORG PURGE and a scheduled VACUUM, so files are physically removed after 7 days, and Snowflake DELETEs, with our documented policy that Time Travel and Fail-safe copies age out within 97 days. Raw S3 JSON is the hardest. Going forward I’d stop storing raw PII there: pseudonymise at ingestion, and keep the PII in an encrypted vault keyed per customer, so erasure means deleting the vault row and key (crypto-shredding). For the backlog of raw files, a monthly rewrite job filters out the subjects. Backups age out on 35-day retention, and the suppression list is re-applied on any restore. Every step logs evidence for the DPO.”
Trade-offs:
| Approach | Pros | Cons |
|---|---|---|
| Physical deletes everywhere | Clear compliance | Expensive rewrites of immutable data |
| Pseudonymisation + vault | Most systems hold no direct PII | Requires upfront design; re-identification controls |
| Crypto-shredding | Fast erasure, even in backups | Key management complexity |
| Anonymised aggregates retained | Keeps analytics | Must ensure true anonymisation (k-anonymity concerns) |
Learn more: Protecting PII in Data Pipelines: Masking, Hashing, Tokenisation and Encryption
45. Design a data platform from scratch for a growing startup
Scenario:
A Series B fintech startup (300 employees, growing fast) has a Postgres production database, Stripe, HubSpot, Segment events (~20 M/day), and Google Sheets. There’s no data team yet beyond you and one analyst. They need investor metrics, product analytics, finance reporting, and SOC 2 readiness within 6 months. The data budget is about $15k/month.
Answer:
“With two people and six months, I’d buy rather than build. Fivetran for Stripe, HubSpot and Postgres via log-based CDC from a read replica, and Segment’s native warehouse destination for events. Snowflake as the warehouse, since we’re on AWS and it needs little ops. dbt on the dbt platform for transformations, CI and scheduling, so we don’t operate Airflow. One BI tool, with KPI definitions in dbt’s semantic layer, so investor metrics like ARR and net revenue retention mean one thing. From day one: SSO, roles per function, PII tagged and masked, prod and dev databases, Terraform for warehouse objects, and secrets in AWS Secrets Manager. That covers much of what SOC 2 auditors look for. Month 1 delivers the finance and investor dashboard, the most valuable thing. Months 2 and 3 cover product funnels. By month 6, tests on every model, freshness alerts, and documentation. Estimated cost is about $6–9k/month at current volumes, well within budget. I’d revisit streaming only when a real-time use case such as fraud scoring appears.”
Trade-offs:
| Decision | Option A | Option B | Rationale |
|---|---|---|---|
| Ingestion | Managed ELT | Custom scripts | Managed saves months for small team; cost per row grows later |
| Warehouse | Snowflake/BigQuery | Lakehouse (Databricks) | SQL-first team → warehouse; lakehouse if ML-heavy early |
| Orchestration | dbt platform jobs | Self-hosted Airflow | Low ops vs flexibility |
| Streaming | Later | Now | No current real-time requirement |
46. Multiple jobs writing to the same table cause conflicts
Scenario:
Three jobs write to silver.customer_profile (Delta, 300 M rows): an hourly CRM MERGE, a streaming job updating last_seen_at, and a nightly GDPR delete job. Since adding the streaming job, the hourly MERGE fails 3–5 times a day with ConcurrentAppendException, and the GDPR job sometimes fails too.
Answer:
“Delta uses optimistic concurrency. The streaming job is constantly rewriting files across the whole table to update last_seen_at, so the hourly MERGE almost always finds that files it read have changed. The cleanest fix is to stop having three writers on one hot table. I’d move last_seen_at into a narrow customer_activity table owned only by the streaming job, and expose a customer_profile_v view, or a gold table that joins them. The CRM MERGE then only conflicts with the GDPR job, and I’d schedule GDPR deletes right after the hourly MERGE in the same Lakeflow job, so they run sequentially. As extra protection, I’d enable deletion vectors and liquid clustering on customer_id, which gives row-level conflict detection, and add a retry with backoff around the MERGE for rare conflicts. The MERGE is idempotent, so retries are safe. Since the change, the conflicts went to zero.”
Approach:
- Understand the conflict: each writer reads a snapshot and rewrites files. If two transactions touch the same files, the later commit fails (see Optimistic concurrency control and write conflicts in Delta).
- Reduce overlap:
- Split responsibilities: move frequently updated columns (
last_seen_at) to a separate table (customer_activity), joined in a view or gold model. Different tables, no conflicts. - Partitioning or clustering so writers touch disjoint files, with explicit predicates in the MERGE conditions.
- Row-level concurrency (Databricks, with deletion vectors and liquid clustering), so updates to different rows in the same files don’t conflict.
- Split responsibilities: move frequently updated columns (
- Coordinate writers: schedule the GDPR deletes in a window when the hourly MERGE isn’t running, or run them through the same orchestrated job.
- Retry with backoff for the remaining transient conflicts. The jobs must be idempotent.
- Streaming writer frequency: batch
last_seen_atupdates every 15 minutes instead of continuously, if acceptable.
Learn more: Delta Lake: Transactions, Schema Evolution and Time Travel
47. Build a data quality framework for 200 tables
Scenario:
A company has 200 critical tables across Snowflake and Databricks, fed by dbt and Spark pipelines. Quality issues are found by business users 2–3 times a week. Leadership asks you to design a data quality framework within a quarter, with a team of 3.
Answer:
“With three people, I’d go for coverage on what matters most. Week 1–2: work with domain leads to tier the 200 tables. Around 30 are Tier 1, feeding exec dashboards and regulatory reports, each with a named owner. Then I’d auto-generate baseline checks for all 200 from metadata: primary-key uniqueness and not_null, freshness against each table’s SLA, row-count anomaly detection, and schema-change alerts. In dbt these become tests run in dbt build, so failures block downstream models. For Spark pipelines, they become expectations. For Tier 1, we’d add business rules with the owners, such as reconciliation of revenue against the billing system, valid currency codes, and no negative quantities. Alerts route by tier: Tier 1 to the on-call pager with a runbook, the rest to team channels with daily digests. The success metric is the share of incidents caught by checks before users, aiming to go from about 0% to 80% in a quarter, plus mean time to detect. A quality dashboard shows status per table and per owner.”
Approach:
- Tier the tables: Tier 1 (exec and regulatory, about 30), Tier 2 (operational, about 70), Tier 3 (exploratory). Assign owners.
- Define the dimensions: freshness, volume, schema, validity, uniqueness, referential integrity, reconciliation.
- Baseline checks for every table, generated from metadata:
- PK unique and not_null, freshness, row-count anomaly, schema change detection.
- Business rules for Tier 1 and 2: range, accepted-value and reconciliation tests, written with the owners.
- Where the checks run:
- dbt tests (in
build, as circuit breakers). - Expectations in Spark or Lakeflow pipelines.
- Warehouse-native monitors (Snowflake DMFs, Databricks data quality monitoring).
- Observability tooling (elementary, Monte Carlo and similar) for anomalies.
- dbt tests (in
- Alerting and incidents: route alerts to the owners by tier (Tier 1 pages, Tier 2 goes to a Slack channel), with a runbook and severity levels.
- Prevent at the source: data contracts for Tier 1 sources (see What are data contracts, and how do you enforce them?).
- Measure: incidents found by users vs by checks, time to detect, time to resolve, and a quality score per table on a dashboard.
Learn more: Data Quality: Checks, Contracts and Failure Handling
48. Merge customer data after an acquisition (entity resolution)
Scenario:
Your company acquired a competitor. You have 12 M customers, and they have 5 M. An estimated 15–25% overlap, but there are no shared IDs. Fields include name, email (sometimes missing), phone, address and date of birth (partial). The business wants a unified customer view for marketing and a single count of customers within 3 months.
Answer:
“I’d build a matching pipeline rather than a one-off join. First, standardise contact data: normalised emails, E.164 phones, parsed addresses. Then blocking keys (email, phone, postcode plus the first three letters of the surname) generate candidate pairs, maybe tens of millions instead of 60 trillion. Exact email or phone-plus-name matches are auto-merged. For the rest I’d compute similarity features and use a probabilistic model, using a library like Splink on Spark or the warehouse, calibrated on a few thousand pairs labelled by the CRM team. Scores above 0.95 merge automatically, 0.8–0.95 go to a review queue, and below that stay separate. Connected components form customer clusters, and I’d cap and inspect any cluster larger than about 10 records. Survivorship rules pick the golden values, and a cross-reference table maps the master ID to both systems’ IDs, so marketing gets one customer count. New customers are matched incrementally every day. I’d report precision and recall, with marketing agreeing that over-merging is worse than under-merging for email campaigns.”
Trade-offs:
| Approach | Pros | Cons |
|---|---|---|
| Deterministic only | Simple, explainable | Misses fuzzy matches |
| Probabilistic/ML | Higher recall | Needs labels, tuning, explainability |
| Commercial MDM/ER tool | Mature workflows | Cost, integration |
| Manual review at scale | Accurate | Impossible for millions |
Learn more: Delta Lake MERGE, Change Data Feed and Streaming
49. Build point-in-time-correct training data for an ML model
Scenario:
Data scientists are training a churn model on 3 years of history: 5 M customers, monthly labels (churned within the next 30 days). Features include support tickets, payments, plan changes and usage aggregates. The offline model shows 0.92 AUC, but production performance is 0.71. You suspect data leakage.
Answer:
“A gap from 0.92 to 0.71 usually means leakage. Looking at the training query, features were computed from current tables: ‘tickets in the last 90 days’ used today’s data for every historical row, and account_status already reflected cancellation. I’d rebuild the training set around explicit observation points: for each customer and month-end, as_of_ts, with the label being churn in the following 30 days. Every feature is computed from data available before as_of_ts. Event aggregates use event_ts < as_of_ts, adjusted for ingestion delays. Attributes like plan come from the SCD2 version valid at that time. Implementing this as feature tables with timestamps in the feature store gives point-in-time joins for training and the same definitions online. I’d also switch to a temporal split, training on years 1–2 and testing on year 3. That should bring offline AUC to a realistic level that matches production.”
Approach:
- Find the leakage: features computed using data after the prediction time. For example, “total tickets” computed today and joined to an observation from last year, or a status column that already reflects the churn.
- Define observation points:
(customer_id, as_of_ts)for each training example, with the label computed strictly afteras_of_ts. - Make features time-aware:
- Event features aggregated only from events with
event_ts < as_of_ts(windows such as the last 30 or 90 days). - Dimension attributes from SCD2 versions valid at
as_of_ts(see How do you design and load an SCD Type 2 dimension?). - Account for data availability delays: if payments land a day late, use
< as_of_ts − 1 day.
- Event features aggregated only from events with
- As-of joins: a point-in-time join from observations to feature tables keyed by entity and timestamp. Feature stores (Databricks Feature Engineering, SageMaker, Feast, Snowflake Feature Store) offer this.
- Consistency: compute features with the same code for training and serving, whether a feature store or shared definitions.
- Validate: compare feature distributions in training vs production, and do a temporal train/test split (train on older periods, test on newer).
50. Add multi-region disaster recovery to the platform
Scenario:
A payments analytics platform runs in one cloud region: Snowflake, S3 lake, Airflow, and Kafka. Regulators require recovery from a full regional outage with RPO ≤ 1 hour and RTO ≤ 4 hours for tier-1 reporting. The budget is limited, so you can’t simply double everything.
Answer:
“I’d scope DR to tier-1 reporting rather than the whole platform. On Snowflake, I’d put the tier-1 databases in a failover group replicated to a secondary account in another region every 30 minutes. That meets the 1-hour RPO, and client redirect lets BI tools reconnect with a connection URL switch. Warehouses in the secondary account stay suspended, so we pay mainly for replication and storage. The raw S3 prefixes feeding tier-1 get cross-region replication. Airflow and dbt are code in Git with Terraform, so standing up orchestration in the DR region takes under an hour, and secrets are replicated in the secrets manager. Kafka sources are replayable from the upstream databases via CDC, so instead of a hot standby Kafka cluster, we’d restart CDC into a DR cluster from the last replicated offsets or a fresh snapshot. A runbook defines who declares a disaster, the steps, and validation queries. We’d run a DR drill every quarter, and the last one measured RTO at 2.5 hours.”
Trade-offs:
| Approach | RPO/RTO | Cost |
|---|---|---|
| Backup & restore only | Hours–days | Low |
| Pilot light (replicated data, cold compute) | ≤1h / hours | Medium |
| Warm standby (some compute running) | Minutes / <1h | Higher |
| Active-active | Near zero | Highest, complex consistency |

