RecapsKayavak

Kayavak / Recaps / Data Engineering for Analytics

Recaps · Volume 21

Data Engineering for Analytics

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

01

How Analytical Databases Work

Key ideas

  • OLTP: few rows, all columns, many concurrent writes (row stores, B-trees). OLAP: many rows, few columns, bulk writes (column stores).
  • Column storage reads only needed columns; encodings (dictionary, RLE, delta, bit-packing) plus zstd shrink them.
  • Vectorised execution and late materialisation remove per-row overhead and avoid decompressing what isn't needed.
  • Zone maps, sorting and partitioning skip data; choose sort and partition keys from common filters.
  • MPP splits work across nodes; shuffles are the expensive part.
  • Cloud warehouses separate storage (object storage) from compute; you pay for compute or bytes scanned.
  • PostgreSQL (on a replica) is enough for modest analytics; move when reports hurt the product or sources multiply.

Numbers to remember

  • Lab: 5M orders: CSV 465 MB, PostgreSQL 558 MB, Parquet zstd 34 MB.
  • Monthly revenue: PostgreSQL 758 ms vs DuckDB 81 ms; point lookup: PostgreSQL PK 0.06 ms vs DuckDB 0.9 ms.

Glossary

  • OLTP / OLAP: transactional / analytical processing.
  • Column chunk / row group: Parquet's per-column data within a horizontal slice of rows.
  • Zone map: min/max statistics per block, used to skip blocks.
  • Vectorised execution: operators processing batches of values.
  • Shuffle: redistributing rows across nodes by key.

02

Modelling Data for Analysis

Key ideas

  • Facts at a declared grain with measures; dimensions with descriptive attributes; star schemas; conformed dimensions; surrogate keys.
  • Transaction, periodic snapshot and accumulating snapshot facts.
  • Additive, semi-additive and non-additive measures.
  • SCD types 0/1/2/3; point-in-time joins for type 2.
  • Layers: raw → staging → intermediate → marts; wide tables and semantic layers built on top.
  • Double-counting traps: fan-out, many-to-many, duplicates, mixed grains.

Numbers to remember

  • Lab: type 1 moved ₹9 lakh of Q1 revenue to the wrong area; fan-out doubled revenue (₹72.4 lakh → ₹1.45 crore).

Glossary

  • Grain: what one fact row represents.
  • Star schema: a fact table joined to dimension tables.
  • SCD: slowly changing dimension.
  • Surrogate key: a warehouse-generated identifier for a dimension row/version.
  • Semantic layer: shared metric definitions.

03

Batch Processing and Spark

Key ideas

  • Map (local, parallel) → shuffle (expensive) → reduce.
  • Spark: driver, executors, partitions, lazy logical plans, Catalyst, stages split at shuffles, one task per partition.
  • Narrow vs wide transformations; count your shuffles.
  • Joins: broadcast (small side), sort-merge (default for large), shuffle hash, bucketed.
  • Skew: one key, one partition; fix with broadcast, AQE, salting, separate handling.
  • Partition sizing, spills, caching with care, no collect() on big data.
  • Partitioned, sorted Parquet output with controlled file sizes; idempotent partition overwrites.
  • Don't use Spark when one machine or the warehouse suffices.

Numbers to remember

  • Lab: sort-merge 1.70 s vs broadcast 0.60 s; skew: largest partition ~50% regardless of partition count; bound 32.5× at 64 partitions.
  • Defaults: auto-broadcast 10 MB; 200 shuffle partitions; ~128 MB input splits.

Glossary

  • Stage: a set of tasks between shuffles.
  • Catalyst: Spark's query optimiser.
  • AQE: adaptive query execution.
  • Salting: splitting a hot key with random suffixes.
  • Spill: writing intermediate data to disk when memory is short.

04

Transformations as Code: ELT and dbt

Key ideas

  • ELT: load raw, transform in the warehouse; raw stays for reprocessing.
  • dbt: models as SELECTs; source() and ref() build the graph; dbt build runs models and tests in order and skips downstream of failures.
  • Materialisations: view, table, incremental (idempotent strategy + lookback), ephemeral.
  • Snapshots capture type 2 history from raw sources.
  • Tests: generic, singular, unit, contracts; severity thresholds.
  • Docs and lineage for tracing numbers; macros and packages for reuse.
  • Per-developer schemas; slim CI (state:modified+); orchestrated production runs with freshness checks.

Numbers to remember

  • Lab: 37 duplicated payments → unique test failed → revenue model skipped; ₹8,778 of phantom revenue avoided.
  • Incremental 1.12 s vs full 1.6 s, because staging still processed everything.

Glossary

  • Model: a dbt SELECT materialised as a view or table.
  • Materialisation: how dbt builds a model.
  • Snapshot: dbt's type 2 history capture.
  • Lineage: the graph from sources to models to exposures.
  • Slim CI: building only changed models and dependents.

05

Orchestration and Backfills

Key ideas

  • Orchestrators run DAGs of tasks or assets on schedules or data events, with retries, timeouts and alerts.
  • Tasks process the period they're given, never the clock.
  • Every task idempotent: replace partitions, delete+insert, merge; deterministic reads.
  • Retries only for idempotent tasks; SLAs on freshness, not just failures.
  • Backfills: idempotency, concurrency limits, order, cost, communication.
  • Sensors and data-aware scheduling stop late inputs from producing wrong outputs.
  • The orchestrator schedules; the warehouse, Spark or containers compute.

Numbers to remember

  • Lab: 30-day backfill, 30% post-write failures: append +53% orders; overwrite exact.

Glossary

  • DAG: directed acyclic graph of tasks.
  • Data interval / partition key: the period a run processes.
  • Backfill: rerunning past periods.
  • Catch-up: automatically running missed intervals.
  • Sensor: a task that waits for an external condition.

06

Stream Processing

Key ideas

  • Event time for correctness; processing time only for pipeline metrics; record both.
  • Windows: tumbling, sliding, session, global with triggers.
  • Watermarks trade latency for completeness; allowed lateness with upserts gets both; side outputs for the very late; batch as the safety net.
  • State per key, checkpointed with offsets; exactly-once needs transactional or idempotent sinks; bound state with TTLs.
  • Joins: stream–table, windowed stream–stream, temporal.
  • Engines: Flink, Kafka Streams, Spark Structured Streaming, streaming databases; real-time OLAP for serving.

Numbers to remember

  • Lab: processing-time worst window error 90%; watermark lag 0 s → 6.2% first-result error, 120 s → 1.6%; lateness with updates → 0.0% final.

Glossary

  • Watermark: the event-time point before which no more events are expected.
  • Allowed lateness: how long window state is kept to apply late events.
  • Side output: a separate stream for events too late to apply.
  • Checkpoint: a consistent snapshot of state and input positions.
  • Backpressure: slowing producers when consumers fall behind.

07

Lakehouses and File Formats

Key ideas

  • Lakehouse: open files in object storage + a table format + a catalog; many engines, one copy.
  • Parquet: row groups, column chunks, pages, encodings, footer statistics; readers fetch only needed byte ranges.
  • Partition by common low-cardinality filters (date); sort within for statistics; measure compression effects.
  • Small files: write larger, compact, partition less finely.
  • Table formats: atomic commits via catalog pointer swaps, snapshots, time travel, schema and partition evolution, row-level deletes (copy-on-write or merge-on-read), maintenance.
  • Bronze/silver/gold = raw/cleaned/modelled.

Numbers to remember

  • Lab: sorted file read 2 of 50 row groups (7 ms vs 103 ms); 2,000 files 262 ms vs 1 file 29 ms; rollback restored 41,094 rows.
  • Target file sizes ~128 MB–1 GB.

Glossary

  • Row group: a horizontal slice of a Parquet file with per-column chunks.
  • Manifest: Iceberg metadata listing data files and their statistics.
  • Snapshot: a committed version of a table.
  • Copy-on-write / merge-on-read: strategies for row-level changes.
  • Catalog: the service mapping table names to current metadata.

08

Data Quality, Contracts and Observability

Key ideas

  • Pipelines can succeed with wrong data; check the data.
  • Dimensions: freshness, volume, completeness, uniqueness, validity, consistency, accuracy, distribution, schema.
  • Check at ingestion, in transformations, before publishing; severities and owners.
  • Seasonality-aware, robust, tuned anomaly detection.
  • Data contracts owned by producers, enforced in producers' CI.
  • Lineage (OpenLineage, dbt) for impact and root cause.
  • Circuit breakers keep the last good data; data incidents get postmortems; data SLOs measure trust.

Numbers to remember

  • Lab: 5 of 5 failures caught, 0 false alarms; "row count > 0" caught 0; same-weekday baseline detects 14% drops vs 32% for a plain trailing baseline.

Glossary

  • Data contract: a versioned agreement on schema, semantics, quality and freshness.
  • Circuit breaker: blocking publication when checks fail.
  • Lineage: which jobs read and wrote which datasets (and columns).
  • Reconciliation: comparing totals with the system of record.
  • Data SLO: a target for freshness and quality of a dataset.

09

Governance, Privacy and Cost

Key ideas

  • Roles from identity groups; least privilege; row-level security; column masking; catalog policies across engines; audited access.
  • Personal data: minimise, pseudonymise with keyed HMAC or tokens, restrict, aggregate; pseudonymised is still personal.
  • Retention per dataset; erasure across every copy, including lakehouse history (delete, compact, expire snapshots).
  • Owners, descriptions, sensitivity tags and certification in a catalog.
  • Cost: bytes scanned, compute time, storage; prune, materialise wisely, separate compute, attribute, budget, review top queries.

Numbers to remember

  • Lab: bytes read 100% → 13% (partitioned month) → 2% (+3 columns); MD5 pseudonym reversed in 40 ms.

Glossary

  • Row-level security: per-user row filtering.
  • Dynamic masking: role-dependent transformation of column values.
  • Pseudonymisation: replacing identifiers with keyed or tokenised references.
  • Anonymisation: making re-identification impossible (rarely achieved).
  • Chargeback / showback: assigning or showing platform costs to teams.