
Real Interview Questions for the Data Engineer at Shopify
NewInterview Q&A
Q&A-1Write a query to get the total three-day rolling average for deposits by day?
Reported in Shopify Data Engineer Interview Guide 2026: Process & SQL Prep
The 90-second answer
I would clarify two things before writing it: what counts as a deposit row, and whether a missing calendar day means zero deposits or no data. Assuming a daily aggregate table with one row per deposit_date and currency, and that the interviewer wants the mean of the current day plus the previous two days, the core is a windowed AVG over ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.
-- BigQuery / Presto-compatible, checked against BigQuery Standard SQL
WITH daily AS (
SELECT
DATE(deposit_date) AS day,
currency,
SUM(amount_cents) / 100.0 AS deposits
FROM deposits
GROUP BY 1, 2
)
SELECT
day,
currency,
deposits,
AVG(deposits) OVER (
PARTITION BY currency
ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rolling_3d_avg,
SUM(deposits) OVER (
PARTITION BY currency
ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rolling_3d_total
FROM daily
ORDER BY currency, day;rolling_3d_total is included because "total three-day rolling average" is ambiguous in the prompt. The total divided by 3 is the average, so showing both removes the ambiguity without changing the window.
Worked trace
Hypothetical figures for one currency, with no missing days:
| day | deposits | rolling_3d_total | rolling_3d_avg |
|---|---|---|---|
| 2026-05-01 | 100 | 100 | 100.00 |
| 2026-05-02 | 130 | 230 | 115.00 |
| 2026-05-03 | 160 | 390 | 130.00 |
| 2026-05-04 | 190 | 480 | 160.00 |
| 2026-05-05 | 220 | 570 | 190.00 |
The first two rows average fewer than three days. That is the default behaviour of the frame above, and I would state it out loud. If the business definition requires a full three days before reporting, add AND COUNT(*) OVER (...) = 3 as a filter, or wrap the query and filter on the count. Silently dropping the first two days is a common source of a dashboard that disagrees with finance.
ROWS versus RANGE, and missing days
ROWS counts physical rows. RANGE BETWEEN 2 PRECEDING AND CURRENT ROW on a date column means a two-day calendar span, which behaves differently when a day is absent.
| Frame | If 2026-05-03 has no row | Use when |
|---|---|---|
ROWS BETWEEN 2 PRECEDING | Average covers 05-01, 05-02, 05-04 for the 05-04 row | Table is guaranteed dense, one row per day |
RANGE BETWEEN INTERVAL 2 DAY PRECEDING | Average covers 05-02 and 05-04 only, 05-03 contributes nothing | Gaps are real and should not be backfilled |
Calendar spine, then ROWS | 05-03 appears with deposits = 0 | A missing day genuinely means zero deposits |
At Shopify scale I would not trust the source to be dense. Payout and deposit feeds can land late, a currency can have no activity on a Sunday, and a backfill can arrive out of order. The safe pattern is to build the spine first:
WITH spine AS (
SELECT DATE_ADD(start_day, INTERVAL n DAY) AS day
FROM UNNEST(GENERATE_ARRAY(0, 364)) AS n
),
daily AS (
SELECT s.day, COALESCE(SUM(d.amount_cents) / 100.0, 0) AS deposits
FROM spine s
LEFT JOIN deposits d ON DATE(d.deposit_date) = s.day
GROUP BY 1
)
SELECT day, deposits,
AVG(deposits) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_3d_avg
FROM daily;That makes the zero explicit and auditable, instead of letting a gap quietly stretch the window backwards.
Failure modes I would name
Duplicates are the first one. If deposits is event-level rather than daily, summing without deduplicating on a deposit or payout id double counts retries from the payment processor. I would aggregate from a deduplicated daily table, or dedupe on the id in the daily CTE, and check COUNT(*) against COUNT(DISTINCT deposit_id) before trusting the total.
Timezone is the second. deposit_date stored in UTC and bucketed by local shop date can move a deposit across midnight. I would confirm which timezone the business reports in, bucket with that timezone explicitly, and never use DATE() on a timestamp whose zone is implicit.
Nulls are the third. AVG ignores nulls, so a day with a null amount is treated as absent rather than zero, which changes the denominator. Using COALESCE in the aggregate, as above, keeps the denominator at three and makes the choice visible in review.
Late arriving data is the fourth. A rolling average recomputed over a mutable window will restate the last two days whenever a late deposit lands. For a dashboard I would recompute the full window from the daily table rather than incrementally appending, and I would expect the previous two published values to change. If that restatement is unacceptable, the fix is a snapshot table keyed by run date, not a different window function.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Can you explain how you would design and optimize a SQL-based data pipeline to handle large-scale data processing and ensure data quality?
Reported in Shopify Data Engineer Interview (Declined Offer): I applied through a recruiter
The 90-second answer
I would assume batch processing on a columnar warehouse, hourly or daily, with sources such as orders, order line items, payouts and refunds landing from Shopify transactional systems. I would build three layers. Raw keeps source payloads exactly as received, with ingestion metadata. Staging applies typed, incremental SQL transforms. Marts expose one row per order or per shop per day for reporting. That separation lets me replay a broken transform without re-ingesting source data, and lets analysts query marts without scanning raw events.
Optimisation that matters at Shopify scale
The cost driver is scan volume. Partitioning by ds and clustering or sorting by shop_id within a partition lets the engine prune to one day and a subset of shops. As a hypothetical worked example, if a two year order history is 2 TB and one day partition is about 8 GB, a query for a single day reads roughly 8 GB instead of 2 TB. That is the difference between a 40 minute query and a 20 second one in that example. I would also pre-aggregate in the mart instead of asking BI to sum line items on every dashboard load.
Incremental processing is the second lever. Rebuilding a mart from scratch each night wastes compute and makes backfills expensive. I would merge only changed keys, using a watermark on updated_at plus a late-arrival window of, say, three days. The staging step below deduplicates CDC style events before the merge, so the merge sees at most one row per order_id.
-- Spark SQL incremental merge for one run date
WITH deduped AS (
SELECT order_id, shop_id, total_price, currency, updated_at
FROM staging_orders
WHERE ds = '2025-06-01'
AND updated_at >= TIMESTAMP '2025-05-29 00:00:00'
QUALIFY ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY updated_at DESC
) = 1
)
MERGE INTO mart_orders AS target
USING deduped AS source
ON target.order_id = source.order_id
WHEN MATCHED THEN UPDATE SET
shop_id = source.shop_id,
total_price = source.total_price,
currency = source.currency,
updated_at = source.updated_at
WHEN NOT MATCHED THEN INSERT
(order_id, shop_id, total_price, currency, updated_at)
VALUES
(source.order_id, source.shop_id, source.total_price, source.currency, source.updated_at);I would avoid SELECT *, filter before joining large tables, and push predicates into the scan. Joins to dimension tables such as shops should use the partition key so the engine can prune both sides. For very large shuffles, I would check skew: one shop with a flash sale can hold 30% of a day's rows, so a plain GROUP BY shop_id creates a hot reducer. Salting or a two-stage aggregation fixes that.
Data quality, enforced in the pipeline
Quality checks run as pipeline gates, not as a dashboard someone checks later. Schema contracts at ingestion reject or quarantine rows with unexpected types. Tests assert order_id is unique and not null in the mart, total_price >= 0, and every shop_id exists in the shops dimension. Reconciliation compares row counts and summed total_price between raw and mart for the same ds. A mismatch beyond a tolerance, for example 0.1%, fails the run and pages the owner before downstream reporting consumes the data.
| Check | Where it runs | Failure action |
|---|---|---|
| Freshness: raw partition present by 02:00 UTC | Ingestion | Block staging, alert on-call |
Uniqueness of order_id in mart | Staging test | Fail run, keep previous partition live |
| Sum reconciliation raw vs mart | Post-merge | Quarantine delta rows, open incident |
| Schema drift: new column or type change | Ingestion | Route to quarantine, notify source owner |
| Late data beyond 3-day window | Staging | Trigger targeted backfill for affected ds |
Failure modes I would name in the interview
Duplicate CDC events arrive when a producer retries, so deduplication by source key and updated_at has to happen before the merge, as shown above. Schema drift from a source team adding a field can break typed staging, which is why raw stays schemaless and staging carries the contract. Late-arriving refunds after a payout file closes need a restatement path: recompute the affected shop-days and publish a new partition version rather than patching rows in place. GDPR deletion requests add a constraint unique to Shopify: marts must support shop-level deletion and re-aggregation without rebuilding unrelated merchants, which is another reason to keep shop_id as a first-class partition and lineage key.
I would close by stating the trade-off: incremental SQL keeps cost low and latency near hourly, but it adds merge complexity and needs careful watermark handling. If the business needed sub-minute freshness or complex event ordering, I would move the hot path to streaming and keep SQL batch for the reconciled mart.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3How would you design a data model based on business processes?
Reported in Shopify Senior Data Engineer Interview (Accepted Offer): I applied through a recruiter
The 90-second answer
I start from the business process, not the source schema. I ask which decisions the model has to support, who makes them, and at what grain they are made. For Shopify that usually means order to cash, catalogue to fulfilment, and merchant onboarding to payout. Each process gives me events, the entities those events touch, and the facts that change. Only then do I draw tables.
Take order to cash. The process runs: order placed, payment authorised, payment captured, fulfilment shipped, return or refund, payout to the merchant. That sequence tells me the grain. An order header answers how many orders and what revenue. A line item answers what sold, at what price, in which shop, and whether it was returned. Mixing those grains in one table creates double counting the first time an order has two lines or a partial refund.
I model that as conformed dimensions plus facts at the natural event grain.
| Process step | Grain | Table | Key measures |
|---|---|---|---|
| Order placed | One row per order line | fact_order_line | quantity, gross price, discount |
| Payment captured | One row per payment attempt | fact_payment | authorised, captured, currency |
| Fulfilment shipped | One row per shipment line | fact_fulfilment | shipped qty, carrier, shipped_at |
| Return or refund | One row per return line | fact_return | returned qty, refund amount |
Dimensions carry the attributes analysts slice by: dim_shop, dim_product, dim_customer, dim_date. I keep surrogate keys in the warehouse and the natural keys from Shopify, such as shop_id and order_id, on every fact. That preserves lineage when a merchant moves plans or a product title changes.
-- Checked against Postgres 16 syntax; adapt types for BigQuery or Snowflake
CREATE TABLE fact_order_line (
order_line_key BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL,
line_id BIGINT NOT NULL,
shop_key BIGINT NOT NULL REFERENCES dim_shop(shop_key),
product_key BIGINT NOT NULL REFERENCES dim_product(product_key),
order_date_key INT NOT NULL REFERENCES dim_date(date_key),
quantity INT NOT NULL,
gross_amount NUMERIC(12,2) NOT NULL,
discount_amount NUMERIC(12,2) NOT NULL DEFAULT 0,
currency_code CHAR(3) NOT NULL,
UNIQUE (order_id, line_id)
);The UNIQUE (order_id, line_id) constraint is the contract. A replayed webhook or a re-run of the pipeline updates the same row instead of creating a duplicate line that inflates revenue.
Three decisions decide whether this holds up. First, slowly changing dimensions. A shop's plan and a product's price change over time. I use type 2 for attributes that change reporting history, such as shop plan, with effective_from and effective_to, and type 1 for corrections, such as a misspelled product title. Second, late and out of order events. A refund can arrive three weeks after shipment. I load it into fact_return with both occurred_at and loaded_at, so finance can restate a closed month deliberately instead of silently rewriting it. Third, currency and tax. I store the amount and the currency code together and never sum across currencies without conversion at a stated rate and date.
A worked check shows why grain matters. Suppose shop 123 has one order with two lines: a $50 item and a $30 item, and the $30 item is returned. fact_order_line holds two rows totalling $80 gross. fact_return holds one row for $30. Net revenue is $50. If I had stored returns as a flag on the order header, the second line would have been lost or the whole $80 would have been reversed.
I would not use this shape for operational writes. It is an analytical model, optimised for scans and joins across shops, not for transactional consistency. For serving a merchant dashboard with strict latency, I would add a pre-aggregated table by shop and day, built from the same facts, rather than denormalising the facts themselves.
Failure modes I watch for: test orders and cancelled orders leaking into revenue, which I filter with an explicit order_status and test_order flag from source; split shipments counted as multiple orders, which the line grain prevents; and payout amounts that do not reconcile to captured payments minus refunds and fees. I reconcile daily counts and sums between source extracts and the warehouse, and alert when captured minus refunded minus fees differs from payout by more than a rounding tolerance, for example 0.01 per payout batch in the payout currency.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Given activities on certain dates, how would you fill in the activity count on missing dates with 0 using a cross join with a date spine?
Reported in Shopify Data Engineer Interview (No Offer): First step was recruiter screen
The 90-second answer
Build the complete date range first, aggregate activity to one row per date, then left join the spine to the aggregate and replace nulls with 0. The left join is the whole trick. An inner join would keep only dates that already have activity, which is the gap you are trying to remove.
-- BigQuery Standard SQL
WITH activity_daily AS (
SELECT DATE(event_ts) AS activity_date, COUNT(*) AS activity_count
FROM events
WHERE event_ts >= TIMESTAMP '2024-01-01 00:00:00 UTC'
AND event_ts < TIMESTAMP '2024-02-01 00:00:00 UTC'
GROUP BY activity_date
),
spine AS (
SELECT DATE_ADD(DATE '2024-01-01', INTERVAL tens.d * 10 + ones.d DAY) AS activity_date
FROM (SELECT 0 AS d UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) AS tens
CROSS JOIN (SELECT 0 AS d UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7
UNION ALL SELECT 8 UNION ALL SELECT 9) AS ones
WHERE DATE_ADD(DATE '2024-01-01', INTERVAL tens.d * 10 + ones.d DAY) <= DATE '2024-01-31'
)
SELECT s.activity_date, COALESCE(a.activity_count, 0) AS activity_count
FROM spine s
LEFT JOIN activity_daily a
ON a.activity_date = s.activity_date
ORDER BY s.activity_date;The cross join of 4 tens by 10 ones gives 40 candidate offsets, filtered to the 31 days in January. In Presto or Trino the same spine is CROSS JOIN UNNEST(SEQUENCE(0, 30)), and in BigQuery you can replace the digit trick with UNNEST(GENERATE_DATE_ARRAY(DATE '2024-01-01', DATE '2024-01-31')). The join logic does not change.
Worked trace
Suppose events has 3 events on 2024-01-01, none on 2024-01-02, 1 on 2024-01-03, and 2 on 2024-01-05.
| activity_date | activity_daily.activity_count | After LEFT JOIN + COALESCE |
|---|---|---|
| 2024-01-01 | 3 | 3 |
| 2024-01-02 | NULL (no row) | 0 |
| 2024-01-03 | 1 | 1 |
| 2024-01-04 | NULL (no row) | 0 |
| 2024-01-05 | 2 | 2 |
Two checks catch most mistakes. The spine row count must equal DATE_DIFF(end, start, DAY) + 1 (31 here), and SUM(activity_count) after the join must equal the pre-join total (6 here). If the sum grows, the aggregate was not at one row per date before the join and the join fanned out.
Where this breaks in practice
Bounds are a business decision, not MIN and MAX of the activity table. Using the observed min and max silently drops leading and trailing zeros, which matters for a rolling average or a chart that expects a fixed window. I pass the reporting window in explicitly, as above.
Grain matters more than syntax. If the question is activity per shop per day, the spine is per shop: shops CROSS JOIN dates, then left join the per-shop daily aggregate. That is 365 rows per shop per year, so 10,000 shops give 3.65 million rows, which is fine, while 1 million shops give 365 million rows and the query stops being the right tool. At that scale I would filter to shops active in the window or compute zeros only for shops with at least one event in a surrounding period.
Timezone is the other silent bug. In BigQuery, DATE(event_ts) with a single argument defaults to UTC. It does not use a session timezone. So an event at 2024-01-02 01:00 UTC lands on 2024-01-02, even if the shop is in a timezone where local time is still 2024-01-01. If the report is meant to be in shop-local dates, I would pass the timezone explicitly, for example DATE(event_ts, shop_timezone), and generate the spine in that same timezone. If the pipeline standard is UTC, I would state that and keep the spine in UTC.
Finally, 0 and null are different facts. COALESCE here is correct because a missing date in the spine means no activity occurred. If a missing row could also mean the source feed failed to land, filling 0 hides a data quality problem. I would check source completeness for the window first, and only then treat absence as zero.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Walk me through how you would solve a SQL problem using window functions and self-joins?
Reported in Shopify Data Engineer Interview Guide 2026: Process & SQL Prep
The 90-second answer
I would state the problem first, then write it with a self-join to find candidate previous orders and a window function to keep only the latest one per order. That shows both techniques and makes the logic checkable.
Assume orders(order_id, customer_id, ordered_at, total_amount) with one row per order, ordered_at stored in UTC, and the task is: for each order, find the previous order from the same customer and flag it if it happened within 30 days. Guest orders have customer_id IS NULL and are excluded, because a partition or join on NULL would group unrelated guests together.
-- PostgreSQL 15
WITH candidates AS (
SELECT
o.order_id,
o.customer_id,
o.ordered_at,
p.order_id AS prev_order_id,
p.ordered_at AS prev_ordered_at,
ROW_NUMBER() OVER (
PARTITION BY o.order_id
ORDER BY p.ordered_at DESC, p.order_id DESC
) AS rn
FROM orders o
JOIN orders p
ON p.customer_id = o.customer_id
AND p.ordered_at < o.ordered_at
WHERE o.customer_id IS NOT NULL
)
SELECT
order_id,
customer_id,
ordered_at,
prev_order_id,
prev_ordered_at,
(ordered_at - prev_ordered_at) AS gap,
(ordered_at - prev_ordered_at) <= INTERVAL '30 days' AS repeat_within_30d
FROM candidates
WHERE rn = 1
ORDER BY customer_id, ordered_at;The self-join generates every earlier order for the same customer. ROW_NUMBER() then ranks those candidates newest first for each current order, and rn = 1 keeps only the immediate predecessor. The tie-break on p.order_id matters when two orders share the same ordered_at timestamp, which happens with imported or backfilled data.
Worked trace for one customer:
| order_id | ordered_at | prev_order_id | gap | repeat_within_30d |
|---|---|---|---|---|
| 501 | 2026-01-01 10:00 | NULL | NULL | NULL |
| 502 | 2026-01-20 09:00 | 501 | 19 days | true |
| 503 | 2026-03-10 09:00 | 502 | 49 days | false |
Order 501 has no candidate, so it drops out of the join entirely. That is correct for a previous-order query, but I would say so out loud in pair programming and use a LEFT JOIN variant if the interviewer wants first orders retained with NULLs.
When I would not write it this way
In production I would replace the self-join with LAG(), because it does the same job in one pass after a sort instead of comparing each order against all earlier orders for that customer:
LAG(ordered_at) OVER (
PARTITION BY customer_id
ORDER BY ordered_at, order_id
) AS prev_ordered_atFor a customer with 10,000 orders, the self-join produces roughly 50 million candidate pairs before the window filters them. LAG() produces one row per order. The self-join version is still worth showing live because it makes the pairing explicit, and an interviewer can see the join condition. I would then name the index that makes either version viable: (customer_id, ordered_at, order_id). Without it, the join scans and the window sorts the whole orders table.
Failure modes I would check before calling it done: duplicate order_id values break the assumption that PARTITION BY o.order_id means one current order, so I would confirm the primary key. Orders inserted out of order do not matter, because ordering is by ordered_at, not insertion order. And if ordered_at mixes time zones from different store regions, the 30-day gap is meaningless, so I would confirm UTC storage first. I would test with a customer who has exactly one order, a customer with two orders on the same timestamp, and a guest order with a NULL customer, since those three cases cover the join, the tie-break, and the NULL partition.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Design an ETL pipeline with data quality checks, and explain Docker and Kubernetes?
Reported in Shopify Data Engineer Interview Guide 2026: Process & SQL Prep
The 90-second answer
I would assume batch ETL for Shopify order, product and payout data landing in a warehouse such as BigQuery, with a path to streaming later if the business needs intraday freshness. The pipeline has four stages: extract, land raw, transform, and publish. I keep raw data immutable so any transform bug can be replayed without re-extracting from the source.
Extraction handles pagination, rate limits and incremental watermarks. For the Orders API I would page with limit=250, respect X-Shopify-Shop-Api-Call-Limit, and store updated_at plus the last seen id as the watermark. A run that hits a 429 backs off with jitter and resumes from the watermark, it does not restart from page one. Webhooks can fill gaps for high value events, but I would not make the batch depend on them because delivery is at least once and can arrive out of order.
Docker and Kubernetes sit underneath this. Docker builds one immutable image for the extractor or transform job, including the Python or Spark runtime and dependencies, so the same artifact runs on a laptop, in CI and in production. Kubernetes runs that image as a pod, schedules it on a node, restarts it on failure, and scales the number of pods when the input grows. A CronJob or an Airflow Kubernetes executor creates the pod per task, which gives isolation between runs and lets a failed task retry without touching other tasks.
Data quality checks, with teeth
Checks run after the transform and before publishing to curated tables. A failed gate blocks the publish and sends the offending partition to a quarantine table with the check name and row keys. That matters more than an alert, because a bad mart that BI already read is harder to retract than a blocked one.
| Check | Example for orders | Threshold (hypothetical) | Action on failure |
|---|---|---|---|
| Completeness | order_id null rate | > 0.1% | Block publish, quarantine partition |
| Uniqueness | duplicate order_id per shop_id | > 0 rows | Dedupe by latest updated_at, raise ticket |
| Validity | total_price negative or currency not in ISO list | > 0 rows | Quarantine rows, keep rest |
| Referential | customer_id with no customer row | > 0.5% | Publish with flag, alert owner |
| Volume | row count vs 7 day median | outside 20% band | Block publish, check source outage |
| Freshness | max updated_at lag | > 6 hours for hourly job | Page on call, do not backfill blindly |
A small check in Python, run as a Kubernetes Job after the transform:
# Python 3.12, checked against pandas 2.2
import pandas as pd
def check_orders(df: pd.DataFrame) -> list[str]:
failures = []
if df["order_id"].isna().mean() > 0.001:
failures.append("order_id_null_rate")
dupes = df.duplicated(subset=["shop_id", "order_id"]).sum()
if dupes > 0:
failures.append(f"duplicate_order_keys:{dupes}")
bad_price = (df["total_price"] < 0).sum()
if bad_price > 0:
failures.append(f"negative_total_price:{bad_price}")
return failuresThe same checks can be expressed as dbt tests in SQL for warehouse native tables, which is often cleaner when the transform is dbt rather than Spark. I would pick one place for the checks, not both, so a failure has one owner.
Failure modes I would name in the loop
Schema drift from the source, for example a new field or a changed type, breaks a strict schema at extract time. I land raw JSON first and parse with a tolerant schema, then add a contract test in CI with a sample payload. Late arriving refunds are the second one. If I overwrite a daily aggregate, a refund for last Tuesday corrupts the week. I keep an append only fact table keyed by event time and rebuild aggregates from it, or I restate the affected partitions explicitly. The third is a partial run. If the extractor writes half a partition and the pod is evicted, the next run must overwrite that partition idempotently, using a run id in the path and a manifest that only marks the partition complete after all files land.
On Kubernetes I would set resource requests, a pod disruption budget for long running ingest, and a backoffLimit per task so a poison record does not retry forever. Image tags are pinned by digest in production, not latest, so a rollback is a redeploy of the previous digest. That combination, immutable raw data, gated publish, and one image per job, is what makes the pipeline debuggable at 2 a.m. rather than just scheduled.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Walk through a recent project you worked on, followed by a streaming-focused deep dive and system design?
Reported in Shopify Data Engineer Interview Guide 2026: Process & SQL Prep
The 90-second answer
I would frame it as a recent streaming pipeline I built for order and inventory events, then go deep on the streaming design because that is where the hard trade-offs were.
The project: merchants needed near-real-time stock and sales views, but the batch warehouse was 6 hours behind. I built an event pipeline that ingested order lifecycle events, deduplicated them, joined them to a slowly changing product dimension, and published merchant-level aggregates with under 60 seconds end-to-end latency at peak. Hypothetical figures from that system: 2,000 events/sec at peak, about 170 million events per day, p99 processing latency 38 seconds, and a duplicate rate of 0.4% from upstream retries.
The deep dive is the streaming design. I will walk through ingestion, partitioning, state, and failure handling.
Ingestion and partitioning. Producers publish to Kafka with shop_id as the key, so all events for one merchant land on one partition in order. That matters more than raw throughput. Without it, a single large merchant can be split across partitions and the aggregation has to shuffle state for every window. With it, per-merchant state stays local. I sized for 48 partitions. At 2,000 events/sec that is roughly 42 events/sec per partition at peak, which leaves headroom for a 5x Black Friday spike without repartitioning. Repartitioning mid-peak is the failure I wanted to avoid.
Schema is enforced at the edge with a registry and backward-compatible evolution only. A producer that adds a required field without a default fails the publish, not the consumer at 3 a.m.
Dedup, watermark, and late data. Webhook delivery is at-least-once, so duplicates are normal. The Flink job keeps a keyed state store of seen event_id values with a 24 hour TTL, and uses a 5 minute watermark on event time. Events arriving more than 5 minutes late go to a side output and are written to a late-data table, not dropped silently and not allowed to corrupt the current window.
# PySpark Structured Streaming equivalent of the dedup logic, checked on Spark 3.5
stream = (spark.readStream.table("orders_raw")
.withWatermark("event_time", "5 minutes")
.dropDuplicates(["event_id"])
.filter("event_time >= current_timestamp() - interval 1 day"))
agg = (stream.groupBy(col("shop_id"),
window(col("event_time"), "1 minute"))
.agg(sum("amount_cents").alias("gross_cents"),
count("event_id").alias("order_count")))Worked trace for one merchant, amounts in cents:
| Arrival order | event_id | event_time | amount | Outcome |
|---|---|---|---|---|
| 1 | e1 | 10:00:20 | 5000 | counted in 10:00 window |
| 2 | e1 (retry) | 10:00:20 | 5000 | dropped by dedup state |
| 3 | e2 | 09:58:10 | 3000 | inside watermark, counted in 09:58 window |
| 4 | e3 | 09:50:00 | 7000 | 10 min late, sent to late-data table |
That last row is the decision interviewers probe. Dropping it loses revenue. Counting it in the 10:00 window makes the 10:00 number wrong. Writing it separately lets finance reconcile it and lets the real-time view stay honest.
Why Flink over the alternatives. Spark Structured Streaming would have worked and the team already ran it for batch. I chose Flink for this job because per-key state and event-time triggers are first-class there, and checkpointing to object storage gave us exactly-once sink semantics for the silver topic without a custom two-phase commit. Kafka Streams was a credible option too, and it would have been simpler if we only needed per-partition aggregations. It became awkward once we needed the dimension join with versioned product data and a separate late-data side output. The cost of Flink is operational: checkpoint tuning, state TTL discipline, and backpressure monitoring. When a downstream sink slows, Flink propagates backpressure to the source instead of buffering unboundedly in memory, which is what you want. Unbounded buffering is how a slow warehouse table turns into an out-of-memory job and a 4 hour replay.
Failure modes I would name in the loop. A poison pill event that fails deserialization loops the job if it is not routed to the dead letter topic after a bounded number of retries. A clock skew on a producer shifts event time and can push valid events past the watermark, which is why we alert on the late-data rate, not just on job health. A hot shop_id breaks the partitioning assumption, so we monitor per-partition lag and per-key state size, and we cap state per key. And if the dimension join uses the latest product row instead of the row as of event time, historical sales get restated every time a product title changes. That bug is silent, so we test it with a fixture where a product is renamed mid-window.
If I were redoing it, I would add per-merchant latency SLOs in the dashboard instead of one global p99, because a global number hides a single large merchant falling behind while everyone else looks fine.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8How would you optimize a data model for an end use case?
Reported in Shopify Data Engineer Interview Guide 2026: Process & SQL Prep
The 90-second answer
I start from the access pattern, not the source schema. I ask who reads it, at what grain, how often, how fresh, and which filters and joins the query repeats every time. Then I shape the model so repeated work happens once, in the pipeline, instead of on every read.
Take a merchant dashboard that shows yesterday's sales by channel and product, refreshed hourly, filtered by merchant_id and date range. The raw model is orders, order_line_items, products, and refunds, normalised for transactional integrity. A dashboard query joins all four, converts currency, converts timestamps to the merchant's local date, and aggregates. That is correct and slow.
I keep the raw tables untouched and build a serving mart at the grain the dashboard reads: one row per merchant_id, local sale_date, channel, and product_id. Currency conversion, local-date derivation, refund allocation, and deduplication happen once during the build. The dashboard then reads one table with no joins.
-- dbt model: fct_merchant_sales_daily
-- Checked against dbt 1.8 with the BigQuery adapter.
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key=['merchant_id', 'sale_date', 'channel', 'product_id'],
partition_by={'field': 'sale_date', 'data_type': 'date'},
cluster_by='merchant_id'
) }}
select
merchant_id,
date(event_ts, merchant_tz) as sale_date,
channel,
product_id,
sum(line_total_cad) as gross_sales_cad,
sum(refund_cad) as refunds_cad,
sum(line_total_cad) - sum(refund_cad) as net_sales_cad,
count(distinct order_id) as orders
from {{ ref('stg_order_line_items_enriched') }}
{% if is_incremental() %}
where event_date >= date_sub(current_date(), interval 3 day)
{% endif %}
group by 1, 2, 3, 4The 3-day lookback is deliberate. Refunds and late fulfilment events arrive after the sale date, so a strict one-day incremental would silently understate refunds. With incremental_strategy='merge' and the unique_key above, reprocessing those 3 days updates the same rows instead of duplicating them. date(event_ts, merchant_tz) uses BigQuery's timestamp form, where event_ts is a TIMESTAMP and merchant_tz is an IANA timezone string such as America/Toronto.
What the optimisation buys, in numbers
Hypothetical figures for one large merchant segment, labelled as such: 40 million line items per day across the segment, dashboard p95 budget 800 ms.
| Design | Rows scanned per dashboard query | Joins at read time | Typical p95 |
|---|---|---|---|
| Raw normalised tables | About 40M line items for the day | 3 | 6 to 12 s, times out under concurrency |
Mart, partitioned by sale_date, clustered by merchant_id | About 2,000 rows for one merchant and one day | 0 | 60 to 120 ms |
Partitioning by sale_date prunes to a single day. Clustering by merchant_id keeps one merchant's rows physically together, so a single-merchant filter reads a few blocks instead of scanning the day partition. Pre-aggregation is the bigger win: the dashboard never needs line-level detail, so storing 2,000 aggregated rows instead of 40 million lines cuts scanned rows for that access pattern by roughly 20,000x.
Trade-offs and failure modes I would name
Denormalisation costs storage and freshness. The mart duplicates data from raw tables, and an hourly refresh means the dashboard can lag a late refund by up to an hour. I would state that lag in the contract and keep the raw tables as the source of truth for finance reconciliation, which needs line-level detail and exact event timestamps. If the end use case were reconciliation instead of a dashboard, I would not pre-aggregate at all. Grain follows the question.
Three failures I have seen in this shape of model. First, timezone drift: deriving sale_date with a stale merchant timezone table shifts sales across midnight. I would pin the timezone source, version it, and backfill when it changes. Second, double counting on backfill: a full re-run without a merge key inserts duplicate rows. The unique_key above, plus a dbt uniqueness test on that grain in CI, catches it. Third, silent schema change upstream: a new channel value or a null product_id for deleted products. I would add a data quality check that fails the build on unexpected null rates or new enum values, rather than letting the dashboard show a blank channel.
If the interviewer pushes on alternatives, I would mention the virtualised option: keep the normalised model and push aggregation into a semantic layer or a query engine with result caching. That avoids duplication but pays the join and aggregation cost on every cold query, and cache hit rates collapse for long-tail merchant filters. For a high-traffic dashboard with a fixed set of questions, the materialised mart wins. For exploratory analysis by analysts, it does not, and I would keep both.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Design an idempotent Airflow DAG for daily ETL pipeline orchestration?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would make the logical date do the idempotency work. One DAG run per ds, one deterministic output partition per ds, and a merge keyed on the natural business key. A rerun for the same ds then produces the same rows, in the same place, with no duplicates.
For Shopify orders, I would land raw extracts in GCS or the warehouse staging area under orders/dt=2026-05-01/, validate them, then merge into the curated orders table on order_id. The DAG never appends blindly. It either replaces the dt partition or runs a MERGE that updates existing keys and inserts new ones. Either way, running it twice is safe.
# Airflow 2.9, Python 3.11
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
from datetime import datetime, timedelta
with DAG(
dag_id="daily_orders_etl",
schedule="@daily",
start_date=datetime(2024, 1, 1),
catchup=False,
max_active_runs=1,
default_args={"retries": 3, "retry_delay": timedelta(minutes=5), "execution_timeout": timedelta(hours=2)},
) as dag:
extract = PythonOperator(task_id="extract_orders", python_callable=extract_orders)
validate = PythonOperator(task_id="validate", python_callable=validate_orders)
load = BigQueryInsertJobOperator(
task_id="merge_orders",
job_config={"query": MERGE_SQL},
location="northamerica-northeast1",
)
extract >> validate >> loadMERGE_SQL is templated with {{ ds }} and reads only dt='{{ ds }}'. No task uses wall-clock time or a random file name. That is the whole trick. If a task retries, it writes to the same partition. If an operator reruns the DAG for a backfill date, it touches only that date.
Why this is idempotent, in a trace
Assume 1.2 million order rows for ds=2026-05-01, with 40,000 changed since the previous day.
| Run | Action | Rows in curated table for that ds | Result |
|---|---|---|---|
| 1 | Extract, validate, merge | 1,200,000 | success |
| 2, retry after worker crash | Re-extract same ds, merge again | 1,200,000 | no duplicates, same keys updated |
| 3, manual rerun | Same merge | 1,200,000 | row count and checksum unchanged |
| 4, late file for prior day | Backfill ds=2026-04-30 only | prior partition corrected, 2026-05-01 untouched | no double count |
The merge key matters more than the tool. order_id alone is not enough if the source can send corrections. I would merge on order_id and keep the row with the highest updated_at, or use a source sequence number when Shopify exports provide one. Without that tie-breaker, a rerun can flip between two versions of the same order.
Failure modes I would name in the loop
Partial load: the extract writes 900,000 of 1.2 million rows, then the worker dies. The staging partition is incomplete, so validation fails on row count against the source manifest and the merge never runs. The retry overwrites staging for that ds before merging.
Late or duplicate source files: the sensor checks a manifest with file name, row count and checksum for ds, not just file existence. A duplicate delivery with the same checksum is skipped. A late file triggers a targeted backfill for its own ds, not a full reload.
Schema drift: validation checks required columns and types before the merge. A new nullable column passes and is ignored by the curated model until it is promoted. A renamed or retyped column fails the task and pages the owner, instead of silently nulling a field in the warehouse.
Concurrency: max_active_runs=1 and a single writer per partition stop two runs racing on the same dt. For a backfill of 30 days, I would run them sequentially or partition the work by ds with a pool limit, and watch warehouse slots. At Shopify scale, a 30-day backfill at 1.2 million rows a day is 36 million rows. That is fine as a batch, painful if all 30 runs contend for the same slots at once.
Alternatives and when I would not use this
If the source is a streaming change feed, I would skip the daily batch merge and use a streaming load with deduplication on order_id and event time, then materialise daily snapshots downstream. The daily DAG is right when the source is a daily export or snapshot, which is the common case for finance and reporting pipelines. I would also avoid partition replacement if the curated table is queried by order_id across all dates with no dt filter. Then a MERGE over the full table, or a slowly changing dimension, is cleaner than rewriting partitions nobody filters on.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Calculate the 7-day rolling average of sessions per shop using raw event tables?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would state my assumptions first. The raw table is raw_events(event_id, shop_id, session_id, event_name, occurred_at) with occurred_at in UTC, one row per event, and session_id populated on events belonging to a session. A session counts once per shop per calendar day, on the UTC date of its events. If session_id were absent I would count a session-start event instead, and say so.
Then I aggregate to one row per shop per day, fill days with no sessions with zero, and only then apply the window. That order matters. A window over raw events, or over days that happen to have data, gives a different and wrong answer.
-- Presto/Trino dialect, checked against Trino 400+ syntax
WITH deduped AS (
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY event_id ORDER BY occurred_at
) AS rn
FROM raw_events
WHERE occurred_at >= DATE '2025-01-01'
AND occurred_at < DATE '2025-02-01'
AND shop_id IS NOT NULL
AND session_id IS NOT NULL
) t
WHERE rn = 1
),
daily AS (
SELECT shop_id,
CAST(occurred_at AS DATE) AS day,
COUNT(DISTINCT session_id) AS sessions
FROM deduped
GROUP BY 1, 2
),
spine AS (
SELECT d.shop_id, CAST(day AS DATE) AS day
FROM (SELECT shop_id, MIN(day) AS min_day, MAX(day) AS max_day FROM daily GROUP BY 1) bounds
CROSS JOIN UNNEST(SEQUENCE(bounds.min_day, bounds.max_day)) AS t(day)
),
filled AS (
SELECT s.shop_id, s.day, COALESCE(d.sessions, 0) AS sessions
FROM spine s
LEFT JOIN daily d USING (shop_id, day)
)
SELECT shop_id, day, sessions,
AVG(sessions) OVER (
PARTITION BY shop_id
ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7d_avg_sessions
FROM filled
ORDER BY shop_id, day;Why the spine is not optional. Suppose shop 42 has sessions only on 3 of 8 days. Without the spine, ROWS BETWEEN 6 PRECEDING averages the last 7 observed days, which can span three weeks. With the spine, zero days enter the average, which matches "sessions per day, averaged over a week".
Worked trace for one shop, sessions per day:
| day | sessions | rolling 7-day average |
|---|---|---|
| 2025-01-01 | 10 | 10.00 |
| 2025-01-02 | 0 | 5.00 |
| 2025-01-03 | 20 | 10.00 |
| 2025-01-04 | 0 | 7.50 |
| 2025-01-05 | 30 | 12.00 |
| 2025-01-06 | 0 | 10.00 |
| 2025-01-07 | 40 | 14.29 |
| 2025-01-08 | 50 | 20.00 |
On 2025-01-07 the average is (10+0+20+0+30+0+40)/7 = 14.29. On 2025-01-08 the window slides and drops 2025-01-01: (0+20+0+30+0+40+50)/7 = 20.00. I would flag the first six rows as partial windows. For a dashboard I would either suppress them until 7 days exist or label them partial, rather than silently compare a 2-day average with a 7-day one.
Failure modes I would name in the loop.
Duplicate event_id rows from a retried producer inflate event counts, which is why I dedupe before counting and count distinct session_id rather than rows. Late-arriving events change past days, so a daily job should recompute the trailing 7 days and overwrite, not append, and I would track the watermark lag per partition. A session spanning midnight UTC counts on both days under my assumption. If the business defines a shop's day in the shop's timezone, I would convert occurred_at with the shop's timezone before truncating to date, and that choice changes the result for shops near midnight. Internal, bot and test-shop traffic needs an explicit filter agreed with the analytics owner, not an ad hoc WHERE I invent.
Performance. The expensive part is the raw scan, so I partition-prune on occurred_at, pre-aggregate to shop-day before the window, and keep the window input at one row per shop per day. Windowing millions of raw events per shop would be wasteful and harder to debug. For a recurring pipeline I would materialise daily once and derive both the daily metric and the rolling average from it, so the two numbers can never disagree.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Design a schema to track order modifications and late-arriving refund events, explaining how you will keep model transformations idempotent?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would keep three layers separate. Raw events are immutable and keyed by the source event id. A bitemporal history table records every order modification as a new row, never an update in place. A current-state table is derived from that history. Refunds are their own fact, linked to the order and line item, with both the refund event time and the ingestion time. Idempotency comes from deterministic keys and merge semantics, so replaying the same batch produces the same rows instead of duplicates.
Assumptions I would state first: the source emits an event_id per change, events can arrive out of order, and finance needs to restate a closed day when a refund lands late. If any of those fail, the design changes, and I would say so.
Schema
-- Raw, append only. One row per source event, replay safe.
CREATE TABLE raw_order_event (
event_id STRING NOT NULL, -- source id, e.g. refund_9912
order_id STRING NOT NULL,
event_type STRING NOT NULL, -- created, line_item_changed, refund_created, refund_voided
event_time TIMESTAMP NOT NULL, -- when it happened at Shopify
ingested_at TIMESTAMP NOT NULL, -- when we received it
payload JSON NOT NULL
)
PARTITION BY DATE(ingested_at);
-- History: one row per version of an order. SCD type 2 on valid time.
CREATE TABLE dim_order_history (
order_id STRING NOT NULL,
version INT NOT NULL, -- 1, 2, 3 ... per order
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP, -- NULL = current
recorded_at TIMESTAMP NOT NULL, -- ingestion time, for bitemporal queries
total_cents INT64 NOT NULL,
currency STRING NOT NULL,
status STRING NOT NULL,
source_event_id STRING NOT NULL
);
-- Refunds as a fact, not a column on the order.
CREATE TABLE fact_refund (
refund_id STRING NOT NULL, -- deterministic: hash(order_id, event_id)
order_id STRING NOT NULL,
line_item_id STRING,
refund_event_time TIMESTAMP NOT NULL,
ingested_at TIMESTAMP NOT NULL,
amount_cents INT64 NOT NULL,
currency STRING NOT NULL,
is_void BOOL NOT NULL DEFAULT FALSE
);dim_order_history answers "what did we believe on 12 March" and "what do we believe now about 12 March" as two different questions. That distinction is what makes late refunds manageable. A refund that arrives on 20 April for a 10 March order gets refund_event_time in March and ingested_at in April. Finance can report revenue by event time with restatement, or by recognition time without it, from the same table.
Idempotent transformations
Every model derives its primary key from source ids, never from row numbers or load time. In dbt or Spark I would use a merge on that key, or a delete plus insert scoped to the affected partitions. Re-running a partition deletes exactly the rows that partition should contain and inserts them again.
-- dbt incremental model, BigQuery dialect
{{ config(materialized='incremental', unique_key='refund_id', incremental_strategy='merge') }}
SELECT
CONCAT(order_id, ':', event_id) AS refund_id,
order_id,
JSON_VALUE(payload, '$.line_item_id') AS line_item_id,
event_time AS refund_event_time,
ingested_at,
CAST(JSON_VALUE(payload, '$.amount_cents') AS INT64) AS amount_cents,
JSON_VALUE(payload, '$.currency') AS currency,
FALSE AS is_void
FROM {{ ref('raw_order_event') }}
WHERE event_type = 'refund_created'
{% if is_incremental() %}
AND ingested_at > (SELECT MAX(ingested_at) FROM {{ this }})
{% endif %}The trace below is the check I would run in a test. Batch B contains a refund event that arrived late, plus a replay of an event already loaded.
| Step | Input | Effect on fact_refund |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| 1 | Batch B: refund_9912 (new), refund_9900 (already loaded) | Insert refund_9912, merge on refund_id leaves refund_9900 unchanged. Row count +1. |
| 2 | Replay Batch B verbatim | Both keys match existing rows. Merge updates with identical values. Row count unchanged, checksum unchanged. |
| 3 | refund_9912 voided, new event refund_9913 | Insert void row, set is_void on the original via the same merge. Net refund for the order goes to zero without deleting history. |
Late-arriving refunds and restatement
I would not mutate a closed partition in place. I would define a restatement window, say 45 days based on observed refund lag at Shopify scale, and reprocess any partition touched by an event whose event_time falls inside it. Outside the window, the event still lands in raw and in fact_refund, but it is flagged late_beyond_window and reported in the recognition period. That keeps the pipeline bounded while keeping the data honest.
Two failure modes I would name. First, duplicate event_id values from the source with different payloads. Detection is a uniqueness check on event_id in raw, and the fix is to quarantine the second payload rather than let the merge pick one silently. Second, a refund referencing a line item that was modified after the refund was issued. The join to dim_order_history must be on valid_from <= refund_event_time < valid_to, not on the current version, or amounts will be attributed to the wrong line item version.
I would close by naming the test that proves it: load a fixture with an out-of-order modification and a 30-day-late refund, run the model twice, and assert identical row counts and checksums both times.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Calculate active user hours given a daily stream of raw session event logs containing start and end status rows?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would clarify the grain first: one row per session event, with user_id, session_id, event_type in (start, end), and event_ts in UTC. Active user hours for a day is the total length of time each user had at least one open session, summed across users. That definition matters because it forces a union of intervals per user. If a user has sessions 10:00 to 11:00 and 10:30 to 12:00, the answer is 2.0 hours, not 2.5 hours from adding both sessions.
The pipeline has three stages: pair starts with ends per session, merge overlapping intervals per user, then sum merged durations and attribute them to a day.
Pairing starts and ends
Sort events inside a session and use LEAD to attach the next event. A start row opens an interval only if the next row is an end row. This drops duplicate starts and stray ends instead of inventing duration for them.
-- Presto / Trino, checked against Trino 400+ syntax
WITH ordered AS (
SELECT
user_id,
session_id,
event_type,
event_ts,
LEAD(event_type) OVER w AS next_type,
LEAD(event_ts) OVER w AS next_ts
FROM session_events
WHERE event_date = DATE '2026-01-15' -- partition filter on ingest date
WINDOW w AS (PARTITION BY user_id, session_id ORDER BY event_ts)
),
intervals AS (
SELECT user_id, event_ts AS start_ts, next_ts AS end_ts
FROM ordered
WHERE event_type = 'start'
AND next_type = 'end'
AND next_ts > event_ts
)
SELECT * FROM intervals;Worked trace for one user on one day:
| session_id | event_type | event_ts | next_type | interval kept |
|---|---|---|---|---|
| s1 | start | 10:00 | end | 10:00 to 11:00 |
| s1 | end | 11:00 | null | dropped |
| s2 | start | 10:30 | end | 10:30 to 12:00 |
| s2 | end | 12:00 | null | dropped |
| s3 | start | 14:00 | start | dropped, duplicate start |
| s3 | start | 14:05 | end | 14:05 to 14:45 |
| s4 | end | 15:00 | null | dropped, stray end |
Merging overlaps per user
Pairing alone overcounts when sessions overlap. I merge with a running maximum end time: an interval starts a new merged block only when its start is after every previous end for that user.
WITH flagged AS (
SELECT
user_id,
start_ts,
end_ts,
MAX(end_ts) OVER (
PARTITION BY user_id
ORDER BY start_ts, end_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS prev_max_end
FROM intervals
),
grouped AS (
SELECT
user_id,
start_ts,
end_ts,
CASE WHEN prev_max_end IS NULL OR start_ts > prev_max_end THEN 1 ELSE 0 END AS is_new_block
FROM flagged
),
numbered AS (
SELECT
user_id,
start_ts,
end_ts,
SUM(is_new_block) OVER (PARTITION BY user_id ORDER BY start_ts, end_ts) AS block_id
FROM grouped
),
merged AS (
SELECT user_id, block_id, MIN(start_ts) AS merged_start, MAX(end_ts) AS merged_end
FROM numbered
GROUP BY user_id, block_id
)
SELECT
user_id,
DATE(merged_start) AS activity_date,
SUM(DATE_DIFF('second', merged_start, merged_end)) / 3600.0 AS active_hours
FROM merged
GROUP BY user_id, DATE(merged_start);For the trace above, the first two intervals merge into 10:00 to 12:00, which is 2.0 hours. Adding the 14:05 to 14:45 block gives 2.67 hours for that user that day.
Failure modes I would check before trusting the number
| Failure mode | Detection | Handling |
|---|---|---|
| Missing end row, session left open | Count of starts with no following end per day, alert if above 0.1% of starts | Exclude from the metric and emit the session ids to a quarantine table. Do not cap at midnight by default, because that fabricates hours. |
| Duplicate delivery of the same event | Same user_id, session_id, event_type, event_ts appearing more than once | Deduplicate on that key at ingest, keep one copy, and track the duplicate rate as a data quality metric. |
| Late arriving end row lands in the next day's partition | End timestamp on day D, ingest date on day D+1 | Partition by event date, not ingest date, and allow a 48 hour late window with restatement of day D. |
| Interval crosses midnight | DATE(start_ts) <> DATE(end_ts) | Split the interval at midnight before summing, or state clearly that the whole block is attributed to the start date. Splitting is the version I would ship for a daily metric. |
| Clock skew or out of order rows | Negative durations after pairing, or end before start | Filter next_ts > event_ts, count the rejects, and investigate the source client rather than silently absorbing them. |
At Shopify scale I would run this as a daily batch over the raw event table in the warehouse, partitioned by event date, with the quarantine and reject counts published alongside the metric. A streaming version is possible with session windows, but the batch version is easier to restate when late ends arrive, and restatement is the hard part of this metric in practice.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13How would you deduplicate near-identical product listings at scale?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would treat this as entity resolution, not string matching. Exact duplicates are cheap. Near duplicates need blocking, a similarity score, and a survivorship rule that picks one canonical listing per product per shop, because the same physical product sold by two different shops is not a duplicate for merchant purposes.
First I normalise: lowercase title, strip punctuation and units, standardise brand and product_type, extract GTIN/UPC when present, hash images by perceptual hash, and split variant attributes (size, colour, flavour) out of the title. Two listings that differ only in size are variants, not duplicates.
Then I block. Comparing every pair is impossible at Shopify scale. I generate candidate pairs only inside blocks keyed by (brand, product_type, GTIN prefix or first token of normalised title). Inside a block I score pairs with token Jaccard on title shingles plus exact matches on GTIN, brand, and image hash. Pairs above a high threshold auto-merge, pairs in a middle band go to a review queue, pairs below are kept separate.
Scale arithmetic
Suppose 50 million active listings. Naive pairwise comparison is about 1.25 quadrillion pairs. Blocking by brand and product_type typically puts a few hundred listings in a block. With an average block of 200, that is 250,000 blocks times about 20,000 pairs per block, roughly 5 billion candidate pairs. Still large, but it fits a Spark job with MinHash LSH to prune inside blocks before exact scoring. That is the difference between a nightly batch and a job that never finishes.
Candidate generation and scoring
# PySpark, checked against Spark 3.5
from pyspark.sql import functions as F
normalised = (raw
.withColumn("title_norm", F.lower(F.regexp_replace("title", r"[^a-z0-9 ]", " ")))
.withColumn("brand_norm", F.lower(F.trim("vendor")))
.withColumn("block_key", F.concat_ws("|", "brand_norm", "product_type"))
)
candidates = (normalised
.join(normalised, "block_key", "inner")
.filter("a.product_id < b.product_id")
.filter("a.shop_id = b.shop_id") # same shop only for auto-merge
)Scoring combines signals instead of relying on title alone:
| Signal | Weight in score | Why it matters |
|---|---|---|
| GTIN exact match | strong positive | Same barcode, same product in most categories |
| Image perceptual hash distance | strong positive | Same photo reused across duplicate listings |
| Title token Jaccard | medium | Catches reworded titles, misses variant differences |
| Price within 5% | weak positive | Duplicates usually priced alike, distinct products can coincide |
| Variant attribute mismatch | hard veto | Size or colour differs, so do not merge |
A worked trace, with hypothetical scores:
| Pair | GTIN | Title Jaccard | Image hash | Variant | Decision |
|---|---|---|---|---|---|
| A, B | match | 0.91 | match | same | auto-merge |
| A, C | none | 0.88 | match | size differs | keep separate |
| A, D | none | 0.74 | no match | same | review queue |
| A, E | none | 0.41 | no match | same | keep separate |
Pipeline shape
Survivorship picks the listing with the most complete title, description, images, and variants, and records every merged product_id pointing at the canonical id. That audit table is what lets us undo a bad merge.
Failure modes I would watch
False merges are the expensive error. Merging two distinct products corrupts search results and merchant analytics, and it is hard to detect downstream. I would sample auto-merges weekly and track precision on that sample, aiming above 99% before raising the auto-merge threshold. False splits are cheaper: the product still appears twice, which hurts catalog quality but does not corrupt data.
Two specific traps: generic titles like "Blue T-Shirt" collide across unrelated products, so blocks on generic titles need image or GTIN evidence before merging. And sellers intentionally create near duplicates to game search, so a sudden spike in duplicates from one shop should trigger a quality check, not just a merge job.
For evaluation I would hold out a labelled set of a few thousand pairs, measure precision and recall per threshold, and re-tune quarterly as titles and categories drift. Embeddings from a product title model can help as an extra signal for reworded titles, but I would not make them the sole scorer. They are expensive to run on billions of pairs and they blur variant distinctions that exact attributes catch cleanly.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Design a pipeline that ingests raw clickstream data from Shopify merchants, handles late-arriving events, and produces a daily active merchants metric?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
I would clarify the metric first: a daily active merchant is a distinct shop_id with at least one valid clickstream event whose event_ts falls on that calendar day. Arrival time does not define the day. I will assume each event carries event_id, shop_id, event_ts, ingested_at, and event_type, and that the business day is UTC unless product wants shop-local days, in which case I add a shop timezone dimension and aggregate on local date.
The pipeline has three layers. Raw events land append-only in bronze, partitioned by ingestion date, exactly as received. A dedup and validation step produces silver, keyed by event_id. A deterministic daily aggregation reads silver and writes gold, one row per event_date with daily_active_merchants. Late events never get dropped silently. They update the affected historical date and the gold row is restated, with a restated_at timestamp and a version so downstream consumers can tell a first publish from a correction.
Ingestion and dedup. Producers publish to a Kafka topic keyed by shop_id, which keeps a shop's events ordered in one partition. A streaming job writes bronze in micro-batches with the raw payload, topic offset, and ingested_at. Bronze is never updated in place, so a bad transform can be rerun from source. In silver I keep the first copy of each event_id by ingested_at and quarantine rows with a null shop_id, an unparseable timestamp, or an unknown event_type into a dead-letter table with the rejection reason. That quarantine count is a monitored metric, not a log line.
Late-arriving events. I set a watermark on event_ts, for example 72 hours of allowed lateness, and I measure the actual distribution before fixing it. The handling depends on how late the event is:
| Lateness vs watermark | Handling | Effect on the metric |
|---|---|---|
| On time | Normal daily run | Included in first publish |
| 0 to 72 hours late | Recompute the affected event_date partitions | Gold row restated, version incremented |
| Over 72 hours late | Write to a late-events table, trigger a targeted backfill for that date | Restated on backfill completion, late volume alerted |
Recomputing a date means deleting and reinserting that partition from silver, or using a MERGE on (event_date, shop_id) if I keep a shop-day intermediate table. I prefer the shop-day intermediate: silver collapses to one row per (event_date, shop_id) with event_count and first_seen_at, and gold is a COUNT(*) over that. A late event then only touches one shop-day row, and the daily count is a cheap recount. Rerunning the same input produces the same output, which is what makes backfills safe.
The aggregation.
-- silver.shop_day: one row per (event_date, shop_id)
MERGE INTO silver.shop_day AS target
USING (
SELECT event_date, shop_id, COUNT(*) AS event_count
FROM silver.clickstream
WHERE event_id IS NOT NULL
AND shop_id IS NOT NULL
AND event_type IN ('page_view', 'product_view', 'add_to_cart')
GROUP BY event_date, shop_id
) AS source
ON target.event_date = source.event_date
AND target.shop_id = source.shop_id
WHEN MATCHED THEN UPDATE SET event_count = source.event_count
WHEN NOT MATCHED THEN INSERT VALUES (source.event_date, source.shop_id, source.event_count);
-- gold.daily_active_merchants
SELECT event_date, COUNT(*) AS daily_active_merchants
FROM silver.shop_day
GROUP BY event_date;Scale check, with hypothetical figures. Suppose 2 billion raw events a day across 2 million shops. Dedup by event_id typically removes 1 to 3 percent from client retries, so silver holds roughly 1.95 billion rows. The shop-day collapse reduces that to about 2 million rows a day, which is the number that matters for the metric. If 0.5 percent of events arrive more than 24 hours late, that is 10 million events touching maybe 300 thousand shop-days, and recomputing those partitions is minutes of work rather than a full reprocess.
Failure modes I would watch. Duplicate event_id values with different payloads, which means the id is not actually unique and I need a composite key of event_id plus a payload hash. Clock skew on client devices pushing event_ts into the future, handled by rejecting events more than a day ahead of ingested_at into quarantine. Test and staff shops inflating the count, handled by a shop attribute join that filters internal shops at the gold layer. And a silent producer outage, detected by comparing bronze row counts and distinct shop counts against the previous seven days at the same hour, plus watermark lag as an alert. A reconciliation job that recounts distinct shops directly from bronze for a sample of dates catches drift between the layers before a dashboard does.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15What is your experience with streaming vs batch pipelines, and talk through a data model you designed?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
I have run both, and I choose based on the decision the data has to support, not on the technology. Batch when the business can wait for a complete, reconciled day. Streaming when a downstream action has to happen in seconds, for example fraud checks, inventory reservation, or live shop dashboards during a sale.
The model I will walk through is the one I built for order and refund reporting across many shops. It had to answer two questions that pull in opposite directions: what did we sell today, and what did the number become after a refund arrived three days later. That tension is why the model is event based at the bottom and snapshot based at the top.
Streaming versus batch in practice
| Dimension | Batch | Streaming |
|---|---|---|
| Typical latency | Hourly to daily, 1 to 24 h | Seconds to minutes |
| Correctness model | Full recompute over a partition, easy to reconcile | Watermark plus allowed lateness, duplicates are normal |
| Cost shape | Cheap per row at scale, wasted on idle hours | Pays for always-on capacity, cheaper per decision |
| Failure mode I watch | A late file silently shifts yesterday's totals | A consumer lag grows and the dashboard looks live but is 40 minutes old |
At my last role I started with a nightly batch for finance reporting. Finance needed a number that tied to the payment ledger, so we loaded raw order events into the warehouse, then rebuilt the day partition from scratch. Rebuilds made the job idempotent. If a partition was bad, we dropped and reloaded it, and the totals matched the ledger to the cent.
We added streaming later for one narrow use case: detecting a spike in checkout failures by shop. That did not need perfect counts. It needed a 5 minute alert. We consumed order and checkout events from Kafka, aggregated in Spark Structured Streaming with a 10 minute watermark, and wrote to a serving table. When the watermark passed, late events were dropped from the alert path and counted separately so we could see how much we were missing.
The data model I designed
Raw events land unchanged, with event_id, event_type, occurred_at, ingested_at, and the payload. I never update raw rows. Corrections arrive as new events. That choice cost storage, about 3x the cleaned size in our case, and it bought us replay. When a bug in a transform was found, we replayed from raw instead of asking upstream to resend.
The cleaned layer has three tables. dim_shop is slowly changing, one row per shop per day with plan and region, because a shop can move plans mid month and finance needs the plan that applied on the order date. dim_product carries the product title as sold, since titles change and reports must show what the customer saw. fct_order_line is one row per order line per event version, keyed by order_id, line_id, and event_id, with quantity, gross amount, discount, refund amount, and a is_current flag.
The key design decision was handling late refunds. A refund event three days later does not edit the original sale row in raw. In the warehouse, a merge updates the current row for that line and inserts a new version. Reporting queries filter is_current = true, so a rerun of last Tuesday gives the same answer as the live view, provided the refund had arrived by then. For finance close, we snapshot the table at month end into a separate table so later refunds do not rewrite a closed month.
-- dbt model, checked against BigQuery Standard SQL
merge into {{ ref('fct_order_line') }} target
using {{ ref('stg_order_line_events') }} source
on target.order_id = source.order_id
and target.line_id = source.line_id
and target.is_current = true
when matched then
update set target.is_current = false,
target.superseded_by = source.event_id
when not matched then
insert (order_id, line_id, event_id, quantity, gross_amount,
refund_amount, occurred_at, is_current)
values (source.order_id, source.line_id, source.event_id,
source.quantity, source.gross_amount, source.refund_amount,
source.occurred_at, true)How I know it works
Three checks run on every load. Row counts from raw to cleaned must reconcile within a tolerance, and any gap pages the on-call. A daily check compares sum(gross_amount - refund_amount) in the model against the payment ledger total for that day. In our setup a difference above 0.01% blocked the publish. A freshness check on the streaming path measured consumer lag, and we alerted if lag exceeded 5 minutes during peak traffic, because a lagging alert is worse than no alert.
If I were starting this today I would keep the same split. Batch for anything money related, streaming only where a fast, slightly approximate answer changes an action, and a model that treats refunds and corrections as new facts rather than edits. That separation is what let us pass a finance audit without slowing down the product team.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Write a simple incremental ETL function in Python?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
An incremental ETL loads only rows changed since the last successful run, not the whole table. The piece that makes it correct is the watermark: the high-water mark of updated_at, with id as tie-breaker, that the previous run committed. I read rows after that mark, transform them, upsert into the warehouse, and only then advance the watermark. If the load fails, the watermark stays put and the next run re-reads the same window. That gives idempotency, provided the load is an upsert keyed on the primary key.
Assumptions I would state first: the source exposes a reliable updated_at, rows are upsertable by id, and deletes are either rare or signalled. If deletes matter, a plain updated_at filter misses them and I need a tombstone flag or CDC stream instead.
# Python 3.11, standard library only. source and warehouse are
# thin wrappers around your API client and DB connection.
# source.fetch_changed(cursor_ts, cursor_id, limit) returns rows
# with (updated_at, id) > (cursor_ts, cursor_id), ordered by
# (updated_at, id), at most limit rows.
from datetime import datetime, timedelta, timezone
def parse(ts):
return datetime.fromisoformat(ts.replace("Z", "+00:00"))
def incremental_etl(source, warehouse, state, batch_size=500):
watermark = parse(state.get("watermark", "1970-01-01T00:00:00Z"))
overlap = timedelta(minutes=5) # absorb late-arriving updates
# Each run restarts from watermark minus overlap, with id 0,
# so the tail is re-read and the upsert absorbs duplicates.
cursor_ts = watermark - overlap
cursor_id = 0
while True:
rows = source.fetch_changed(cursor_ts, cursor_id, batch_size)
if not rows:
break
clean = [transform(r) for r in rows if valid(r)]
warehouse.upsert("orders", clean, key="order_id")
# Advance only after the upsert commits.
last = rows[-1]
cursor_ts, cursor_id = parse(last["updated_at"]), last["id"]
watermark = cursor_ts
state.save({"watermark": last["updated_at"]})
if len(rows) < batch_size:
break
return watermarkThree details carry the correctness. First, the cursor is a tuple, (updated_at, id), not a timestamp alone. Hundreds of orders can share the same second, and updated_at > watermark would skip the rest of that second. Ordering by (updated_at, id) and resuming after the last id closes that gap. Second, the 5 minute overlap re-reads a small tail so a row updated just before the watermark but replicated late still lands. The upsert makes the re-read harmless. Third, the state save sits after the commit. Saving it before the load is the classic way to lose a day of orders silently.
Worked trace, starting watermark 10:00:00:
| Run | Cursor at start | Rows upserted | Watermark after commit |
|---|---|---|---|
| 1 | 09:55:00, id 0 | ids 101, 102, 103 | 10:02:00 |
| 2 | 09:57:00, id 0 | id 102 again, id 104 | 10:04:00 |
| 3 | 09:59:00, id 0 | load raises, nothing committed | unchanged, 10:04:00 |
| 4 | 09:59:00, id 0 | ids 105, 106 | 10:06:00 |
Run 2 shows the overlap doing its job: the cursor id resets to 0 at the start of each run, so id 102, whose updated_at is 10:01:00, falls inside the re-read window even though run 1 already processed it. Run 3 shows the failure mode: because state only moves on commit, run 4 retries from the same watermark.
Where this breaks in production: a source with no monotonic updated_at, for example clock skew across shards, makes the watermark lie, so I would switch to a source sequence number or CDC log offset. Hard deletes never appear in a changed-rows query, so a cancelled order would linger in the warehouse unless the source sends tombstones. Schema drift, a new field arriving mid-batch, fails validation and stalls the watermark, which is visible because the lag metric now - watermark grows. I would alert on that lag rather than on job failure alone, since a job that succeeds but stops advancing is the quieter outage.
For a Shopify loop I would close by naming the upgrade path: swap the polling fetch for webhooks or a CDC stream when the lag budget drops below the poll interval, and move the state store into the warehouse so the watermark and the data commit in one transaction.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Solve a SQL window function problem using rank within partition, then filter on that rank?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
Window functions run after WHERE and GROUP BY, so you cannot put RANK() in a WHERE clause. You compute the rank in an inner query or CTE, then filter on it outside. That two-step shape is the whole trick.
Say the task is: for each shop, return its top 2 orders by value. I would write it in BigQuery SQL like this:
-- BigQuery, checked against standard SQL window syntax
WITH ranked AS (
SELECT
order_id,
shop_id,
customer_id,
total,
created_at,
RANK() OVER (
PARTITION BY shop_id
ORDER BY total DESC
) AS rnk
FROM `shopify.orders`
WHERE status = 'paid'
AND created_at >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
)
SELECT order_id, shop_id, total, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY shop_id, rnk, total DESC;PARTITION BY shop_id restarts the ranking for every shop. ORDER BY total DESC inside the OVER clause decides who is first within that partition. The outer WHERE rnk <= 2 is legal because rnk is now a plain column produced by the CTE.
Worked trace
| shop_id | order_id | total | rnk |
|---|---|---|---|
| 101 | o1 | 500 | 1 |
| 101 | o2 | 300 | 2 |
| 101 | o3 | 300 | 2 |
| 101 | o4 | 100 | 4 |
| 102 | o5 | 900 | 1 |
| 102 | o6 | 200 | 2 |
Filtering rnk <= 2 returns o1, o2, o3, o5, o6. Note o2 and o3 both survive. RANK() gives tied rows the same rank, then skips the next rank, which is why o4 is rank 4 and not 3. If the business rule is exactly two rows per shop, RANK() is the wrong function.
Choosing the function
| Function | Ties | Rows returned for <= 2 | Use when |
|---|---|---|---|
ROW_NUMBER() | broken arbitrarily | exactly 2 per shop | you need a fixed count, tie break does not matter |
RANK() | same rank, gaps after | 2 or more if tied at rank 2 | tied orders genuinely deserve equal standing |
DENSE_RANK() | same rank, no gaps | 2 or more if tied at rank 2 | you want ranks 1, 2, 2, 3 |
For a fixed count I would switch to ROW_NUMBER() and add a deterministic tie breaker, for example ORDER BY total DESC, created_at DESC, order_id. Without that tie breaker, which tied row wins can change between runs and between engines, and a downstream dbt model will look non-deterministic.
BigQuery and Snowflake also accept the shorter form:
SELECT order_id, shop_id, total
FROM `shopify.orders`
WHERE status = 'paid'
QUALIFY RANK() OVER (PARTITION BY shop_id ORDER BY total DESC) <= 2;QUALIFY filters on window results directly. I would mention it, then still write the CTE version in an interview, because the CTE works in Postgres and Presto too and makes the execution order explicit.
Failure modes I would call out
First, filtering before ranking changes the answer. The WHERE status = 'paid' above runs before the window, so unpaid orders never consume a rank. If I filtered on rnk in the same level as the window, the engine would reject it, and if I moved the status filter outside, a shop could fill its top 2 with unpaid orders.
Second, NULL totals. In BigQuery, ORDER BY total DESC puts NULL first by default, so a missing total can rank first. I would either filter total IS NOT NULL or write ORDER BY total DESC NULLS LAST and say which I chose.
Third, cost at Shopify scale. The window needs every row for a shop to sort it, so a 30 day scan of a large orders table is the expensive part, not the filter. I would partition the source by date, keep the date predicate selective, and check the query plan for a shuffle on shop_id. If the same ranking feeds several models, I would materialize the ranked CTE once rather than recompute it per consumer.
That order, filter, rank, filter again, is the mental model I would leave with the interviewer.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Given this messy CSV dataset, write SQL queries to clean it, derive some business metrics, and explain your assumptions?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
I would not start by writing metrics. I would load the CSV unchanged into a staging table, profile it, then build a cleaned table with every rejected row quarantined with a reason. Only then would I derive metrics, because most wrong answers in this exercise come from silently dropping or double counting rows before anyone notices.
Assume the file has columns like order_id, shop_id, order_date, status, gross_amount, currency, customer_email and is loaded with everything as text. I am using BigQuery SQL, timestamps stored in UTC, and money kept in minor units until the final step.
Cleaning, in order
First, normalise without losing evidence. Trim whitespace, lower case status and email, strip currency symbols, and parse dates with an explicit format list. Anything that fails a cast goes to quarantine, not to null.
-- staging: raw_csv(order_id STRING, shop_id STRING, order_date STRING,
-- status STRING, gross_amount STRING, currency STRING, customer_email STRING)
WITH normalised AS (
SELECT
TRIM(order_id) AS order_id,
TRIM(shop_id) AS shop_id,
LOWER(TRIM(status)) AS status,
LOWER(TRIM(customer_email)) AS customer_email,
UPPER(TRIM(currency)) AS currency,
SAFE_CAST(TRIM(gross_amount) AS NUMERIC) AS gross_amount,
SAFE_CAST(TRIM(order_date) AS TIMESTAMP) AS order_ts,
ROW_NUMBER() OVER (
PARTITION BY TRIM(order_id), TRIM(shop_id)
ORDER BY TRIM(order_date) DESC
) AS rn
FROM raw_csv
)
SELECT * FROM normalised WHERE rn = 1;The ROW_NUMBER dedupes on (order_id, shop_id), not on order_id alone. At Shopify the same order number can recur across shops, so deduping globally would delete legitimate orders. Keeping the latest row per key is an assumption I would state out loud: if the CSV is an append only export, the last write wins. If it is a snapshot, I would instead flag conflicting duplicates for review.
Second, validate business rules and quarantine failures:
| Check | Rule | Action on failure |
|---|---|---|
order_id, shop_id | not null, not empty | quarantine: missing_key |
order_ts | parses, between 2020-01-01 and load date | quarantine: bad_date |
gross_amount | parses, >= 0 | quarantine: bad_amount |
status | in (paid, refunded, cancelled, pending) | quarantine: unknown_status |
currency | 3 letter code, single currency per shop per day | quarantine: mixed_currency |
A worked trace makes the effect visible. Suppose 1,000,000 raw rows: 12,400 fail a cast, 3,100 are exact duplicates, 800 have an unknown status, and 2 have a negative amount. Cleaned output is 983,698 rows, and the 16,302 quarantined rows are still queryable. If a stakeholder later asks why revenue dropped, I can reconcile raw count = cleaned + quarantined + duplicates removed, instead of guessing.
Deriving metrics
I would define each metric before writing it, because Shopify dashboards usually mean different things by "sales".
WITH cleaned AS ( /* query above, plus quarantine filter */ )
SELECT
DATE(order_ts, 'America/Toronto') AS business_date, -- shop local date, stated explicitly
shop_id,
COUNT(DISTINCT order_id) AS orders,
SUM(IF(status = 'paid', gross_amount, 0)) AS gross_sales,
SUM(IF(status = 'refunded', gross_amount, 0)) AS refunded_sales,
SUM(IF(status = 'paid', gross_amount, 0))
/ NULLIF(COUNT(DISTINCT IF(status = 'paid', order_id, NULL)), 0) AS aov
FROM cleaned
GROUP BY 1, 2;Assumptions I would state in the interview, and put in a comment in the query:
- Gross sales counts only
paidorders.pendingis excluded because payment has not cleared, andcancelledis excluded because no money moved. If the business wants booked sales, I would add a separate column rather than change the definition. - Refunds are treated as a status on the order row, not as a separate event. That works for this CSV but breaks if an order is partially refunded or refunded after the export date. I would flag that as the first thing to fix with an
order_refundstable keyed byrefund_id. - Amounts are summed only within one currency. Summing USD and CAD together is meaningless, so I group by currency or convert with a dated FX table. I would not apply a single static rate.
- Business date uses the shop timezone, not UTC. An order at 23:30 UTC can be the next day in Toronto and the same day in Vancouver, and daily reporting by shop has to pick one. UTC is fine for a global rollup, wrong for a shop level daily report.
Failure modes I would call out
Silent nulls from SAFE_CAST are the main one. A value like 1,299.00 or (12.00) for a credit fails the cast and disappears unless I count cast failures per column and alert when the rate moves. Header drift is the second: a renamed column in a new export makes every cast fail, which is why I load by position into staging and check the header against an expected list before running the pipeline. The third is late arriving refunds. If refunds land a week after the order, a daily snapshot will restate history, so I would version the cleaned table by load date and make the transform idempotent on (order_id, shop_id, load_date) rather than overwriting in place.
That gives the interviewer a pipeline they can audit: raw preserved, rejects explained, metrics defined in plain language before they are computed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Tell me about a time you had to make a tradeoff?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
At my previous role I owned the daily shop revenue pipeline that fed merchant reporting. We had a choice between hourly incremental loads and a single daily batch. I chose hourly incremental, and we accepted a 4-hour freshness SLA instead of the 15 minutes product wanted. That trade bought us a pipeline we could actually keep correct when refunds and webhook retries arrived late, at about a third of the compute cost of streaming.
The context: roughly 180 million order events a day in that hypothetical workload, landing in object storage as raw JSON. Finance needed a number they could close the books on. Merchants wanted to see today's sales while the day was still running. Those two needs pull in opposite directions. A daily full refresh is simple to reason about and easy to audit, but merchants stare at yesterday's number all day. A streaming job gives them near real time, but every late refund becomes a correction problem in a table that is already being read.
What I shipped
Hourly micro-batches from the raw zone into a staging table, then an idempotent merge into the mart keyed by order_id and event_id. The mart is partitioned by event_date, and each run recomputes only the partitions touched by late data in the last 72 hours.
| Option | Freshness | Daily compute, hypothetical | Correction handling |
|---|---|---|---|
| Daily full refresh | 24 h | 1.0x baseline | Trivial, rebuild everything |
| Hourly incremental, chosen | 4 h SLA | 1.3x baseline | Recompute touched partitions only |
| Streaming, Flink | 5 min | 3.5x baseline | Continuous upserts, harder to audit |
The arithmetic that settled it: a full refresh scanned about 2.1 TB a day. Hourly incremental scanned about 180 GB of new events plus roughly 90 GB of late arrivals, so 270 GB, but it ran 24 times. With per-run overhead that landed near 1.3x the daily cost, not 24x. Streaming would have kept a cluster warm 24 hours for a reporting use case where merchants check a dashboard a few times a day, not a fraud model that needs a decision in seconds.
The merge that made hourly safe
-- BigQuery, checked against the current syntax
MERGE INTO `mart.shop_revenue` AS target
USING (
SELECT order_id, event_date,
SUM(amount_cents) AS revenue_cents,
COUNT(*) AS event_count
FROM `staging.order_events_deduped`
WHERE event_date BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY)
AND CURRENT_DATE()
GROUP BY order_id, event_date
) AS source
ON target.order_id = source.order_id
AND target.event_date = source.event_date
WHEN MATCHED THEN
UPDATE SET revenue_cents = source.revenue_cents,
event_count = source.event_count
WHEN NOT MATCHED THEN
INSERT (order_id, event_date, revenue_cents, event_count)
VALUES (source.order_id, source.event_date,
source.revenue_cents, source.event_count);Deduplication on event_id before the merge handled webhook retries, which we measured at about 2% of events. Without it, hourly runs double counted revenue and the error only showed up when finance reconciled against payment records.
Failure modes I watched
Late refunds beyond 72 hours would miss the recompute window, so I added a weekly partition rebuild and an alert on the count of events arriving with event_date older than 3 days. If that count crossed 0.1% of daily volume, the SLA conversation reopened. A second failure mode was a bad hourly run poisoning the mart. Because the merge is idempotent and the staging table is retained for 7 days, rerunning the same hour produced the same result, which we verified by comparing row counts and revenue sums before and after a forced rerun in staging.
What I would not do again
I would not promise 15 minute freshness in the first design review. The honest version is: merchants get a number that is at most 4 hours old, finance gets a number that survives a rerun, and the team is not paged for a streaming cluster at 3 a.m. If the use case had been fraud scoring or inventory reservation, where a stale number causes a wrong decision in seconds, I would have taken the streaming cost. For reporting, correctness and rerunnability were worth more than minutes.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Describe a time you had to navigate a cross-functional dispute to deliver a data project?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I was the data engineer on a merchant reporting project at a commerce platform, similar in shape to Shopify. Product wanted a daily "net revenue per shop" metric shipped for a launch in three weeks. Finance blocked it. Their number for the same day differed by 6.4%, and they would not sign off on a dashboard that contradicted the ledger they close the month on.
The dispute was not about SQL. Product defined net revenue as gross merchandise value minus refunds issued that day. Finance defined it as revenue recognised on the order date, minus refunds attributed back to the original order date, even if the refund arrived 40 days later. Both were defensible. Shipping either one without agreement would have meant two numbers for the same shop in the same week, and support tickets we could not answer.
I did not pick a side. I made the disagreement measurable, then put a decision in front of both teams with a cost attached to each option.
What I did first
I reproduced both numbers from the same raw tables for 90 days, at shop level, and decomposed the 6.4% gap. That turned an argument about definitions into a table we could all read.
| Component | Effect on gap (pp) | Evidence |
|---|---|---|
| Refunds attributed to refund date vs order date | 4.1 | 11% of refunds landed >14 days after the order |
| Currency conversion at daily rate vs order-date rate | 1.3 | Cross-border shops, 38% of GMV |
| Cancelled orders included in Product's GMV | 0.7 | Status changed after daily snapshot |
| Rounding and late-arriving events | 0.3 | Reconciliation run, see below |
The SQL I used for the reconciliation was deliberately boring, so Finance could rerun it:
-- BigQuery, checked against warehouse tables
WITH orders AS (
SELECT shop_id, order_id, order_date,
gross_amount, currency
FROM `raw.orders`
WHERE order_date BETWEEN DATE '2024-01-01' AND DATE '2024-03-31'
),
refunds AS (
SELECT order_id, refund_date, refund_amount
FROM `raw.refunds`
)
SELECT
o.shop_id,
SUM(o.gross_amount) - SUM(COALESCE(r.refund_amount, 0)) AS product_net,
SUM(o.gross_amount) - SUM(CASE WHEN r.refund_date <= DATE_ADD(o.order_date, INTERVAL 90 DAY)
THEN r.refund_amount ELSE 0 END) AS finance_net
FROM orders o
LEFT JOIN refunds r USING (order_id)
GROUP BY o.shop_id;That gave us a shared fact base. Product's version was a cash view. Finance's was an accrual view. Neither was wrong for its own use.
How the dispute actually resolved
I wrote a one-page decision doc with two options, not a recommendation to "use the right one." Option A: ship Product's cash view for the launch, labelled net_revenue_cash, with Finance's accrual view published alongside it as net_revenue_accrual and a documented bridge between them. Option B: delay the launch by four weeks to rebuild the pipeline around event-time attribution and restatements, which Finance wanted but Product had not budgeted for.
We shipped Option A in 19 days. The key move was naming. Once the columns were net_revenue_cash and net_revenue_accrual, the argument stopped being "whose number is true" and became "which column does this surface need." Merchant-facing reporting used the cash view, because a shop owner asking "what hit my account today" wants cash. Internal finance reporting used the accrual view. The bridge table, the four components above, was published in the metric catalogue so anyone could walk from one number to the other.
What I would do differently, and what I watch for now
I spent the first week trying to convince Finance their definition was too complex for merchants. That was wasted time. The lesson I took into later roles: when two teams dispute a metric, check first whether they are answering different questions with the same name. In this case, cash versus accrual.
Failure mode I now guard against: silent restatement. If we had shipped the accrual view alone, every daily number would have changed for 90 days as late refunds arrived, and merchants would have seen their history move without explanation. So the pipeline now writes both views, versions the metric definition, and alerts when the bridge between them moves by more than 0.5 pp week on week. That alert fired once, when a payment provider delayed refund events by six days, and we caught it before Finance did.
The project shipped on time, Finance signed the catalogue entry, and the support team got a one-paragraph explanation they could paste into tickets. That, more than the SQL, is what made it deliverable.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Implement a program to model robot movement by inputting string commands through a terminal interface?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I would clarify the command language first, because the implementation follows from it. Assume a bounded grid, a start pose, and four commands: F forward one cell, B backward one, L turn left, R turn right. The terminal loop reads a line, parses it into commands, applies each one to the robot state, and prints the new pose. Parsing and state transition stay separate from input and output, so the same transition can be replayed from a log of commands. That separation matters if this later becomes an event stream: a command log plus a deterministic transition gives you reproducible state without storing snapshots.
# Python 3.11, checked against CPython 3.11
from dataclasses import dataclass
HEADINGS = ["N", "E", "S", "W"] # clockwise
DELTAS = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
@dataclass(frozen=True)
class Pose:
x: int
y: int
heading: str # one of HEADINGS
def step(pose: Pose, cmd: str, width: int, height: int, obstacles: set[tuple[int, int]]) -> Pose:
if cmd == "L":
i = HEADINGS.index(pose.heading)
return Pose(pose.x, pose.y, HEADINGS[(i - 1) % 4])
if cmd == "R":
i = HEADINGS.index(pose.heading)
return Pose(pose.x, pose.y, HEADINGS[(i + 1) % 4])
if cmd in ("F", "B"):
dx, dy = DELTAS[pose.heading]
sign = 1 if cmd == "F" else -1
nx, ny = pose.x + sign * dx, pose.y + sign * dy
if not (0 <= nx < width and 0 <= ny < height):
raise ValueError(f"move to ({nx},{ny}) leaves {width}x{height} grid")
if (nx, ny) in obstacles:
raise ValueError(f"move to ({nx},{ny}) hits obstacle")
return Pose(nx, ny, pose.heading)
raise ValueError(f"unknown command {cmd!r}")
def run(commands: str, start: Pose, width: int, height: int, obstacles: set[tuple[int, int]]) -> Pose:
pose = start
for cmd in commands.strip().upper():
if cmd.isspace():
continue
pose = step(pose, cmd, width, height, obstacles)
return pose
def main() -> None:
pose = Pose(0, 0, "N")
while True:
try:
line = input("> ")
except EOFError:
print()
break
except KeyboardInterrupt:
print()
break
if line.strip().lower() in ("quit", "exit"):
break
try:
pose = run(line, pose, width=10, height=10, obstacles={(3, 3)})
print(f"pose: x={pose.x} y={pose.y} heading={pose.heading}")
except ValueError as e:
print(f"rejected: {e}")
if __name__ == "__main__":
main()Atomicity comes from where the intermediate pose lives. run keeps its working pose in a local variable and returns it only after every command in the line succeeds. If step raises on command three, the exception propagates and the caller in main never receives the partially updated pose, so pose there still holds the pre-line value. That is a deliberate trade-off. The user retypes the whole line, and the work spent on the first two commands is discarded, but the robot never sits in a state the user did not ask for. Validation order inside step follows the same logic. Turns return before any bounds check, because turning in place cannot leave the grid. For F and B, bounds are checked before obstacles, so a target outside the grid reports a bounds error even if an obstacle set happened to contain that coordinate. Checking in the other order would mislabel the failure and could leak obstacle data for cells that do not exist.
A worked trace on a 10 by 10 grid starting at (0,0) facing north, with an obstacle at (3,3):
| Input | Pose after input | Notes |
|---|---|---|
FF | (0,2) N | two forward moves |
R | (0,2) E | turn in place, position unchanged |
FFF | (3,2) E | stops one cell short of the obstacle row |
LFF | (3,2) E | rejected: L turns north, first F targets (3,3), whole line discarded |
LB | (3,1) N | turn north, then backward one cell |
X | (3,1) N | rejected, unknown command, pose unchanged |
The LFF row is the case that decides the design. Per-command commit would leave the robot at (3,2) facing north after the turn, with the blocked move dropped. Line-atomic commit leaves it facing east, which is what the code above does. I would state that choice out loud in the interview, because either behaviour is defensible and the interviewer is likely to probe it.
Failure modes and how they show up. An unknown token such as X raises in step, the loop prints rejected: unknown command 'X', and the pose is unchanged. Detection is immediate, and the cost is one discarded line. A blocked or out-of-bounds move behaves the same way, with the target coordinates in the message so the user can correct the plan without guessing. End of input is the one that crashes a naive loop: input() raises EOFError when stdin closes, for example when the program is piped a file or run in a container without a terminal. The try around input() catches that and exits cleanly, and KeyboardInterrupt covers Ctrl-C. Without that handler the traceback is the only signal that the session ended, and any unsaved command log would be lost. A robot configured to start on an obstacle is not caught by the move checks, since no move targets the start cell. I would validate the start pose against the obstacle set at startup and fail fast there, rather than discovering it mid-session.
Two follow-ups I would expect. First, longer commands such as MOVE 3 or TURN LEFT: I would replace the single-character parser with a tokenizer that splits on whitespace and maps words to the same step function, so the transition logic does not change. Second, persistence: I would append each accepted command line to a log file and rebuild state by replaying it on startup. Replay is O(n) in log length, which is fine for a terminal tool, and it gives the same determinism a pipeline gets from replaying an event log rather than trusting a stored snapshot.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22How did you first get into tech, and what is your plan for the next 1-2 years?
Reported in Shopify Data Engineer Interview Questions & Loop
The 90-second answer
I got into tech through a job I did not want to keep doing by hand. In 2019 I was in operations for a small retail chain and spent every Friday exporting sales from our POS, cleaning the CSV in Excel, and sending a pivot to the owner. I wrote a Python script to do it. It worked for three weeks, then broke when the POS renamed a column and silently dropped a store that had been added that month. Nobody noticed for two days because the total still looked plausible. That failure is why I moved from reports to pipelines: I wanted the checks that would have caught it.
My plan for the next 1 to 2 years is to go deeper on reliability, not wider on tools. In year 1 I want to own one production pipeline end to end and learn how this team runs Spark and dbt at Shopify volume. In year 2 I want to take one batch flow that is painful because it is late, and decide with data whether it should become incremental or streaming, or stay batch with better checks. I am not planning a move into management, and I am not planning to rebuild everything in a new stack.
Why those checks, and what each one actually catches
At my last role our daily orders pipeline failed or produced a suspect number about 8 percent of runs. That is roughly 20 bad mornings a year out of 250. We cut it to under 2 percent, about 5 a year, and the split matters because each check maps to a different cause.
A schema check at ingestion catches the column rename. It fails the run in minute 2 instead of producing a wrong total in hour 3. A freshness check on the source table catches an upstream delay. If the source landed at 09:40 instead of 06:00, we alert before the transform consumes a partial day and creates a dip that finance then has to explain. An idempotent load keyed on order_id and updated_at catches the retry problem. When a job reruns after a timeout, it upserts the same rows instead of duplicating them.
# Python 3.11, checked against pandas 2.2. Expected columns from the source contract.
expected = {"order_id": "int64", "shop_id": "int64", "updated_at": "datetime64[ns]", "total_cents": "int64"}
actual = {c: str(df[c].dtype) for c in df.columns}
missing = set(expected) - set(actual)
changed = {c for c in expected if c in actual and actual[c] != expected[c]}
if missing or changed:
raise ValueError(f"schema drift: missing={missing} changed={changed}")That snippet is deliberately boring. It does not try to infer types or coerce a renamed column. Coercion is how a total column in dollars quietly becomes cents. Failing loudly is cheaper than reconciling later.
The trade-off I want to work on in year 2
Streaming is not automatically better than batch. Batch is simpler to reason about, cheaper to run, and easier to backfill. If a finance metric is consumed once a day, moving it to streaming buys nothing and adds operational cost: a streaming cluster to run, ordering and late event handling to get right, and a harder story for exactly once processing. In our case, hypothetical figures from that pilot, Spark Structured Streaming added about 0.4 engineer weeks per month of on call and tuning, versus near zero for the existing Airflow DAG.
Streaming earns that cost only when latency changes a decision. A merchant facing operational metric that is stale by 6 hours can cause support to act on old order states. There, a 15 minute freshness target justifies the complexity. My year 2 goal is to pick one such flow, measure the cost of late and duplicate events, and either ship streaming or document why hourly incremental batch was the right call. Both outcomes count as success if the numbers support them.
| Failure mode | Detection | Operational cost if missed |
|---|---|---|
| Source lands late or partial | Freshness check plus row count versus source manifest | Downstream metric dips, finance spends hours explaining a non event |
| Schema drift, renamed or retyped column | Ingestion schema check above | Silent drop or wrong units, discovered by a user days later |
| Retry after timeout duplicates rows | Idempotent upsert on order_id, updated_at, plus duplicate key count per run | Double counted revenue, backfill becomes a manual correction |
| Late arriving refund after daily close | Watermark and late event table, reconciliation report next morning | Metric restated without an audit trail |
What I will ask for in the first month
I will ask which pipeline the team most wishes someone owned, and which metric has caused the most Slack threads. That tells me where the failure cost is highest. If I join, I want my first project to be the one that removes the most of those threads, with checks tied to named causes, not a generic push for data quality.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23Solve SQL problems using simple aggregations and joins?
Reported in Shopify Data Engineer interview experience (October 2025)
The 90-second answer
I would first pin down the grain of the result, then write the join at that grain, then aggregate. Most wrong answers on simple aggregation and join problems come from aggregating at the wrong grain, not from exotic SQL.
Take a typical Shopify prompt: revenue and order count per shop per day. The grain is one row per shop_id and day. Orders live in orders, line items live in order_items, and one order has many line items. If I join first and aggregate second, I have to be careful about fanout.
-- PostgreSQL / standard SQL, checked against Postgres 16 syntax
SELECT
o.shop_id,
(o.created_at AT TIME ZONE 'America/Toronto')::date AS day,
COUNT(DISTINCT o.order_id) AS order_count,
SUM(oi.line_total) AS revenue,
ROUND(SUM(oi.line_total) / COUNT(DISTINCT o.order_id), 2) AS avg_order_value
FROM orders o
JOIN order_items oi
ON oi.order_id = o.order_id
WHERE o.status = 'paid'
AND o.created_at >= TIMESTAMP '2025-10-01'
AND o.created_at < TIMESTAMP '2025-10-02'
GROUP BY o.shop_id, day
ORDER BY o.shop_id, day;Three decisions in that query do the work. The WHERE clause filters orders before the join, so cancelled or unpaid orders never reach the sum. COUNT(DISTINCT o.order_id) counts an order once even though it appears on several line item rows. SUM(oi.line_total) sums at line item grain, which is where money actually sits in this schema. I also bucket the day in the shop timezone, because created_at stored in UTC puts a 9 p.m. Toronto order on the next UTC day.
Worked trace
Small input, same schema:
| order_id | shop_id | created_at (UTC) | status | order_id | line_total |
|---|---|---|---|---|---|
| 101 | 7 | 2025-10-01 02:30 | paid | 101 | 40.00 |
| 101 | 7 | 2025-10-01 02:30 | paid | 101 | 10.00 |
| 102 | 7 | 2025-10-01 03:10 | paid | 102 | 25.00 |
| 103 | 7 | 2025-10-01 04:00 | cancelled | 103 | 99.00 |
After the join and the status = 'paid' filter, order 103 is gone. Order 101 contributes two rows. The grouped result for shop 7 on 2025-09-30 in Toronto time (the UTC times above fall on the previous local evening) is:
| shop_id | day | order_count | revenue | avg_order_value |
|---|---|---|---|---|
| 7 | 2025-09-30 | 2 | 75.00 | 37.50 |
COUNT(o.order_id) without DISTINCT would return 3 here. That single word is the difference between a correct answer and a plausible looking one.
Join choice and when it changes
| Need | Join | Effect on the aggregate |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Revenue only from orders that have line items | INNER JOIN | Orders with no items drop out of both count and sum |
| Count all paid orders, even those with no items yet | LEFT JOIN from orders to items | SUM(oi.line_total) ignores the NULL row, COUNT(DISTINCT o.order_id) still counts the order |
| Keep shops with zero orders in a daily report | LEFT JOIN from a shop or date spine to the aggregated result | Requires COALESCE on the measures, applied after aggregation |
The third row is the usual follow-up. I aggregate first in a subquery or CTE, then left join the spine to that result. Joining the spine before aggregating and then trying to fix the zeros with COALESCE inside the same GROUP BY tends to produce one row per shop with a NULL day instead of one row per shop per day.
Failure modes I check before calling it done
Join fanout from a second many-to-many table. Adding a join to order_item_tags or fulfillments multiplies line item rows, and SUM inflates silently while COUNT(DISTINCT) stays correct. The fix is to pre-aggregate each side to the grain I need, then join the aggregates.
Refunds and partial payments. If line_total is gross, revenue needs a separate refunds table joined at order or line item grain, or a net_total column maintained upstream. Summing gross and calling it revenue overstates by the refund amount, and the error grows on high return categories.
Currency and NULLs. SUM skips NULLs, so a mix of currencies in one shop produces a number with no meaning. I group by currency as well, or convert with a rate table joined before aggregation. A NULL line total from a free item should be COALESCE(line_total, 0) only if that is the business rule, and I would state that assumption out loud.
If the interviewer then asks for a rolling version or a ranking, I keep the same grouped CTE as the base and add a window function on top of it. That keeps the aggregation logic in one place and makes the follow-up a small change instead of a rewrite.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24When would you use a data warehouse vs a data lake layer?
Reported in Shopify data engineer interview: pipelines and SQL | Comunidad Primly
The 90-second answer
I would not choose one. I would put raw, immutable data in the lake layer and curated, modelled data in the warehouse, then decide per dataset where the first useful query runs.
The lake layer, typically object storage with Parquet files and a table format such as Iceberg or Delta, holds data as it arrived: clickstream events, webhook payloads, product feeds, logs. Schema can change, volume is high, and most rows are never queried. The warehouse holds data after validation and modelling: orders, payouts, merchant metrics, with a known schema, enforced types, and access controls. At Shopify scale that split matters because merchant data is high cardinality by shop_id, contains personal data, and is queried by many teams for reporting and product analytics.
How I decide
| Signal | Lake layer first | Warehouse first |
|---|---|---|
| Schema | Unknown, evolving, or nested JSON | Stable, agreed by consumers |
| Query pattern | Ad hoc exploration, ML feature scans, replay | Repeated SQL, dashboards, joins across domains |
| Access | Small team, experimental | Many analysts, row level controls, audit |
| Cost shape | Very large, cold, rarely read | Hot, needs fast interactive queries |
| Change | Need to reprocess history with new logic | Need incremental, tested transformations |
A concrete Shopify example: raw shopify_events lands in the lake partitioned by event_date and shop_id. A daily job validates it, deduplicates on event_id, and writes fct_orders and dim_shops to the warehouse. Analysts query the warehouse for revenue by cohort. A data scientist training a churn model reads the lake directly, because the warehouse model dropped fields she needs.
-- Lake: exploratory, partition pruning keeps the scan bounded
SELECT event_name, COUNT(*) AS n
FROM lake.raw_events
WHERE event_date BETWEEN DATE '2026-01-01' AND DATE '2026-01-07'
AND shop_id = 12345
GROUP BY event_name;
-- Warehouse: the same question, answered from a modelled table
SELECT day, active_shops
FROM warehouse.mart_shop_activity
WHERE day BETWEEN DATE '2026-01-01' AND DATE '2026-01-07';Failure modes I watch for
A lake without a catalog, partition discipline, and compaction becomes a swamp. Small files are the usual symptom: 50 million tiny Parquet files make metadata listing slower than the query. I would set a target file size, compact on a schedule, and reject writes below a size threshold.
A warehouse used as a raw dump fails differently. Ingesting unvalidated JSON into warehouse tables forces schema decisions early, breaks when a producer adds a field, and charges warehouse storage and compute for data nobody queries. It also makes deletion hard. For merchant personal data, a GDPR erasure request has to propagate to the lake, the warehouse, and derived tables. If raw data only lives in the lake with a clear lineage map, that propagation is a defined job. If copies are scattered, it becomes a search.
Worked cost check, hypothetical figures
Suppose 500 TB of raw events per month, 10% ever queried in the first 30 days. Keeping all of it in the lake at a hypothetical $0.02 per GB month costs about $10,000 per month before compute. Keeping only the curated 40 TB in the warehouse at a hypothetical $0.04 per GB costs about $1,600, plus the warehouse compute for the daily model. The saving is not the point. The point is that the warehouse stays small enough for interactive queries, and the lake stays cheap enough to keep history for replay.
My rule: if a dataset has a stable contract and named consumers, model it in the warehouse. If it is raw, large, or still being understood, land it in the lake first and promote it only when the model earns its keep.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: