Working with Large-Scale Datasets Questions
Analyzing data that does not fit comfortably in memory or a single query. Covers distributed processing concepts, partitioning and sampling strategies, query and pipeline performance, and trade-offs when scaling an analysis. Focuses on getting correct answers efficiently at scale.
An analytics query joining a 1B row events table to user_profiles is taking 40 minutes. Show concrete optimization strategies you would evaluate (indexing, partitioning, materialized views, approximate aggregation, denormalized tables, clustering) and explain trade-offs in cost, freshness, and accuracy. Where appropriate reference Snowflake/BigQuery/Postgres differences.
Sample Answer
Start by clarifying SLA: how fresh must results be, acceptable error, and whether query is ad-hoc or repeated. Then evaluate concrete strategies with trade-offs.
- Partitioning / pruning
- Events by event_date (or ingestion_date) so engine prunes partitions.
- BigQuery: use PARTITION BY DATE(event_timestamp); Snowflake: use micro-partitions (control via clustering); Postgres: declarative RANGE partitioning.
- Trade-off: improves scan bytes (cost) dramatically; needs queries to filter on partition key (freshness = real-time if streaming supported).
Example (BigQuery):
CREATE TABLE project.dataset.events
PARTITION BY DATE(event_timestamp) AS
SELECT * FROM source;
- Clustering / sort keys
- Snowflake: cluster keys to reduce scanned micro-partitions for selective joins.
- BigQuery: clustering on user_id reduces query I/O for group-by/join on user_id.
- Postgres: BRIN/BTREE indexes or CLUSTER on column.
- Trade-off: maintenance cost on ingest (compute), extra storage; near-real-time if reclustering is deferred.
- Indexes (Postgres)
- Create B-tree on user_id in both events (if small) and user_profiles; consider covering indexes.
- Trade-off: fast seeks for selective filters but high write overhead and storage; not available in column-store clouds same way.
- Materialized views / persisted pre-joins
- Pre-join heavy aggregation: events aggregated by user_id daily, joined to profiles.
- Snowflake/BigQuery: use materialized views (Snowflake MV auto-refresh options; BigQuery materialized views have restrictions).
- Trade-off: very fast reads, cost to refresh (can be incremental); freshness lag depends on refresh schedule.
Example (Snowflake MV):
CREATE MATERIALIZED VIEW daily_user_events AS
SELECT user_id, COUNT(*) AS events
FROM events
GROUP BY user_id;
- Denormalization / summary tables
- Store user attributes with aggregated metrics in a denormalized table updated via batch/stream.
- Trade-off: simplest read performance, increased storage and ETL complexity, eventual consistency.
- Approximate aggregation / sampling
- Use APPROX_COUNT_DISTINCT, hyperloglog, or reservoir sampling for exploratory or dashboard KPIs.
- BigQuery: APPROX_COUNT_DISTINCT; Postgres: extensions (hyperloglog).
- Trade-off: huge speed/cost gains; small, quantifiable error.
- Join strategy and query tuning
- Ensure join keys are same type, use selective predicates before join, pushdown aggregations.
- Use broadcast join when user_profiles is small (force in Snowflake/BigQuery via hints or in Postgres using appropriate planner settings).
- Example: in Snowflake, set JOIN_TYPE or in BigQuery use SELECT /*+ BROADCAST_JOIN */ if supported.
- Caching and result reuse
- Use result cache (Snowflake), BI tool caching, or materialized/summary tables for repeated queries.
- Trade-off: freshness vs cost.
- Hardware / compute sizing
- Increase cluster size (Snowflake warehouse size, BigQuery slots) for large ad-hoc jobs; Postgres: more RAM/parallel_workers.
- Trade-off: higher cost for faster run.
Prioritization:
- If queries are repeated: build aggregated materialized view or denormalized summary.
- If one-off but filterable by date: partitioning + clustering.
- If approximate is acceptable: use approximate functions.
- Tune joins and consider broadcasting small table.
Measure: track bytes scanned, query profile, and refresh latency. Start with partition pruning and pre-aggregation — biggest win for a 1B row events table.
Design an ETL job to ingest daily transactions that sometimes arrive late and occasionally require backfills. Describe how you would implement idempotent upserts, watermarks for late windows, and a mechanism to reprocess backfills without double-counting. What metadata would you store to support audits?
Sample Answer
Requirements & constraints
- Daily transactions arrive in files/stream; some arrive late; occasional backfills required.
- Consumers need accurate aggregates (no double-counting) and auditable provenance.
High-level design
- Ingest raw messages into a landing table (raw_events) capturing full payload + metadata.
- Normalize/transform into a canonical transactions table via idempotent upserts into a curated table (txn_curated).
- Maintain auxiliary tables: processing_log (batch metadata) and watermark_tracker.
Idempotent upserts
- Use a stable natural key (transaction_id) or deterministic composite key (user_id, event_time, vendor_id).
- Each raw event carries: transaction_id, event_time, amount, source_batch_id, file_checksum, ingestion_time.
- Upsert pattern (pseudo-SQL):
-- txn_curated primary key: transaction_id
MERGE INTO txn_curated t
USING (SELECT * FROM staging_transactions) s
ON t.transaction_id = s.transaction_id
WHEN MATCHED AND s.source_batch_id > t.source_batch_id THEN
UPDATE SET amount = s.amount, event_time = s.event_time, source_batch_id = s.source_batch_id, last_modified = CURRENT_TIMESTAMP
WHEN NOT MATCHED THEN
INSERT (transaction_id, event_time, amount, source_batch_id, last_modified) VALUES (...)
- Use source_batch_id (monotonic per ingestion) and file_checksum to decide newer vs older; idempotency ensured by deterministic key + not re-applying same source_batch_id.
Watermarks & late windows
- Track watermark per source/topic in watermark_tracker: watermark = max(event_time) processed minus allowed_lateness.
- Allowed lateness (e.g., 48 hours) chosen by business.
- For windowed aggregates, only advance finalization of a window after watermark passes window_end + allowed_lateness. Before that, emit tentative aggregates marked as partial.
- Implementation: compute aggregates from txn_curated filtering event_time <= watermark for final windows; keep separate partial_aggregates table for in-flight windows.
Backfill & reprocess without double-counting
- Backfill runs create a new processing_log entry with backfill_id and target_date_range; they write to staging and then MERGE with higher precedence: backfill source_batch_id > normal batch ids for the range.
- To avoid double-counting:
- Use MERGE logic comparing source_batch_id / file_checksum.
- Alternatively implement soft-deletes and versioning: txn_versions table that stores every version with version_ts and active flag; reprocess marks older versions inactive and activates new one.
- For aggregates, compute from current canonical table (txn_curated active records) rather than incrementally adding counts. If incremental required, store change-delta per batch and ensure idempotent application keyed by (aggregate_id, source_batch_id).
Metadata for audits
- processing_log: source_batch_id, source_type, file_name, file_checksum, ingestion_time, processed_by, row_count, backfill_id (nullable), status.
- raw_events: ingestion_time, source_batch_id, file_checksum, raw_payload.
- txn_curated: transaction_id, event_time, amount, source_batch_id, last_modified, version_id.
- watermark_tracker: source, watermark_time, allowed_lateness, last_updated.
- txn_versions (optional): version_id, transaction_id, effective_from, effective_to, active_flag, source_batch_id.
- Aggregation_audit: aggregate_window_start, aggregate_window_end, computed_at, computed_by, source_batch_ids_used, checksum_of_input, aggregate_value.
Operational notes & best practices
- Make source_batch_id monotonic (timestamp + sequence) and apply checksums to detect exact-duplicate replays.
- Keep raw retention long enough to re-run backfills; store partitioned by ingestion_date.
- Provide idempotent CLI/API for reprocessing a backfill: it creates a new processing_log entry and runs the same pipeline; MERGE semantics ensure no double-counting.
- Monitor: failure alerts, counts comparison between raw and curated, and data-quality checks (nulls, negative amounts).
This approach gives deterministic idempotency, clear late-arrival handling via watermarks, safe backfills via versioning/precedence, and rich metadata for auditing.
A monitoring dashboard demands sub-minute latency for critical alerts, while analysts need daily aggregates. Describe an architecture to support both: ingestion (batch vs streaming), storage layers (hot/warm/cold), pre-aggregation strategy, and cost trade-offs. Suggest technologies for each layer and how to display freshness metadata on dashboards.
Sample Answer
Requirements and constraints:
- Functional: sub-minute (<=30s) critical alerts; daily aggregates and ad-hoc analyst queries.
- Non-functional: cost-conscious, durable historical storage, simple SQL access for analysts, clear freshness metadata on dashboards.
High-level architecture:
Event sources → Ingest layer (stream + micro-batch) → Streaming processor (real-time pipeline) → Hot/Warm store (for low-latency reads & alerts) → Batch/OLAP store (for daily aggregates & historical) → BI tools (Tableau/PowerBI) + Alerting/Monitoring.
Ingestion:
- Streaming (Kafka / AWS Kinesis): all events published; guarantees low latency for alerts.
- Batch/micro-batch (Airflow or Spark jobs): bulk loads from upstream sources or to backfill.
Streaming processing & alerting:
- Use stream processor (Flink / Kafka Streams / Spark Structured Streaming) to compute rolling metrics and detect alert conditions within seconds. Emit alerts to Alerting system (PagerDuty, Opsgenie) and write materialized real-time aggregates to Hot store.
Pre-aggregation strategy:
- Real-time materialized views: sliding-window aggregates (1s–1m windows) for critical metrics stored in Hot store (Redis, Druid, ClickHouse).
- Nearline/warm aggregates: 5–60 minute rollups in Warm store (ClickHouse, BigQuery with partitioned tables) for exploratory queries.
- Daily batch aggregates: scheduled jobs compute day-level summaries into Cold/OLAP (BigQuery, Snowflake, Redshift) with partitioning by date and precomputed rollups for common dimensions.
Storage layers & tech:
- Hot (<1 minute reads, ephemeral): Redis or ClickHouse for single-row/aggregate reads and alert thresholds.
- Warm (minutes-hours): ClickHouse or Cassandra for time-series rollups enabling fast ad-hoc queries.
- Cold (long-term, cost-efficient): BigQuery / Snowflake / S3 + Parquet + Athena for full-history analytics.
Cost trade-offs:
- Keep event retention in Kafka short (days) to reduce cost; persist only aggregates to long-term stores.
- Hot stores (Redis/ClickHouse) are expensive per GB—limit retention and only store derived aggregates/indices needed for alerts.
- Warm store sized for query latency vs storage cost; use compression and partitioning to lower cost.
- Cold storage on object store (S3 + Parquet) is cheapest; accepts higher query latency for deep historical analytics.
- Use compute-on-demand (serverless query engines) where interactive cost is acceptable; use scheduled materialized tables for heavy, repeated queries.
Data pipeline specifics:
- Exactly-once semantics for correctness (Kafka + idempotent sinks or Flink checkpointing).
- Schema evolution via schema registry (Avro/Protobuf).
- Backfills: batch jobs read cold store and repopulate warm/hot aggregates.
Freshness metadata on dashboards:
- Each widget shows: last_updated_timestamp and latency (event_time → processed_time). Compute and materialize these in aggregation tables; expose via SQL view.
- Color-code freshness (green <30s, yellow 30s–5min, red >5min). For daily aggregates show processing window and dataset_partition_date.
- Include lineage link to ingestion pipeline status and recent ingestion lag metrics (from Kafka consumer lag / streaming job metrics) in dashboard header.
Why this works:
- Streaming handles sub-minute urgency; pre-aggregations and tiered storage give analysts fast interactive queries at reasonable cost; explicit freshness metadata builds trust and surfaces pipeline issues quickly.
You are handed a 1TB event dataset partitioned by date in a data warehouse and need to produce an EDA summary (top-level metrics, distribution snapshots, and data-quality checks) within 24 hours. Outline an actionable plan: sampling strategy, representative SQL queries or pre-aggregation steps, compute/resource considerations, and validation to ensure rare events and seasonality are captured in your sample.
Sample Answer
Plan overview (24-hour target): split work into 4 phases — fast discovery (2–3h), targeted sampling & pre-aggregation (6–8h), full EDA reports & QA (8–12h), handoff & follow-ups (1–2h). Focus on representative sampling that preserves seasonality and rare events, use pre-aggregations to reduce compute, and validate sample fidelity.
Sampling strategy
- Hybrid stratified + reservoir approach:
- Temporal strata: sample by date granularity (day/week/month) to preserve seasonality. Always include all boundary dates (first/last day of each partition) and recent N days.
- Proportional random sampling within each stratum: reservoir or RAND() filter to get X rows/day (e.g., 1k–10k/day depending on cardinality).
- Oversample rare-event keys: identify low-frequency event types via a fast pre-aggregation and force higher sampling rate for them.
- Combined sample size aim: ~0.5–2% or ~5–20M rows depending on downstream memory.
Representative SQL / pre-aggregation patterns
- quick counts by date, event_type:
-- fast metadata: counts per day & event_type
CREATE TEMP TABLE day_counts AS
SELECT event_date, event_type, COUNT(1) AS cnt
FROM events
WHERE event_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY event_date, event_type;
- build sampling frame:
-- create per-day sample targets
CREATE TEMP TABLE sample_frame AS
SELECT event_date, SUM(cnt) AS total
FROM day_counts GROUP BY event_date;
- stratified sample (Postgres/BigQuery style with RAND):
CREATE TABLE sampled AS
SELECT * FROM events e
JOIN sample_frame f USING (event_date)
WHERE RAND() < LEAST(0.02, 10000.0 / f.total); -- cap per-day
- rare-event oversample:
CREATE TABLE rare_sample AS
SELECT * FROM events WHERE event_type IN (
SELECT event_type FROM day_counts GROUP BY event_type HAVING SUM(cnt) < 1000
) AND RAND() < 0.5;
- light pre-aggregations for dashboards:
CREATE TABLE agg_hourly AS
SELECT event_date, EXTRACT(HOUR FROM ts) AS hour, event_type, COUNT(*) AS cnt, APPROX_COUNT_DISTINCT(user_id) AS dau
FROM events
WHERE event_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY 1,2,3;
Compute/resource considerations
- Use warehouse features: partition pruning, cluster keys on event_date/event_type, query slots scaling.
- Do heavy aggregation on sample first; run full pre-aggregations incrementally (per-day) rather than full-table scans.
- Use temporary/materialized tables to avoid re-scanning.
- Monitor query concurrency and cost; limit parallelism if hitting quota.
- If memory-bound, move to iterative day-by-day aggregation and merge results.
Validation to capture rare events & seasonality
- Compare sample vs full-aggregate summaries on cheap metrics: daily total counts, event_type distributions for a random subset of days:
-- compare sample to ground truth for a small set of days
SELECT s.event_date, SUM(s.cnt) AS sample_cnt, t.total AS true_cnt
FROM sampled_summary s JOIN (
SELECT event_date, COUNT(*) AS total FROM events WHERE event_date IN ('2024-03-01','2024-07-01') GROUP BY event_date
) t USING (event_date) GROUP BY s.event_date, t.total;
- Verify tail/rare events: run targeted full scans for event_types flagged as rare to ensure they exist and check estimated frequency.
- Seasonality sanity: compute autocorrelation or compare weekday vs weekend ratios across sample and a small full scan for several weeks.
- Quantify sampling error: bootstrap sample estimates or compute confidence intervals for key metrics; if error > tolerance (e.g., 5%), increase sample.
Deliverables
- Top-level metrics: total events, DAU/MAU, unique users, conversion funnels.
- Distribution snapshots: histograms/percentiles for numeric fields (latency, revenue), event frequency heatmaps by hour/day.
- Data-quality checks: null rates, schema drift, duplicates, out-of-range values, timezone anomalies.
- Appendix: sampling methodology, validation results, cost estimates, queries to reproduce.
This plan balances speed, representativeness, and cost — start with stratified sampling + light pre-aggregations, validate against targeted full scans for rare/seasonal signals, then scale up needed queries for final reports.
Design an end-to-end analytics pipeline to measure experiments in near real-time for a product that generates 100M events per day. Include event collection, identity stitching, bucketing consistency, streaming vs batch ETL, data warehouse design, and how you'd ensure experiment assignment and metric calculation are reproducible and auditable.
Sample Answer
Requirements & constraints:
- 100M events/day (~1.2k/s avg, peaks higher), near real-time experiment reporting (minutes), reproducibility, auditable assignments and metrics.
High-level architecture:
- Event producers -> front/back-end SDKs -> streaming layer (Kafka/PubSub) -> stream processing (Flink/Beam/KStream) -> materialized aggregates + event lake -> data warehouse (Snowflake/BigQuery) + serving tables -> BI/analyst queries & dashboards.
Event collection:
- Lightweight JSON/AVRO events from SDKs with schema version, timestamp (client/server), event_id, user_ids (user_id, anon_id), device, experiment_context (optional), and signature for integrity.
- Ingest to Kafka with partitioning by event time bucket or user_id hash to keep ordering.
Identity stitching:
- Maintain a deterministic identity service in stream processor: use deterministic resolver that prefers stable IDs (user_id > login_id > cookie > device). Emit a canonical_id with provenance fields (which ids used, timestamps). Persist identity map writes to a low-latency KV store (Cassandra/Redis) for lookups and to the event-lake for audit trail. All resolution decisions are logged.
Bucketing consistency & experiment assignment:
- Calculate bucketing deterministically in the streaming layer using experiment_id, user_id canonical_id, start_time, and a stable hash function + config (seed, allocation). Store assignment records to a assignments topic and write to assignments table in warehouse (append-only) containing assignment_id, canonical_id, experiment_id, variant, config_version, timestamp, and signature.
- For deterministic repeatability, store experiment config/version in a config service and snapshot configs alongside assignments.
Streaming vs batch ETL:
- Streaming (Flink/Beam) for: identity stitching, deterministic bucketing, real-time metric increments, and writing to materialized views (e.g., metrics topic, OLAP table via Kafka connector).
- Batch for: reprocessing historical events (schema migrations, bug fixes), heavy aggregations, and complex baseline analyses. Keep raw event lake (Parquet on S3/GCS) as single source of truth.
Data warehouse design:
- Raw_events (immutable): event_id, canonical_id, raw_payload, ingestion_ts, event_ts, schema_version
- Assignments: assignment_id, canonical_id, experiment_id, variant, config_version, assigned_ts
- Metrics_facts (near real-time): date_hour, experiment_id, variant, metric_name, count, sum, unique_users_estimated (HyperLogLog) and exact_user_list when needed (for audits)
- Dimension tables: experiments (versioned), users (canonical), events_meta
- Use partitioning by date and clustering by experiment_id/variant to optimize queries.
Reproducible & auditable assignment and metric calculation:
- Immutable event lake + append-only assignments table with config_version links allow exact replay.
- Log experiment configs and seeding rules in a config store; every change gets a versioned snapshot.
- Store deterministic bucketing code in a version-controlled repo and tag deployed versions; include code version in assignment records.
- Support full replay: re-run streaming logic in batch over raw_events with the same config_version/code to reproduce results; record checksum of outputs.
- Maintain lineage metadata for every aggregated metric (SQL or DAG) that traces to raw_events and assignment_id ranges.
Monitoring & validation:
- Deploy unit/integration tests for bucketing determinism, identity merges, and metric aggregations.
- Shadow buckets and canary runs for new experiment logic.
- Drift alerts: compare streaming aggregates vs periodic batch aggregates (daily) and alert on >X% divergence.
- Sampling + store golden sample events for manual audit.
Operational notes for a data analyst:
- Provide pre-built SQL views that join assignments -> raw_events -> metrics_facts to answer "What users in variant A did X in timeframe T".
- Surface experiment meta (config_version, assignment_time) in dashboards.
- Offer reproducible notebooks that accept config_version and date range to rerun metrics from raw_events for audit.
Trade-offs:
- Streaming gives minutes-latency; batch ensures correctness for reprocessing. Keeping raw immutable lets analysts re-run and validate.
- HLL for scalable uniques, but store exact lists for small experiments/audits.
This design balances near-real-time visibility with reproducibility and auditability needed for trustworthy experiment analysis.
Unlock Full Question Bank
Get access to all 14 Working with Large-Scale Datasets interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.