Skip to content

Big Data Architectures: 3Vs, Batch vs Stream, Lambda & Kappa ​

"These days, my advice is to use a batch processing framework like MapReduce if you aren't latency sensitive, and use a stream processing framework if you are, but not to try to do both at the same time unless you absolutely must." — Jay Kreps, Questioning the Lambda Architecture, O'Reilly Radar, 2 July 2014

Summary: A "big data architecture" is a way to move facts out of the operational database, keep them cheaply, transform them in batches or streams, and serve answers fast enough; the whole discipline is choosing how fresh, how exact, how simple and how expensive that path must be. Focus: The Vs (volume, velocity, variety, veracity, value), OLTP versus OLAP, batch (MapReduce, Spark, ELT with dbt), stream (event time, windows, watermarks, state, exactly-once, Flink, Kafka Streams), Lambda, Kappa, the unified Dataflow/Beam model, lake, warehouse and lakehouse, CDC with Debezium, data mesh, serving stores (ClickHouse, Pinot, Druid), ML features, governance, cost, and one order-analytics example built three ways with Go and Laravel. Learning goal: Given a reporting or analytics requirement, decide whether it needs a nightly batch, a stream, or both; draw the path from the OLTP database to the answer; and start with the smallest design (PostgreSQL + CDC + a warehouse) instead of the fashionable one.

This chapter is the "data" style in the Architecture Styles group of the Architecture path. It explains the moving parts and the decisions; it does not re-teach what sibling chapters own. The row-store versus column-store mechanics live in OLTP vs OLAP & Columnar Storage; CDC and the outbox are in Change Data Capture and Outbox Pattern; the stream-processing operators are in Stream Processing; how pipelines compose is in Pipe-and-Filter; and the style vocabulary is in Styles vs Patterns. Related system-level chapters: ML Systems and Search Systems.

Page map ​

If you are looking forGo to
The whole chapter in a few tablesEverything in one minute
Why big-data architecture existsWhy it exists
Laney 2001, MapReduce, Marz, Kreps, Dataflow, Lakehouse, MeshWhere it comes from
Volume, velocity, variety, veracity, valueThe five Vs
Why you do not run reports on the order databaseOLTP vs OLAP
Nightly jobs, MapReduce, Spark, warehouses, dbtBatch processing
Event time, windows, watermarks, state, Flink, Kafka StreamsStream processing
At-least-once, exactly-once, idempotent sinksDelivery semantics
Batch + speed + serving layers, code duplicationLambda
One log, replay, when it failsKappa
Dataflow model, Beam, "unbounded vs bounded"Unified models
Lake, warehouse, lakehouse, Parquet, Iceberg, DeltaStorage tiers
Debezium, WAL, snapshots, outboxCDC
Data mesh versus a central platformData mesh
ClickHouse, Pinot, Druid, pre-aggregationServing analytics
Feature pipelines for MLML features
Schemas, lineage, PII, retentionGovernance
Cost and operational complexityCost
Go and Laravel codeGo, Laravel
Order analytics as batch, Lambda, KappaWorked example
Monolith to distributed scaleIn architecture
Hands-on exerciseLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
VolumeHow much data2 million orders a day, 700 million a yearReports on the live database slow the shop down
VelocityHow fast it arrives and how fast answers are needed300 orders a second at peak, dashboard fresh within 10 sYesterday's numbers during a flash sale
VarietyMany shapes of dataRows, JSON events, logs, images, CSV from partnersOne rigid schema rejects half the sources
VeracityHow far you can trust itDuplicate events, clock skew, botsConfident dashboards that are wrong
ValueWhat the answer is worthChurn prediction pays for the pipeline, or does notA costly platform nobody uses
OLTPMany small transactions that change dataINSERT INTO ordersMixing it with scans stalls checkout
OLAPFew big queries that read lots of dataRevenue by country by dayAnalytics fight for the same locks and cache
BatchProcess a bounded set, then stopNightly "yesterday's orders"Not fresh; but simple and exact
StreamProcess an unbounded flow as it arrivesOrders per minute, liveComplex: time, state, late data
Event timeWhen it happenedOrder placed 10:00:50Wrong windows after a delay
Watermark"No older event will arrive" claimNewest 10:02:10 minus 30 sWindows never close, or close too early
LambdaBatch layer plus speed layer, merged at queryNightly truth plus last-hours incrementTwo codebases that disagree
KappaOne stream job, replay the log to fix historyRerun from offset 0 into a new tableNeeds long retention and a fast replay
CDCTurn database changes into eventsDebezium reads the PostgreSQL WALDual writes and polling updated_at
LakehouseWarehouse features on open files in object storageIceberg tables of Parquet filesTwo copies of data and ETL between them
Data meshDomain teams own analytical data as productsorders team publishes orders_dailyA central team becomes the bottleneck

The four paths from "an order happened" to "an answer".

PathFreshnessComplexityTypical toolsStart here when
Read replica + SQLsecondslowestPostgreSQL replica, materialized viewData under about 1 TB, few analysts
Nightly batch ELThours to a daylowLaravel command or Airflow, dbt, warehouseReports are daily or weekly
CDC + warehouseminutesmediumDebezium, Kafka, ClickHouse or BigQueryDashboards need minutes, source stays OLTP
Stream processingseconds or lesshighKafka, Flink, Kafka Streams, PinotAlerts, fraud, live counters

Lambda, Kappa and "just batch" at a glance.

Batch onlyLambdaKappa
Code paths12 (batch and speed)1
Freshnesshoursseconds plus hours-accurateseconds
Fix a bug in historyrerun the jobrerun the batch layerreplay the log
Needs a long-retention lognohelpsyes (or lake replay)
Main riskstale datatwo implementations driftreplay cost and ordering

Why it exists ​

An operational database is tuned for many tiny transactions: look up one customer, insert one order. Questions like "revenue per country per hour for two years" read millions of rows, hold resources for minutes and want a different layout on disk. Running them on the production database hurts the shop. So organisations copy data out to a system built for scanning, and then discover three more problems: the data arrives continuously, it comes in many formats, and different consumers want different freshness. A big-data architecture is the answer to "where does the data go, in what shape, how fresh, and who maintains it".

Simpler (fewer moving parts)Richer (fresher, bigger, more flexible)
Nightly batch into a warehouseStreaming with event time, state and replay
One storage systemLake plus warehouse plus serving store
Central data teamData mesh with domain ownership
Exact results next morningApproximate or revisable results in seconds
Cheap, easy to debugExpensive, many failure modes

The analogy we reuse: a water system. Rain falls continuously (events). A reservoir stores it (lake). A treatment plant cleans it into one standard (warehouse). Pipes carry it to taps (serving). You can treat water in big batches overnight, or filter continuously as it flows; a town of 5,000 people does not build the plant of a metropolis.

Three common misunderstandings, up front ​

  1. "Big data means Hadoop and Spark." Big data is a problem shape (data that does not fit one machine or one query budget), not a product list. Most product teams never need a cluster; PostgreSQL plus a column store covers a surprising range.
  2. "Streaming is better than batch." It is faster, not better. Kreps' own advice is batch when you are not latency sensitive and stream when you are, "but not to try to do both at the same time unless you absolutely must".
  3. "Lambda or Kappa is the architecture; pick one." They are two answers to one question (how do I get both fresh and correct results and still reprocess history?). Many systems need neither.

Where it comes from ​

Laney, 2001. Doug Laney, then at META Group, published 3D Data Management: Controlling Data Volume, Velocity, and Variety (Application Delivery Strategies, file 949, 6 February 2001). We read the PDF (via the Internet Archive copy): it names three dimensions and explains each from the e-commerce angle; on volume it says e-channels can mean "up to 10x the quantity of data about an individual transaction may be collected". The note never says "big data". Veracity and value are later additions by industry vendors and authors; they are not in Laney's note.

MapReduce and GFS, 2003 to 2004. Google's papers The Google File System (SOSP 2003) and MapReduce: Simplified Data Processing on Large Clusters (Dean and Ghemawat, OSDI 2004) described batch processing on cheap machines; Hadoop (2006) was the open-source follow-up. Spark (UC Berkeley, 2009 onwards) kept data in memory between steps. We cite these from memory of the papers; they are context, not quotes.

Marz, 2011. Nathan Marz's post How to beat the CAP theorem (13 October 2011) proposed the Lambda architecture: keep an immutable master dataset, recompute views from it in a batch layer, and compensate for the last few hours with a realtime layer. His central argument: "Since a query is a function of all the data, the easiest way to make queries run fast is to precompute them." and "To resolve a query function, you query the batch view and the realtime view and merge the results together to get the final answer."

Kreps, 2014. Jay Kreps (LinkedIn, Kafka and Samza) wrote Questioning the Lambda Architecture (2 July 2014). He credits Lambda for two things (keep the input unchanged; reprocessing is a real requirement) and attacks two things: "maintaining code that needs to produce the same result in two complex distributed systems is exactly as painful as it seems like it would be", and the claim that it "beats the CAP theorem". His alternative, which he jokes might be called "the Kappa Architecture", is one stream job and a retained log.

Akidau et al., 2015. The Dataflow Model paper (The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing, VLDB 2015) argued that "streaming versus batch" is a property of the engine, not of the data: "unbounded datasets have been processed using repeated runs of batch systems since their conception, and well-designed streaming systems are perfectly capable of processing bounded data." It became Apache Beam.

Lakehouse, 2021. Armbrust, Ghodsi, Xin and Zaharia (CIDR 2021) argued that "the data warehouse architecture as we know it today will wane in the coming years and be replaced by a new architectural pattern, which we refer to as the Lakehouse", built on "open direct-access data formats, such as Apache Parquet and ORC".

Data mesh, 2019 to 2020. Zhamak Dehghani's article (Martin Fowler's site, 3 December 2020) states four principles: "domain-oriented decentralized data ownership and architecture, data as a product, self-serve data infrastructure as a platform, and federated computational governance."

OLTPGo / LaravelPostgreSQL+ WALCDCDebezium+ Kafka+ outboxLakeParquet filesIceberg / DeltaWarehouseBigQuery, ClickHousestaging tablesTransformdbt (ELT)Flink / SparkmartsServingClickHouse / Pinotproduct dashboardsBI and MLreports, features,training data

The picture is the reference flow of the whole chapter: operational databases emit changes through CDC, storage tiers keep them, transformation shapes them, and a serving layer answers. Everything else is a choice about which boxes you need.

The five Vs ​

Volume Must-know ​

In plain words: how much data, and the point where one machine or one query budget stops being enough.

Common misunderstanding: "Big data starts at a terabyte." There is no number; it starts when your current tool cannot answer in the time you need. A well-indexed PostgreSQL handles many terabytes of OLTP; a poorly shaped 50 GB scan can still hurt.

Definition: data volume is the quantity of data to store and process, which drives storage design (partitioning, compression), compute (parallelism) and cost (see Storage & Data Scaling and Billion-Row Tables).

1  2,000,000 orders/day x 1 KB          = 2 GB/day raw
2  x 365 days                           = 730 GB/year
3  columnar + zstd (about 5-10x)        = 75-150 GB/year in the warehouse
4  one year fits one ClickHouse node; ten years is still a small cluster

Real scenario: a retailer with 2 million orders a day does not need a data lake for orders alone; clickstream (100x more rows) is what pushes it into object storage.

What provides it: partitioning by date, columnar compression, object storage, distributed engines.

Fix: measure first with capacity estimation.

Velocity Must-know ​

In plain words: how fast data arrives, and how soon someone needs the answer.

Common misunderstanding: "High velocity means I need a stream processor." Velocity of ingestion and freshness of answers are two different dials. A million events a minute can be loaded in micro-batches every five minutes and nobody notices.

Definition: ingestion rate (events per second) and required freshness (the latency from event to visible answer).

1  event happens         10:00:00
2  lands in Kafka        10:00:00.2   (ingest velocity)
3  visible on dashboard  10:00:08     (freshness: 8 s)
4  nightly report        next day 02:30 (freshness: hours)

Real scenario: fraud scoring needs milliseconds; a finance dashboard needs yesterday; a stock-level widget needs 10 seconds.

What provides it: Kafka for ingest, Flink or Kafka Streams for sub-second, micro-batches for minutes.

Fix: write the freshness requirement as an SLO per consumer (see SLAs, SLOs, SLIs) before choosing an engine.

Variety Important ​

In plain words: data comes in different shapes: tables, JSON, logs, images, partner CSV files, clickstream.

Common misunderstanding: "Schemaless means no schema work." Someone still decides the structure; schema-on-read just moves that decision to the reader and the day of the bug.

Definition: heterogeneity of formats and structures. Laney called it the third dimension and tied it to integration of many sources.

Real scenario: the order table has columns; the mobile app sends JSON events; a partner sends daily CSV; support exports PDFs. Each needs an ingestion adapter and a schema contract (Message Design & Schema Evolution).

What provides it: schema registry with Avro or Protobuf, a raw landing zone in object storage, transformation into typed tables.

Fix: land raw, then model: keep the original bytes, and build typed tables in the warehouse.

Veracity Important ​

In plain words: can you trust the data? Duplicates, missing events, wrong clocks, bots and bugs all damage it.

Common misunderstanding: "More data averages out the errors." Systematic errors (a timezone bug, double-counted retries) do not average out; they scale.

Definition: the quality and trustworthiness of data. It is an industry addition to the three Vs.

1  producer sends OrderPlaced #42
2  network timeout, producer retries
3  broker stores #42 twice (at-least-once)
4  dashboard counts 2 orders, revenue doubled
5  fix: event_id + idempotent upsert / dedupe window

Real scenario: a retry doubles revenue on a dashboard the CFO reads; a phone with a wrong clock sends events dated 1970.

What provides it: idempotency keys, schema validation, data tests (dbt unique, not_null), reconciliation counts against the source.

Fix: put one reconciliation query in every pipeline: source row count versus warehouse row count per day.

Value Good to know ​

In plain words: the answer must be worth the cost of producing it.

Common misunderstanding: "Collect everything now, find value later." Storage is cheap, but governance, privacy and engineers are not.

Definition: the business benefit of a dataset or pipeline, which should be compared with its running cost and risk.

Real scenario: a real-time geo-heatmap that nobody opens costs more than the nightly sales report that finance reads daily.

Fix: every dataset gets an owner and a named consumer; no consumer for two quarters means retire it.

VQuestion it asksFirst tool to reach forTypical failure
VolumeDoes it fit one box and one query budget?Partitioned PostgreSQL, then a column storeScanning the OLTP database
VelocityHow fresh must the answer be?Micro-batch before streamStreaming a report read weekly
VarietyHow many shapes and sources?Raw landing zone plus schema registryRigid schema rejecting sources
VeracityCan I trust it?Idempotency, data tests, reconciliationWrong numbers with confidence
ValueWho uses it and what is it worth?A named consumer per datasetPlatform without users

OLTP vs OLAP ​

OLTP and OLAP Must-know ​

In plain words: OLTP (online transaction processing) is the shop counter: many small reads and writes. OLAP (online analytical processing) is the accountant at month end: a few huge reads over many rows.

Common misunderstanding: "A read replica solves analytics." It removes load from the primary, but a row-store replica still reads whole rows for a one-column aggregate, and long queries on a replica can conflict with replication (see Replication & Failover). It is a good first step, not the end state.

Definition: OLTP optimises latency of point lookups and short writes with ACID guarantees; OLAP optimises throughput of scans and aggregates, usually on columnar storage with compression. The mechanics (row versus column layout, vectorised execution, zone maps) are taught in OLTP vs OLAP & Columnar Storage. ClickHouse's docs describe it as "a column-oriented SQL database management system (DBMS) for online analytical processing (OLAP)".

1  Checkout (OLTP)      SELECT * FROM orders WHERE id = 1001      -- 1 row, 0.3 ms
2  Analyst (OLAP)       SELECT country, SUM(total_cents)          -- 700M rows, 2 columns
3                       FROM orders GROUP BY country              -- columnar reads 2 of 12 columns
4  Same server: step 2 evicts the cache, step 1 slows down

Real scenario: a marketing export runs for 40 minutes on the primary at 09:00; checkout p99 triples; the incident review recommends a warehouse.

AxisOLTPOLAP
Query shapePoint lookup, short writeScan, aggregate, join of facts and dimensions
Rows per query1 to 100millions to billions
Storage layoutRow-oriented pages (heap, B-tree)Column-oriented, compressed
Concurrencythousands of small transactionstens of heavy queries
Consistency needStrong, serialisable where neededSnapshot per query; eventual vs source
ExamplesPostgreSQL, MySQL/InnoDB, SQL Server, OracleClickHouse, BigQuery, Redshift, Snowflake, DuckDB
Freshness vs sourcecurrentminutes to a day behind

Fix, in order of cost.

sql
-- 1) On the same PostgreSQL: a materialized view refreshed nightly
CREATE MATERIALIZED VIEW sales_daily AS
SELECT date_trunc('day', placed_at) AS day, country,
       count(*) AS orders, sum(total_cents) AS revenue_cents
FROM orders
WHERE status <> 'cancelled'
GROUP BY 1, 2;
CREATE UNIQUE INDEX ON sales_daily (day, country);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;

When this stops being enough (refresh takes too long, queries need history beyond what you keep, or other sources must join), move to a warehouse. The Go and Laravel roles are in Go and Laravel.

Batch processing ​

Batch processing Must-know ​

In plain words: collect data for a period, then process the whole bounded pile in one run, and stop.

Common misunderstanding: "Batch is legacy." Most company reporting still runs as batch, and its exactness, easy reruns and simple failure model are real virtues.

Definition: a job over a bounded input (a day of orders, a file set) that produces output and terminates. Failure handling is "fix and rerun". MapReduce formalised it as a map phase, a shuffle that groups by key, and a reduce phase; Spark replaced disk between steps with in-memory resilient datasets and a DAG of transformations.

1  02:00 scheduler starts job for 2026-11-24
2  extract: read orders where placed_at in the day
3  transform: dedupe, join customers, aggregate
4  load: replace partition day=2026-11-24
5  02:40 success; if step 3 failed, rerun from step 1 with the same inputs

Real scenario: a nightly settlement report, monthly billing, a weekly recommendation model refresh, the daily sales mart.

What provides it: scheduler (cron, Laravel scheduler, Airflow), engine (Spark, warehouse SQL), idempotent writes (overwrite a partition, or upsert on a key).

ConceptMeaningWhy it matters
Bounded inputFinite dataset known at startYou can compute exact results
Idempotent runSame input gives the same output, rerun is safeRetry without fear
Partition overwriteReplace day=... as a unitNo half-written day visible
BackfillRerun for past datesFixing a bug in history
ShuffleRedistribute rows by key across machinesThe expensive step of joins and group-bys
DAGDependency graph of stepsAirflow, Spark, dbt all model it

ETL vs ELT and dbt Must-know ​

In plain words: ETL transforms before loading; ELT loads the raw data first and transforms inside the warehouse with SQL.

Common misunderstanding: "ELT means no modelling." The modelling moved into SQL files that live in version control; dbt turns them into tested, documented dependency graphs.

Definition: with ELT, extract and load copy source tables as-is (a staging layer), then SQL transformations build marts. dbt (the docs say "dbt transforms raw warehouse data into trusted data products") compiles select statements into tables or views, runs tests and tracks dependencies through ref().

1  extract    Laravel command copies orders to stg_orders (raw)
2  load       upsert by primary key, idempotent
3  transform  dbt model fact_orders_daily = select day, country, sum(...) from stg_orders
4  test       unique(day, country), not_null(revenue_cents)
5  publish    BI reads fact_orders_daily
sql
-- dbt model: models/marts/fact_orders_daily.sql (reads staging, builds a table)
select
    date(placed_at)                as day,
    country,
    count(*)                       as orders,
    sum(total_cents)               as revenue_cents
from {{ ref('stg_orders') }}
where status <> 'cancelled'
group by 1, 2
StyleTransform whereStrengthWeakness
ETLIn a pipeline server before loadSensitive data cleaned before storagePipeline code is the bottleneck
ELTIn the warehouseScales with the warehouse, SQL, reruns easyRaw sensitive data lands first (mask it)
Reverse ETLWarehouse back to SaaS toolsActivates analyticsAnother sync to monitor

Modelling the warehouse. A star schema puts one fact table (one row per order line, with measures such as total_cents) in the middle and dimension tables (customer, product, date, country) around it; a slowly changing dimension (SCD type 2) keeps history by adding a new row with validity dates when an attribute such as a customer's country changes. Raw staging, cleaned intermediate models and business marts are the usual three layers in a dbt project.

Stream processing ​

Stream processing Must-know ​

In plain words: process each event as it arrives and keep a running answer, instead of waiting for the day to end.

Common misunderstanding: "A stream is a fast batch." It is a different problem: input is never complete, events arrive late and out of order, and the job keeps state for months.

Definition: continuous computation over an unbounded dataset. Flink's documentation notes that "streams are in general infinite (unbounded)". The Dataflow paper says to prefer unbounded/bounded for data and to reserve streaming/batch for engines. Operators and their ordering rules are in Stream Processing.

1  OrderPlaced arrives         key=order 1001
2  job updates state           orders_this_minute[DE] += 1
3  window closes (watermark)   emit (10:00, DE, 12 orders, 59 EUR)
4  sink upserts the result     idempotent by (window, country)
5  checkpoint saves offsets+state so a crash resumes here

Real scenario: fraud rules, live inventory, alerting on error rates, per-minute order counts, session analytics.

EngineModelStateStrengthPick when
Apache FlinkTrue streaming, event time firstManaged keyed state, checkpointsLow latency, rich windowingHeavy stateful streaming
Kafka StreamsA Java library inside your appState stores backed by changelog topicsNo cluster to run beyond KafkaJVM team, Kafka-centric
Spark Structured StreamingMicro-batches (and continuous mode)State in the Spark engineSame API as batch SparkYou already run Spark
Apache BeamPortable model, runs on Flink, Spark, DataflowPer runnerOne program, many runnersCloud Dataflow or portability
ksqlDBSQL over KafkaKafka-backedQuick SQL streamsSQL-first teams
Go consumer (franz-go)Hand-written loopIn memory or your storeTiny and explicitSimple windows, see Go
Laravel queue workerJob per messageDatabase or cacheFamiliarLow-volume reactions, not windows

Event time, processing time, windows and watermarks Must-know ​

In plain words: event time is when the thing happened; processing time is when your job saw it. Phones go offline, so they differ. A window groups events by event time; a watermark says how far event time has "safely" progressed.

Common misunderstanding: "Use the arrival timestamp; it is simpler." Then a one-hour network outage moves 10,000 orders into the wrong hour and every hourly total is wrong, in a way you cannot reproduce on replay (processing time changes on every run).

Definition: the Flink docs say the mechanism "to measure progress in event time is watermarks". A watermark W(t) declares that no more events with event time at or below t are expected. A window fires when the watermark passes its end. Events behind the watermark are late: drop them, update the emitted result (allowed lateness), or send them to a side output.

1  event A  event_time 10:00:10  arrives 10:00:11
2  event B  event_time 10:01:10  arrives 10:01:11   watermark 10:00:40 (newest - 30 s)
3  event C  event_time 10:00:50  arrives 10:01:20   out of order, still before window end 10:01:00 + watermark rule
4  event D  event_time 10:02:10  arrives 10:02:11   watermark 10:01:40, window 10:00 closes: A + C
5  event E  event_time 10:00:20  arrives 10:02:30   late: window 10:00 is closed
event time (when the order really happened) - windows of 1 minutewindow 10:00window 10:01watermark = newest - latenessfilled: on time, warning: out of order but kept, red: too late (dropped or side output)window 10:00 closes when the watermark passes its right edge
Window typeShapeExampleProduct
TumblingFixed, no overlapOrders per minuteFlink, Kafka Streams, Beam
Sliding (hopping)Fixed size, advances by a smaller stepLast 10 minutes, every minuteFlink, Kafka Streams, Beam
SessionCloses after an inactivity gapA user visitFlink, Beam
GlobalOne window for all, with triggersRunning totalBeam, Flink
Late-data policyWhat happensCost
DropIgnore events behind the watermarkUnder-count, simple
Allowed latenessKeep the window state a while, re-emit updatesState memory, downstream must accept updates
Side outputRoute late events to a separate streamReconcile in batch later
Bigger watermark delayWait longer before closingHigher latency for all

The Go example in Go shows these rules in about 80 lines. In Flink you set the delay with WatermarkStrategy.forBoundedOutOfOrderness(Duration), which the Flink docs list for generating watermarks.

State and checkpoints Important ​

In plain words: "orders so far this minute" is state; if the job crashes, the state must come back exactly as it was.

Common misunderstanding: "State lives in memory, so a crash loses it." Engines snapshot it. Flink's docs describe stream barriers injected at the sources as the core of distributed snapshotting, and recovery means restoring operator state and replaying records from the checkpoint. Kafka Streams backs state stores with changelog topics.

Definition: state is data a streaming operator remembers between events; a checkpoint is a consistent snapshot of all state plus source offsets.

1  source reads offsets 100..199, operators update state
2  barrier n flows through the graph; each operator snapshots state
3  job crashes at offset 230
4  restart: restore snapshot n, source rewinds to offset 200
5  records 200..230 are processed again (state is consistent)

Real scenario: a session window job with 50 million open sessions; state size, not CPU, decides the cluster.

Fix: keep state small (aggregate, do not store raw events), set a TTL, and test restore time.

Mechanics: delivery semantics and exactly-once ​

At-least-once, exactly-once and idempotent sinks Must-know ​

In plain words: a retry can deliver a message twice, so "exactly once" really means "counted once in the result".

Common misunderstanding: "Exactly-once delivery exists end to end." The network cannot give it; what exists is exactly-once processing effect: at-least-once delivery plus either transactional writes or an idempotent sink. Full treatment: Delivery Guarantees and Idempotent Consumers.

Definition: Kafka offers idempotent producers and transactions; Flink gives exactly-once state through checkpoints and uses two-phase-commit sinks for external systems; Kafka Streams enables it through the processing.guarantee setting (value exactly_once_v2 in current releases; we did not re-fetch this page in this session, so check the Kafka docs for your version).

1  consumer reads offset 41, writes row to warehouse
2  crash before committing offset 41
3  restart: reads offset 41 again, writes the same row again
4  idempotent upsert on (order_id): the second write changes nothing
5  commit offset 41
SinkHow to get an effect-once result
PostgreSQL / warehouseINSERT ... ON CONFLICT DO UPDATE keyed by event id
ClickHouseReplacingMergeTree keyed by event id (merges later), or dedupe tokens on insert
Object storage (Parquet)Write to a temporary name, atomic rename or table commit (Iceberg, Delta)
Kafka topicTransactions with read_committed consumers
Search / cacheIdempotent document id

Lambda architecture ​

Lambda Must-know ​

In plain words: run a slow, exact batch job over all history and a fast, rough stream job over the last few hours; when someone asks a question, combine both answers.

Common misunderstanding: "Lambda beats the CAP theorem" (the title of Marz's post). Kreps replied that the system is asynchronous: "the results being computed are not kept immediately consistent with the incoming data. The CAP theorem, sadly, remains intact." Lambda trades consistency for latency in a managed way; it does not abolish the trade.

Definition: three layers over an immutable master dataset. The batch layer recomputes batch views from all data. The speed layer computes realtime views for data not yet in a batch view. The serving layer indexes views and merges them on query. Marz: "Any data older than a few hours has already been incorporated into the batch views, so all that's left to do is compensate for the last few hours of data."

Immutableevent logBatch layerrecompute ALL datahours, exact, simpleSpeed layeronly the recent hoursseconds, incrementalBatch view(old data)Realtime view(last hours)Servingmerge onquerysame logic written twice
1  10:00 query "orders today"
2  batch view   (computed 02:00)   covers 00:00 to 01:59 -> 41,200 orders
3  realtime view (since 02:00)     covers 02:00 to 10:00 ->  9,830 orders
4  serving layer merges: 41,200 + 9,830 = 51,030
5  next batch run absorbs 02:00 to 09:59; realtime view for that range is discarded

Real scenario: Marz's own stack is Hadoop for the batch layer and Storm with Cassandra for the realtime layer; Kreps describes LinkedIn building "various hybrid-Hadoop architectures" of this shape before moving away from them.

LayerJobTypical tools (then and now)Failure mode
Master datasetImmutable raw factsHDFS, S3 or GCS, KafkaMutated by mistake: "human fault-tolerance" lost
Batch layerRecompute everythingHadoop, Spark, warehouse SQLRuns for hours, misses the last hours
Speed layerIncremental, recentStorm, Flink, Kafka Streams, Spark StreamingApproximate or late-data errors
Serving layerMerge and answerHBase, Cassandra, Druid, ClickHouseMerge logic bugs, double counting at the seam
ProsCons
Immutable input, easy human-error recoverySame logic in two systems, kept in sync by hand
Batch result is exact and reproducibleTwo clusters to run, monitor and pay for
Fresh answer for the last hoursThe merge seam is a bug magnet
Reprocessing is built in (Kreps credits this)Streaming and batch bugs differ, so results disagree
Works with immature stream enginesObsolete once the stream engine can replay

Kappa architecture ​

Kappa Must-know ​

In plain words: keep every event in a log; run one stream job; when the logic changes, start a second copy that replays the log from the beginning into a new table, then switch.

Common misunderstanding: "Kappa means no batch ever." Kreps' own text says the data can still go to HDFS and be analysed in Hive; the point is that you do not run your reprocessing there. And it is not "Kafka forever": any ordered, long-retention store can be the log.

Definition: Kreps' steps: retain the full log (he suggests setting Kafka retention to the period you want to reprocess, such as 30 days); to reprocess "start a second instance of your stream processing job that starts processing from the beginning of the retained data, but direct this output data to a new output table"; when the new job catches up, switch the application to the new table and delete the old one.

Retained logKafka topicretention = N daysor tiered storageJob v1 (live)consumer group Areads at the headJob v2 (replay)consumer group Bstarts at offset 0, fastOutput tableorders_v1Output tableorders_v2Appreadscut over, thendrop v1
1  job v1 reads orders.placed.v1 at the head, writes orders_v1
2  bug found in the revenue rule; fix written as job v2
3  start v2 in a new consumer group at offset 0, parallelism x4
4  v2 writes orders_v2; lag drops to zero after 25 minutes
5  app switches reads to orders_v2 (rollback = switch back); drop v1 and orders_v1

Real scenario: LinkedIn's Samza pipelines (Kreps says LinkedIn keeps more than a petabyte of Kafka storage online); event-sourced systems where the log is the source of truth (Event Sourcing & CQRS).

When it fails.

SituationWhy Kappa strugglesWhat to do
Years of historyReplaying a year through a stream job is slow and costly; broker storage is expensiveTiered storage, or replay from a lake via the same engine in batch mode
Log compactionA compacted topic keeps only the latest value per key, so history is goneKeep a separate full-history topic or lake copy
Non-deterministic logicCalls to external services give different answers on replayMake the job a pure function of the log; snapshot lookups
Ordering across partitionsReplay races produce different resultsKey by entity; use event time and watermarks
Heavy ML retrainingNeeds scans and joins over all dataBatch on the lake or warehouse
Output store cannot absorb a bulk reloadKreps: needs "a database that supports high-volume writes for the re-load"Load to a new table, then switch
Schema changes in old eventsOld events do not fit the new logicUpcasters, schema registry, versioned decoding
ProsCons
One codebase, one engineNeeds long retention and replay throughput
Reprocessing is a redeployTemporary 2x output storage during replay
Easier to test and reason aboutWeak fit for large historical joins and ML training
Rollback is a table switchStream engine must be as correct as batch (exactly-once, event time)

Unified models: Dataflow and Beam ​

The Dataflow model Important ​

In plain words: write one pipeline that says what to compute, where in event time, when to emit and how to refine; the same code runs on bounded or unbounded data.

Common misunderstanding: "Beam is just another engine." Beam is a programming model with runners (Flink, Spark, Google Dataflow); the engine does the work.

Definition: the paper frames four questions: what results are computed, where in event time, when in processing time they are emitted, and how refinements relate. It treats batch as the bounded special case. Kreps predicted this direction in 2014 when he argued for one framework over two.

1  PCollection of OrderPlaced (bounded file OR unbounded Kafka topic)
2  window: FixedWindows(1 minute) in event time
3  trigger: at watermark, plus late firings up to 10 minutes
4  combine: Sum(total_cents) per country
5  runner executes on Flink or Dataflow; code is unchanged
QuestionBeam conceptPlain meaning
WhatTransforms (ParDo, GroupByKey, Combine)The computation
WhereWindowingGrouping by event time
WhenTriggers and watermarksEmit moment
HowAccumulation modeDo later results replace or add to earlier ones

Trade-off: the common denominator of runners limits features, and Kreps' warning about leaky abstractions still applies. The unified model reduces code duplication; it does not remove operating two engines if you keep both.

Storage tiers ​

Data lake, warehouse, lakehouse Must-know ​

In plain words: a lake is cheap files of any shape; a warehouse is a managed, structured database for analysis; a lakehouse puts warehouse behaviour (transactions, schema, speed) on top of lake files.

Common misunderstanding: "A lake is a dump you query later." Without table formats, schemas and ownership it becomes a swamp: duplicate files, no deletes, no history of which file is current.

Definition: the Lakehouse paper says the pattern is "characterized by (i) open direct-access data formats, such as Apache Parquet and ORC, (ii) first-class support for machine learning and data science workloads, and (iii) state-of-the-art performance". Its Figure 1 describes the evolution to a two-tier lake plus warehouse model, and the pattern that merges them.

1  OrderPlaced events -> Kafka -> writer
2  writer appends Parquet files to s3://lake/orders/day=2026-11-25/
3  table format (Iceberg or Delta) records the file list in a snapshot (transaction)
4  Trino / Spark / ClickHouse query the table: see all files or none
5  a new snapshot adds files; time travel reads an old snapshot
TierHoldsCostGovernanceProducts
Data lakeRaw and curated fileslowest per TBweak unless addedS3, GCS, Azure Blob + Parquet
Data warehouseModelled tableshigher per TBstrong: schema, accessBigQuery, Snowflake, Redshift, ClickHouse
LakehouseTable format over lake fileslowmedium to strongIceberg, Delta Lake, Apache Hudi, Databricks
Serving storePre-aggregated, indexedhighest per TBper productClickHouse, Pinot, Druid, Redis
File / table formatKindNotes
ParquetColumnar fileThe usual file; row groups, column chunks, dictionary encoding, predicate pushdown
ORCColumnar fileHive ecosystem
AvroRow file with schemaGood for Kafka and raw landing
IcebergTable formatSnapshots, hidden partitioning, schema evolution
Delta LakeTable formatTransaction log over Parquet
HudiTable formatUpserts, incremental pulls

Fix: pick the smallest tier that serves the consumer. A single warehouse is enough for most product teams; add a lake when you need cheap raw history, many engines or ML; adopt a lakehouse table format when you must update or delete data in files (privacy deletes, corrections).

Common storage pitfallSymptomRemedy
Small filesThousands of 1 MB files, slow queriesCompaction jobs, larger batch writes
Wrong partition keyScans everything or creates millions of directoriesPartition by date, cluster by a high-cardinality key
No schema contractColumns change type silentlySchema registry, table-format evolution rules
No delete pathPrivacy deletion impossibleTable format with row-level deletes, or tokenise PII

Change data capture: the bridge from OLTP ​

CDC with Debezium Must-know ​

In plain words: instead of asking the database "what changed?", read its own change log and publish every insert, update and delete as an event.

Common misunderstanding: "I can poll updated_at." Polling misses deletes, misses rows whose timestamp was not updated, loads the database, and gives no order. And "dual write" (write the DB, then publish) loses events when one step fails.

Definition: Debezium describes itself as "a set of distributed services to capture changes in your databases so that your applications can see those changes and respond to them." For PostgreSQL it reads the write-ahead log through logical decoding; the docs say that from PostgreSQL 10 the pgoutput plug-in is natively supported. Each event has an envelope with before, after, op (c create, u update, d delete, r snapshot read) and ts_ms. Topic names follow server, schema and table. Debezium usually runs on Kafka Connect. Mechanics are in Change Data Capture.

1  Laravel: UPDATE orders SET status='paid' WHERE id=1001
2  PostgreSQL writes the WAL; replication slot keeps it until read
3  Debezium decodes the change, emits {before, after, op:"u", ts_ms} to shop.public.orders
4  consumer upserts row 1001 into the warehouse (idempotent)
5  on restart, Debezium resumes from the last confirmed LSN (no gaps)

Real scenario: replicating the orders table to ClickHouse within seconds; building a search index; invalidating caches.

MethodCaptures deletesLoad on sourceOrderingNotes
Log-based CDC (Debezium)yeslowper primary key, from the WALNeeds wal_level=logical, a replication slot
Trigger-basedyesadds write costyesSimple but invasive
Query-based (updated_at polling)noscansweakCheap start, lossy
Dual writen/anonenoneUnsafe: partial failure
Outboxonly what you write1 extra insertyesPublishes domain events, not table rows

Two kinds of CDC event. Table-change events (Debezium on orders) leak your schema to consumers; domain events through the outbox (see PlaceOrder.php below) are a stable contract. For analytics, table CDC is the fastest start; for cross-service integration prefer the outbox.

Operational traps: an unconsumed replication slot makes PostgreSQL retain WAL until the disk fills; a connector restart after a long outage replays a large backlog; schema changes need a compatible converter and a registry.

Data mesh vs a central platform ​

Data mesh Important ​

In plain words: instead of one central data team that owns every pipeline, each domain team (orders, payments, catalogue) publishes its analytical data as a product with an owner, a schema and an SLA.

Common misunderstanding: "Data mesh is a technology you install." It is an organisational and architectural approach; a mesh with no platform and no standards is just chaos with more owners.

Definition: Dehghani's four principles (quoted above): domain-oriented decentralised ownership, data as a product, a self-serve data platform, federated computational governance. It is data's version of the microservices argument and rests on bounded contexts and data ownership.

1  Orders team publishes data product orders_daily (schema v2, freshness 15 min, owner on-call)
2  Platform team provides: storage, CDC templates, catalog, access control
3  Finance team joins orders_daily and payments_daily through the catalog
4  governance bot checks: PII columns tagged, schema compatible, SLO met
Central platform teamData mesh
Who builds pipelinesOne data teamDomain teams on a shared platform
BottleneckThe central queuePlatform maturity and domain skills
Context knowledgeWeak (far from the domain)Strong
ConsistencyEasy: one team, one styleHard: needs federated rules
Best sizeUp to roughly a few dozen engineersMany domains and teams
RiskSlow, backlogDuplicated effort, uneven quality

When it fits: you already have many autonomous teams and a platform group. When it does not: one product team of ten people; the central warehouse is simpler.

Serving analytics ​

Analytics serving stores Important ​

In plain words: a dashboard in a customer-facing product must answer in under a second for thousands of users; the warehouse built for analysts is too slow or too costly per query for that.

Common misunderstanding: "The warehouse can serve the product." Warehouses are built for fewer, heavier queries with a startup cost; product traffic is many concurrent small aggregates.

Definition: real-time OLAP stores (ClickHouse, Apache Pinot, Apache Druid) ingest from Kafka or files and answer aggregates with low latency using columnar storage, indexes and often pre-aggregation (rollups or materialized views that store sums by dimension).

1  OrderPlaced flows into ClickHouse (Kafka engine table or consumer)
2  materialized view maintains sums per (minute, country)
3  product API: SELECT sum(revenue) FROM orders_by_minute WHERE country='DE' AND minute >= now() - INTERVAL 1 HOUR
4  p95 under 100 ms, because 60 rows are read, not 3 million
sql
-- ClickHouse: raw facts plus a pre-aggregated rollup
CREATE TABLE orders_raw (
    order_id UInt64, country LowCardinality(String),
    total_cents UInt64, placed_at DateTime
) ENGINE = MergeTree ORDER BY (country, placed_at);

CREATE MATERIALIZED VIEW orders_by_minute
ENGINE = SummingMergeTree ORDER BY (country, minute) AS
SELECT country, toStartOfMinute(placed_at) AS minute,
       count() AS orders, sum(total_cents) AS revenue_cents
FROM orders_raw GROUP BY country, minute;
StoreStrengthUpdate modelTypical use
ClickHouseVery fast scans, SQL, simple opsAppend, merge-time dedupe (ReplacingMergeTree)Product analytics, logs, order metrics
Apache PinotLow-latency user-facing queries at high concurrencyReal-time and offline segments, upsert tablesUser-facing analytics at high concurrency
Apache DruidTime-series rollups, ingestion-time rollupAppend with rollup, segment compactionEvent analytics, dashboards
Elasticsearch / OpenSearchSearch plus aggregatesDocument upsertSearch-led analytics
RedisCounters, sorted setsin-placeTiny hot aggregates
PostgreSQL + indexes / materialized viewsFamiliarnormalUnder about 1 TB and low concurrency

Pre-aggregation trade-off: it makes reads cheap and queries rigid; you can only ask questions the rollup keeps dimensions for. Keep raw facts as well, so a new question means a new rollup, not lost data.

ML feature pipelines (briefly) ​

Features, offline and online Good to know ​

In plain words: a model needs the same input numbers at training time (history) and at prediction time (now); computing them twice invites mismatch.

Common misunderstanding: "Training data is just a table export." If a feature at training used information from after the event time, the model learns the future (leakage) and fails in production.

Definition: an offline store (lake or warehouse) holds historical feature values with timestamps for point-in-time joins; an online store (Redis, DynamoDB, Cassandra) serves the latest values in milliseconds; a pipeline writes both from one definition. This is the Lambda problem again: batch for history, stream for freshness. Details in ML Systems.

1  stream job updates customer_orders_7d in the online store on each OrderPlaced
2  nightly batch recomputes the same feature into the offline table with event timestamps
3  training joins labels with features as of label time (point-in-time)
4  serving reads the online store; a monitor compares online vs offline values

Governance ​

Schemas, lineage, PII and retention Must-know ​

In plain words: know what each field means, where it came from, who may see it and how long you keep it.

Common misunderstanding: "Governance is paperwork for later." The first privacy-deletion request or schema change that breaks a dashboard makes it urgent, and the lake cannot answer it afterwards.

Definition: the controls around data: schema contracts and a registry (Avro or Protobuf plus compatibility modes), data catalog with lineage (which job produced which table), classification of PII (personally identifiable information), access control (roles, row and column security), retention and deletion (GDPR erasure), quality tests and audits. Dehghani calls it "federated computational governance": rules enforced by the platform, decided by the domains.

1  user requests account deletion
2  catalog lists every table tagged PII with this user key: orders, events, features
3  OLTP row anonymised; CDC emits the change
4  lake: Iceberg/Delta row-level delete or key-rotation (crypto-shredding) executes
5  audit log records the erasure; retention job removes backups on schedule
ControlWhat it preventsExample tooling
Schema registryBreaking consumersConfluent Schema Registry, Apicurio
Data testsBad rowsdbt tests, Great Expectations
LineageUnknown blast radiusOpenLineage, dbt docs, DataHub
PII tagging and maskingLeaksColumn masking in the warehouse, tokenisation
Retention policyHoarding riskTopic retention, table TTL, lifecycle rules
Access controlOver-broad readsRoles, row-level security (see Database Security)

Cost and operational complexity ​

What a pipeline really costs Important ​

In plain words: every box you add is something that can fall over at 3 am, needs an owner, and sends a monthly bill.

Common misunderstanding: "Storage is the cost." Engineers on call, duplicated data, idle clusters, egress and repeated full scans are bigger.

Definition: total cost = infrastructure + people + risk. Complexity grows roughly with the number of independent systems and the number of times the same logic is written.

ChoiceCost driverComplexity addedCheaper alternative
Streaming engineAlways-on cluster, state storage, on-callHigh: time, state, replayMicro-batch every few minutes
LambdaTwo stacksVery high: two codebasesKappa, or batch plus a small stream
Lake plus warehouseTwo copies of dataMedium: sync and ETLLakehouse or one warehouse
Kafka long retentionBroker disk or tiered storageMediumReplay from the lake
Real-time OLAP storeMemory and nodesMediumPre-aggregate in the warehouse
Data meshPlatform team plus domain staffOrganisationalCentral team for small orgs
Warehouse full scansPer-query bytes scannedLowPartitioning, clustering, incremental models
1  count systems: source DB, Kafka, Connect, stream engine, lake, warehouse, serving, BI = 8
2  each has: upgrade path, monitoring, access control, runbook, owner
3  a team of 5 that owns 8 systems owns none of them well
4  start with 3: PostgreSQL, CDC to Kafka (or direct to), warehouse

Solving the classic problems: how a product team starts small ​

StageTriggerWhat you buildDo not build yet
0. ReplicaReports slow the primaryRead replica, materialized viewsAnything else
1. Nightly ELTAnalysts need joins, historyLaravel/Go export to a warehouse table, dbt martsStreaming
2. CDCReports need minutes of freshnessDebezium to Kafka to warehouse (or managed CDC)A second compute engine
3. Serving storeProduct-facing dashboardsClickHouse or Pinot with rollupsLambda
4. Stream jobsA rule truly needs seconds (fraud, alerts)Kafka Streams or Flink for that rule onlyRewriting every report as a stream
5. Lake / lakehouseMany sources, ML, cheap raw historyObject storage with Iceberg or DeltaA mesh before you have many teams
6. MeshMany domain teams, central queue is the bottleneckPlatform, catalog, domain data products

Rule of thumb: add a box only when you can name the consumer, the freshness they need, and the incident that would happen without it.

Go ​

Go's role in a data architecture is narrow and valuable: it produces events, consumes CDC and event streams with small and fast services, writes columnar files, and runs simple windowed aggregations. It is not where big joins happen; the warehouse does that. We use github.com/twmb/franz-go/pkg/kgo for Kafka and github.com/parquet-go/parquet-go for Parquet.

Producing a fact ​

The producer keys by order id (all events of one order stay ordered in one partition), waits for all in-sync replicas, and carries an event_id and a schema_version so consumers can deduplicate and evolve.

go
// Command producer publishes an OrderPlaced fact to Kafka.
// The key is the order id so all events of one order stay in one partition (ordered).
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"
)

// OrderPlaced is an immutable fact. Money is integer cents; time is the EVENT time.
type OrderPlaced struct {
	EventID    string    `json:"event_id"`
	OrderID    int64     `json:"order_id"`
	CustomerID int64     `json:"customer_id"`
	Country    string    `json:"country"`
	TotalCents int64     `json:"total_cents"`
	PlacedAt   time.Time `json:"placed_at"`
	Version    int       `json:"schema_version"`
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS=host:9092 to publish; exiting")
		return
	}
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers),
		kgo.RequiredAcks(kgo.AllISRAcks()), // wait for all in-sync replicas
		kgo.ProducerLinger(20*time.Millisecond),
	)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer cl.Close()

	ev := OrderPlaced{
		EventID: "0192f1c4-0000-7000-8000-000000000001", OrderID: 1001, CustomerID: 7,
		Country: "DE", TotalCents: 4990, PlacedAt: time.Now().UTC(), Version: 1,
	}
	body, _ := json.Marshal(ev)
	rec := &kgo.Record{
		Topic: "orders.placed.v1",
		Key:   []byte(fmt.Sprint(ev.OrderID)),
		Value: body,
	}
	if err := cl.ProduceSync(context.Background(), rec).FirstErr(); err != nil {
		fmt.Fprintln(os.Stderr, "produce:", err)
		os.Exit(1)
	}
	fmt.Println("published order", ev.OrderID)
}

A CDC consumer with an idempotent sink ​

This service reads Debezium events from shop.public.orders, maps op to upsert or delete and commits offsets only after the sink succeeded. Replays are safe because the sink upserts by primary key.

go
// Command cdc reads Debezium change events for the orders table from Kafka and
// upserts them into an analytics store. The consumer is idempotent: replaying the
// same offsets produces the same final state.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/twmb/franz-go/pkg/kgo"
)

// Envelope is the part of the Debezium change-event value we use.
// op: c = create, u = update, d = delete, r = snapshot read.
type Envelope struct {
	Payload struct {
		Before *OrderRow `json:"before"`
		After  *OrderRow `json:"after"`
		Op     string    `json:"op"`
		TsMs   int64     `json:"ts_ms"`
	} `json:"payload"`
}

// OrderRow mirrors the columns of the source table.
type OrderRow struct {
	ID         int64  `json:"id"`
	CustomerID int64  `json:"customer_id"`
	Country    string `json:"country"`
	TotalCents int64  `json:"total_cents"`
	Status     string `json:"status"`
}

// Sink is the warehouse side. Upsert must be idempotent (key = id).
type Sink interface {
	Upsert(ctx context.Context, row OrderRow, sourceTsMs int64) error
	Delete(ctx context.Context, id int64) error
}

// Apply turns one change event into one sink call.
func Apply(ctx context.Context, s Sink, value []byte) error {
	if len(value) == 0 { // tombstone that follows a delete
		return nil
	}
	var env Envelope
	if err := json.Unmarshal(value, &env); err != nil {
		return fmt.Errorf("decode: %w", err)
	}
	p := env.Payload
	switch p.Op {
	case "c", "u", "r":
		return s.Upsert(ctx, *p.After, p.TsMs)
	case "d":
		return s.Delete(ctx, p.Before.ID)
	}
	return fmt.Errorf("unknown op %q", p.Op)
}

type logSink struct{}

func (logSink) Upsert(_ context.Context, r OrderRow, ts int64) error {
	fmt.Printf("upsert order=%d total=%d ts=%d\n", r.ID, r.TotalCents, ts)
	return nil
}

func (logSink) Delete(_ context.Context, id int64) error {
	fmt.Printf("delete order=%d\n", id)
	return nil
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS=host:9092 to consume; exiting")
		return
	}
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers),
		kgo.ConsumerGroup("orders-to-warehouse"),
		kgo.ConsumeTopics("shop.public.orders"), // <server>.<schema>.<table>
		kgo.DisableAutoCommit(),
	)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer cl.Close()

	ctx := context.Background()
	var sink Sink = logSink{}
	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() {
			return
		}
		fetches.EachError(func(t string, p int32, err error) {
			fmt.Fprintf(os.Stderr, "fetch %s/%d: %v\n", t, p, err)
		})
		var last []*kgo.Record
		fetches.EachRecord(func(r *kgo.Record) {
			if err := Apply(ctx, sink, r.Value); err != nil {
				fmt.Fprintln(os.Stderr, "apply:", err) // real code: send to a DLQ
				return
			}
			last = append(last, r)
		})
		// Commit only after the sink succeeded: at-least-once + idempotent upsert.
		if len(last) > 0 {
			if err := cl.CommitRecords(ctx, last...); err != nil {
				fmt.Fprintln(os.Stderr, "commit:", err)
			}
		}
	}
}

Writing Parquet ​

A batch job or a micro-batch flusher turns rows into a columnar file. The footer written on Close makes the file readable; dictionary encoding suits low-cardinality columns such as country; zstd compresses.

go
// Command parquet writes order facts as a columnar Parquet file, the format a
// data lake or lakehouse table (Iceberg, Delta Lake) is built from.
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/parquet-go/parquet-go"
)

// OrderFact is one row of the fact table. Tags set the Parquet column names.
type OrderFact struct {
	OrderID    int64  `parquet:"order_id"`
	CustomerID int64  `parquet:"customer_id"`
	Country    string `parquet:"country,dict"` // dictionary encoding: few distinct values
	TotalCents int64  `parquet:"total_cents"`
	PlacedAtMs int64  `parquet:"placed_at_ms"`
}

func main() {
	path := os.Getenv("OUT")
	if path == "" {
		path = "orders-2026-11-25.parquet"
	}
	f, err := os.Create(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer f.Close()

	w := parquet.NewGenericWriter[OrderFact](f, parquet.Compression(&parquet.Zstd))
	now := time.Now().UnixMilli()
	rows := []OrderFact{
		{OrderID: 1, CustomerID: 7, Country: "DE", TotalCents: 4990, PlacedAtMs: now},
		{OrderID: 2, CustomerID: 9, Country: "DE", TotalCents: 1290, PlacedAtMs: now},
		{OrderID: 3, CustomerID: 7, Country: "FR", TotalCents: 8800, PlacedAtMs: now},
	}
	if _, err := w.Write(rows); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := w.Close(); err != nil { // writes the footer; the file is invalid without it
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println("wrote", path, len(rows), "rows")
}

A simple windowed stream consumer ​

This is the whole idea of event-time windows with a watermark and allowed lateness, in standard library code. Run it with go run ./windows from the snippet module; the output closes window 10:00 with 1500 cents and counts one late event dropped.

go
// Command windows shows event-time tumbling windows with a watermark.
// It is the core idea of stream processing in about 80 lines of standard library.
package main

import (
	"fmt"
	"sort"
	"time"
)

// Event is one order with the time it HAPPENED (event time), not when we saw it.
type Event struct {
	At         time.Time
	TotalCents int64
}

// Aggregator keeps per-window state and closes windows when the watermark passes.
type Aggregator struct {
	Size            time.Duration // window length, e.g. 1 minute
	AllowedLateness time.Duration // how far behind the newest event we still wait
	state           map[time.Time]int64
	maxEvent        time.Time
	Late            int // events dropped because their window had already closed
}

// NewAggregator creates an empty aggregator.
func NewAggregator(size, lateness time.Duration) *Aggregator {
	return &Aggregator{Size: size, AllowedLateness: lateness, state: map[time.Time]int64{}}
}

// Watermark is the claim "no event older than this will arrive any more".
func (a *Aggregator) Watermark() time.Time { return a.maxEvent.Add(-a.AllowedLateness) }

// Add puts the event into its window, or counts it as late.
func (a *Aggregator) Add(e Event) {
	start := e.At.Truncate(a.Size)
	if !start.Add(a.Size).After(a.Watermark()) && !a.maxEvent.IsZero() {
		a.Late++ // window end is at or before the watermark: already emitted
		return
	}
	a.state[start] += e.TotalCents
	if e.At.After(a.maxEvent) {
		a.maxEvent = e.At
	}
}

// Closed returns and removes every window whose end is at or before the watermark.
func (a *Aggregator) Closed() map[time.Time]int64 {
	out := map[time.Time]int64{}
	for start, sum := range a.state {
		if !start.Add(a.Size).After(a.Watermark()) {
			out[start] = sum
			delete(a.state, start)
		}
	}
	return out
}

func main() {
	t0 := time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
	agg := NewAggregator(time.Minute, 30*time.Second)
	// Arrival order differs from event order: the 10:00:50 order arrives late.
	for _, e := range []Event{
		{t0.Add(10 * time.Second), 1000},
		{t0.Add(70 * time.Second), 2000},
		{t0.Add(50 * time.Second), 500},  // out of order but within lateness
		{t0.Add(130 * time.Second), 700}, // pushes the watermark past 10:01:00
		{t0.Add(20 * time.Second), 300},  // too late: window 10:00 is closed
	} {
		agg.Add(e)
		closed := agg.Closed()
		starts := make([]time.Time, 0, len(closed))
		for s := range closed {
			starts = append(starts, s)
		}
		sort.Slice(starts, func(i, j int) bool { return starts[i].Before(starts[j]) })
		for _, s := range starts {
			fmt.Printf("window %s closed: %d cents\n", s.Format("15:04"), closed[s])
		}
	}
	fmt.Println("late events dropped:", agg.Late)
}

The Go angle ​

NeedGo choiceNotes
Kafka clientfranz-go (kgo)Consumer groups, transactions, fast; segmentio/kafka-go is an alternative
Parquetparquet-go/parquet-goGeneric writer with struct tags
Avro / Protobufhamba/avro, google.golang.org/protobufPair with a schema registry client
Warehouse insertclickhouse-go, pgx CopyFrom, BigQuery clientPrefer big batches over single rows
Windows and stateHand-written, or call Flink for hard casesBeyond simple windows use a real engine
ConcurrencyGoroutine per partitionKeep one writer per partition to preserve order

The snippet module pins parquet-go v0.25.1 (newer releases needed a dependency version the build machine could not download on 2026-11-25) and its go.mod says go 1.26.0 because go mod tidy raised it from the dependency graph; adjust for your toolchain.

Laravel ​

Laravel's roles are different: it is usually the source of the data (the OLTP application), it emits events reliably, and it can run batch jobs that move a bounded set of rows. Heavy transformation belongs in the warehouse or a dedicated engine, not in PHP.

Emitting an event with the outbox ​

Insert the order and the outbox row in one transaction; a relay or Debezium's outbox event router publishes the row. This avoids the dual-write failure described in Outbox Pattern.

php
<?php

declare(strict_types=1);

namespace App\Orders;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * Emit a business fact in the SAME transaction as the state change (outbox).
 * A relay (or Debezium's outbox event router) publishes the row to Kafka later.
 */
final class PlaceOrder
{
    /** @param array{customer_id:int,country:string,total_cents:int} $data */
    public function handle(array $data): int
    {
        return DB::transaction(function () use ($data): int {
            $orderId = DB::table('orders')->insertGetId([
                'customer_id' => $data['customer_id'],
                'country' => $data['country'],
                'total_cents' => $data['total_cents'],
                'status' => 'placed',
                'placed_at' => now(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            DB::table('outbox')->insert([
                'id' => (string) Str::uuid7(),
                'aggregate_type' => 'order',
                'aggregate_id' => (string) $orderId,
                'event_type' => 'OrderPlaced',
                'payload' => json_encode([
                    'order_id' => $orderId,
                    'customer_id' => $data['customer_id'],
                    'country' => $data['country'],
                    'total_cents' => $data['total_cents'],
                    'placed_at' => now()->toIso8601String(),
                    'schema_version' => 1,
                ], JSON_THROW_ON_ERROR),
                'created_at' => now(),
            ]);

            return $orderId;
        });
    }
}

Warehouse tables ​

php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Runs on the "warehouse" connection (a separate database or schema).
return new class extends Migration
{
    protected $connection = 'warehouse';

    public function up(): void
    {
        // Raw copy of the source rows (the "L" of ELT); idempotent by primary key.
        Schema::connection('warehouse')->create('stg_orders', function (Blueprint $t): void {
            $t->unsignedBigInteger('id')->primary();
            $t->unsignedBigInteger('customer_id');
            $t->char('country', 2);
            $t->unsignedBigInteger('total_cents');
            $t->string('status', 20);
            $t->timestamp('placed_at')->index();
            $t->timestamp('loaded_at');
        });

        // Modelled output (the "T"): one row per day and country.
        Schema::connection('warehouse')->create('fact_orders_daily', function (Blueprint $t): void {
            $t->date('day');
            $t->char('country', 2);
            $t->unsignedInteger('orders');
            $t->unsignedBigInteger('revenue_cents');
            $t->primary(['day', 'country']);
        });
    }

    public function down(): void
    {
        Schema::connection('warehouse')->dropIfExists('fact_orders_daily');
        Schema::connection('warehouse')->dropIfExists('stg_orders');
    }
};

The nightly ETL command ​

lazyById returns a LazyCollection that uses PHP generators; the Laravel docs describe it as letting you "work with very large datasets while keeping memory usage low", and recommend lazyById over lazy when you filter on a column you update while iterating. chunk(1000) on the lazy collection groups rows into batches for one upsert call each. The command is safe to rerun for the same day.

php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * Nightly batch: extract one day of orders with a lazy cursor, load them into
 * the warehouse staging table in small batches, then rebuild that day's aggregate.
 * Re-running the same day is safe (upsert + delete-and-insert for the day).
 *
 * Schedule (routes/console.php):
 *   Schedule::command('etl:orders')->dailyAt('02:00')->onOneServer();
 */
final class NightlyOrdersEtl extends Command
{
    protected $signature = 'etl:orders {--date= : Y-m-d, default yesterday}';

    protected $description = 'Load one day of orders into the warehouse';

    public function handle(): int
    {
        $day = Carbon::parse($this->option('date') ?? 'yesterday')->startOfDay();
        $from = $day->toDateTimeString();
        $to = $day->copy()->addDay()->toDateTimeString();
        $loadedAt = now()->toDateTimeString();
        $warehouse = DB::connection('warehouse');

        // E + L: lazyById keeps memory flat (one chunk of 2000 rows at a time) and is
        // safe while rows change, because it pages by primary key, not by OFFSET.
        $loaded = 0;
        DB::table('orders')
            ->whereBetween('placed_at', [$from, $to])
            ->lazyById(2000)
            ->map(fn (object $o): array => [
                'id' => $o->id,
                'customer_id' => $o->customer_id,
                'country' => $o->country,
                'total_cents' => $o->total_cents,
                'status' => $o->status,
                'placed_at' => $o->placed_at,
                'loaded_at' => $loadedAt,
            ])
            ->chunk(1000)
            ->each(function ($batch) use ($warehouse, &$loaded): void {
                $rows = $batch->values()->all();
                $warehouse->table('stg_orders')->upsert(
                    $rows,
                    ['id'],
                    ['customer_id', 'country', 'total_cents', 'status', 'placed_at', 'loaded_at'],
                );
                $loaded += count($rows);
            });

        // T: rebuild the day inside the warehouse (SQL does the heavy lifting).
        $warehouse->transaction(function () use ($warehouse, $day, $from, $to): void {
            $warehouse->table('fact_orders_daily')->where('day', $day->toDateString())->delete();
            $warehouse->statement(
                "INSERT INTO fact_orders_daily (day, country, orders, revenue_cents)
                 SELECT DATE(placed_at), country, COUNT(*), SUM(total_cents)
                 FROM stg_orders
                 WHERE placed_at >= ? AND placed_at < ? AND status <> 'cancelled'
                 GROUP BY DATE(placed_at), country",
                [$from, $to],
            );
        });

        $this->info("Loaded {$loaded} orders for {$day->toDateString()}");

        return self::SUCCESS;
    }
}

The Laravel angle ​

NeedLaravel 13 featureNotes
Reliable emissionDB::transaction + outbox tablePublisher is outside Laravel (relay, Debezium)
Domain events in processEvents and listeners (queued with ShouldQueue)Not durable analytics transport on its own
Nightly batchArtisan command + scheduler (Schedule::command(...)->dailyAt('02:00')->onOneServer())One server runs it; make it idempotent
Large readslazyById, chunkById, cursorlazyById for stable memory
Bulk loadupsert, insert in batchesBatch size 500 to 5000 rows
Warehouse connectionA second connection in config/database.phpSeparate credentials, read-only for the source
Long jobsQueue jobs with batches (Bus::batch)Split by day or id range

Worked example: order analytics, three ways ​

The requirement. An online shop: 2 million orders a day (average 23 per second, peak 300 per second during sales). Finance wants daily revenue by country. Operations wants an "orders in the last hour" tile, within 10 seconds. A recommender team wants yesterday's purchase history. Source: PostgreSQL behind Laravel and some Go services.

Option A: nightly batch ​

1  02:00 Laravel etl:orders extracts yesterday via lazyById
2  upsert into warehouse stg_orders (idempotent)
3  rebuild fact_orders_daily for the day
4  07:00 finance reads yesterday's totals
5  "orders in last hour" tile: not served (stale by up to 24 h)

Option B: Lambda ​

1  OrderPlaced in Kafka (immutable log)
2  batch layer: nightly Spark/warehouse SQL builds orders_by_day (exact)
3  speed layer: Flink counts per minute into a realtime table
4  API query "today": batch view for completed days + realtime view for today, merged
5  bug in the revenue rule: fix it in Spark AND in Flink, rerun batch, hope both agree

Option C: Kappa ​

1  OrderPlaced in Kafka, retention 30 days, plus Parquet archive in the lake
2  one Flink job computes per-minute and per-day aggregates into ClickHouse
3  API reads ClickHouse for both tiles
4  revenue rule fix: start job v2 at offset 0 (30 days), write orders_agg_v2, switch, drop v1
5  history beyond 30 days: replay from the Parquet archive with the same job in batch mode
CriterionA: Nightly batchB: LambdaC: Kappa
Meets "last hour in 10 s"NoYesYes
Finance exact daily totalYesYes (batch view)Yes (after correct replay)
Code paths for the revenue rule1 (SQL)2 (SQL + Flink)1 (Flink)
Systems to runSource DB, warehouseKafka, Spark or warehouse, Flink, serving storeKafka, Flink, ClickHouse, lake archive
Fix a historic bugRerun the dayRerun batch, patch speed layerReplay the log into a new table
Team size needed (guess)1 engineer part-time3 or more2 to 3
Failure surfaceSmallLargest (seam, drift)Medium (state, replay)
When it is rightReports onlyLegacy with separate batch and stream stacksNew system needing both freshness and correctness

Decision for this shop: start with A for finance (one weekend of work), add a CDC feed into ClickHouse for the live tile (stage 3 of How a product team starts small), and use Flink only if the tile needs windowing that ClickHouse materialized views cannot express. That is A plus a small C, never B.

Choosing ​

RequirementRecommended pathExtra techniqueReason
Daily and weekly reportsNightly ELT into a warehousedbt tests, partition overwriteSimple, exact, rerunnable
Dashboard fresh within minutesCDC to warehouse or ClickHouseIdempotent upsert, reconciliation countsNo second codebase
Product-facing analytics, many usersReal-time OLAP (ClickHouse, Pinot, Druid)Pre-aggregated rollupsSub-second at high concurrency
Fraud, alerts, live rulesStream job (Flink, Kafka Streams)Event time, state TTL, DLQLatency in seconds
Fix history after a logic changeKappa replay or batch rerunNew output table, then switchAvoids in-place corruption
Existing separate batch and stream stacksKeep Lambda, hide the merge in one query layerShared test vectors for both pathsRewrite cost is high
Many sources, ML, cheap raw historyLake plus table format (Iceberg, Delta)Compaction, catalogOpen formats, many engines
Many autonomous domain teamsData mesh on a self-serve platformFederated governanceCentral team is the bottleneck
Data under about 1 TB, few analystsPostgreSQL replica and materialized viewsPartitioningDo not build a platform

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel app, one PostgreSQL. Analytics means SQL on a read replica or a materialized view like the one in OLTP and OLAP, refreshed by the scheduler. Example: the admin page "orders per day" reads sales_daily. Nothing else is needed, and adding a warehouse here is the most common over-engineering.

Modular monolith / multiple databases ​

Modules own their tables (Modular Monolith). Analytics must not join across module tables with ad-hoc SQL on production; instead each module exposes a read model or an export, and the nightly ELT copies them into a warehouse schema per module. The warehouse becomes the only place where orders and payments meet. Example: etl:orders and etl:payments land in stg_orders and stg_payments; dbt joins them.

Microservices ​

Each service owns its database (Data Ownership), so analytics cannot query "the database". Services publish events (outbox) or Debezium reads each service database; the warehouse or lake consumes the topics. Example flow: orders publishes OrderPlaced, payments publishes PaymentCaptured, shipping publishes Shipped; ClickHouse joins them by order_id within a time bound; late events are expected, so metrics are revisable. Contracts and versioning follow Service Communication and Message Design.

Distributed data (replicas, caches, sharded databases, multi-region) ​

CDC from a replica or a primary has different lag; sharded OLTP means one Debezium connector per shard and a merge key that includes the shard id. Multi-region means events carry the region and an event-time clock that may skew; use event time plus a watermark with generous delay, and de-duplicate by event_id. Caches (Redis) can be derived from the stream, but analytics read the warehouse, not the cache. Replication lag from Replication & Failover shows up as "the dashboard is behind" and should be monitored as freshness SLO.

Scaling path (1x, 10x, 100x) ​

ScaleOrders per dayDesignWhat changes
1x20 thousandReplica, materialized viewsNothing exotic
10x2 millionNightly ELT to one warehouse node, dbtA second system, one owner
100x200 millionCDC and Kafka, ClickHouse cluster or BigQuery, partitioned Parquet in a lakeStreaming ingest, compaction, schema registry
1000x2 billionStream jobs for rules, tiered Kafka storage, lakehouse, possibly meshPlatform team, governance, cost control

The design principle at every step is the same: keep the source of truth a log or a database, derive everything else from it, and make every derived thing rebuildable.

Lab ​

Goal: build the smallest pipeline in this chapter on one laptop and break it on purpose. Prerequisites: Docker, Go, PHP (optional). Expected outputs are in comments.

  1. Source and replica of facts. Run PostgreSQL and create the table.
sql
CREATE TABLE orders (
  id bigserial PRIMARY KEY, customer_id bigint NOT NULL, country char(2) NOT NULL,
  total_cents bigint NOT NULL, status text NOT NULL DEFAULT 'placed',
  placed_at timestamptz NOT NULL DEFAULT now());
INSERT INTO orders (customer_id, country, total_cents)
SELECT (random()*1000)::int, (ARRAY['DE','FR','NL'])[1+(random()*2)::int], (random()*20000)::int
FROM generate_series(1, 1000000);
-- expected: INSERT 0 1000000
  1. Measure the analytic query on the source. EXPLAIN (ANALYZE) SELECT country, sum(total_cents) FROM orders GROUP BY country; Note the time and that all rows are read (expected: a sequential scan of 1M rows, hundreds of milliseconds).
  2. Add the materialized view from the OLTP section, refresh it, query sales_daily (expected: under 5 ms).
  3. Batch ELT. Run go run ./parquet to write a Parquet file and inspect it with DuckDB: SELECT country, sum(total_cents) FROM 'orders-2026-11-25.parquet' GROUP BY country; (expected: three rows).
  4. Windows and lateness. Run go run ./windows (expected: window 10:00 closed: 1500 cents, late events dropped: 1). Change AllowedLateness to 90 seconds and predict, then check, which events are now kept.
  5. Idempotency. Feed the same Debezium JSON to Apply twice with an in-memory Sink that stores rows by id; the count must stay the same. Break it by using INSERT instead of upsert and watch it double.
  6. Replay (Kappa in miniature). Write a function that recomputes per-minute totals from a slice of events; change the revenue rule (exclude cancelled), rerun on the same slice into a new map, and compare both maps. That is job v2 replacing v1.

Common misconceptions ​

BeliefReality
"Big data means Hadoop or Spark"It is a problem shape; many teams solve it with PostgreSQL plus a column store
"Streaming replaces batch"Batch stays the simplest way to get exact, rerunnable results; Kreps says choose by latency need
"Lambda beats CAP"Marz's title says so; Kreps: the results are asynchronous, CAP remains intact
"Kappa means no historical store"Kappa needs a retained log (or lake replay); history still exists, you just reprocess from it
"Exactly-once delivery is available end to end"You get exactly-once effect through checkpoints or idempotent sinks
"Processing time is good enough"Delays shift events into wrong windows and make replays irreproducible
"A watermark guarantees no late data"It is a heuristic; late events can still arrive and need a policy
"A data lake needs no schema"Without schemas and table formats it becomes unusable
"A lakehouse replaces everything"It simplifies two tiers; you may still want a serving store for low latency
"Data mesh means no central team"A self-serve platform team is one of the four principles
"A read replica is an analytics platform"It offloads reads, but row-store scans and replication conflicts remain
"More Vs means a better design"Each V is a question about your data, not a checklist item

Cheat sheet ​

TopicWhat to remember
3VsLaney 2001: volume, velocity, variety; veracity and value were added later
StartPostgreSQL replica, then nightly ELT, then CDC; stream only when needed
OLTP vs OLAPRows and point lookups versus columns and scans; do not mix on one box
BatchBounded, idempotent, rerunnable; partition overwrite; backfill
ELTLoad raw first, transform in the warehouse with tested SQL (dbt)
Event timeUse it for windows; processing time breaks replays
Watermarknewest event time minus allowed delay; closes windows; late-data policy needed
Exactly-onceAt-least-once plus idempotent sink or transactions
LambdaBatch plus speed plus serving; cost is two codebases (Kreps)
KappaOne job, retained log, replay into a new table, then switch
Dataflow/BeamBounded and unbounded are the same model; engines differ
LakehouseParquet files plus Iceberg or Delta table format
CDCRead the WAL (Debezium); events have before, after, op, ts_ms; watch replication slots
MeshFour principles: domain ownership, data as product, self-serve platform, federated governance
ServingClickHouse, Pinot, Druid; pre-aggregate; keep raw too
GovernanceSchema registry, lineage, PII tags, retention, deletion path

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What did Laney's 2001 note name, and which Vs came later? Good to know ​

Answer

Answer: Volume, velocity and variety. Veracity and value were added later by industry usage; they are not in Laney's note.

2 — Why is a nightly report on the production OLTP database risky? Must-know ​

Answer

Answer: A long scan competes for cache and I/O with short transactions; checkout latency rises. A replica, materialized view or warehouse separates the workloads.

3 — Define event time, processing time and watermark. Important ​

Answer

Answer: Event time is when the event occurred, processing time is when the job sees it; a watermark is the claim that no events older than a time will arrive, derived as newest event time minus allowed delay.

4 — An event arrives after its window closed. What are the options? Important ​

Answer

Answer: Drop it, keep window state longer (allowed lateness) and re-emit, send it to a side output for batch reconciliation, or increase the watermark delay.

5 — Why does a Lambda architecture hurt maintenance, per Kreps? Good to know ​

Answer

Answer: Code must produce the same result in two complex distributed systems, and operating and debugging both is costly; abstraction layers leak.

6 — Describe Kappa reprocessing in four steps. Important ​

Answer

Answer: Retain the log; start a second job version at the beginning writing to a new table; when it catches up, switch the application; delete the old job and table.

7 — When does Kappa fail? Good to know ​

Answer

Answer: Very long history, compacted topics, non-deterministic jobs, large historical joins or ML training, and output stores that cannot take a bulk reload.

8 — How do you get an exactly-once result with an at-least-once consumer? Important ​

Answer

Answer: Make the sink idempotent (upsert by event or primary key) or write transactionally with offsets; commit the offset after the write.

9 — Why prefer log-based CDC to polling updated_at? Important ​

Answer

Answer: It captures deletes, order and every change with low load; polling misses deletes and rows whose timestamp was not updated.

10 — What are the four data mesh principles? Good to know ​

Answer

Answer: Domain-oriented decentralised ownership, data as a product, self-serve data infrastructure as a platform, federated computational governance.

11 — A team of six runs one PostgreSQL and wants Flink, Kafka, a lake and ClickHouse. What do you ask first? Must-know ​

Answer

Answer: Who is the consumer, what freshness do they need, and what fails without it. Probably start with a replica, nightly ELT and CDC.

12 — What does lazyById(2000) give you in a Laravel ETL command? Important ​

Answer

Answer: A LazyCollection that reads 2000 rows at a time ordered by id, so memory stays flat and paging is by key, safe if rows change during iteration.

Glossary ​

TermMeaning
Volume, Velocity, VarietyLaney's three dimensions: how much, how fast, how many shapes
Veracity, ValueLater additions: trustworthiness and worth of data
OLTPOnline transaction processing: many small transactions
OLAPOnline analytical processing: large scans and aggregates
Data warehouseStructured store for analysis (BigQuery, Snowflake, Redshift, ClickHouse)
Data lakeObject storage of raw and curated files
LakehouseTable format and engines giving warehouse behaviour on lake files
ParquetColumnar file format with compression and predicate pushdown
Iceberg, Delta Lake, HudiTable formats with snapshots, schema evolution, row-level changes
ETL, ELTTransform before load, or load first and transform in the warehouse
dbtSQL transformation tool with dependency graph and tests
MapReduceMap, shuffle, reduce batch model from Google (2004)
SparkIn-memory distributed batch and streaming engine
Batch, boundedFinite input processed then stopped
Stream, unboundedContinuous, never-complete input
Event time, processing timeWhen it happened versus when the job saw it
Window (tumbling, sliding, session)Grouping of events by time
WatermarkProgress marker in event time: no earlier event is expected
Late dataEvent arriving behind the watermark
CheckpointConsistent snapshot of state and source offsets
Exactly-onceEffect counted once, via checkpoints or idempotent sinks
Lambda architectureBatch layer, speed layer, serving layer merged at query
Kappa architectureSingle stream path, reprocess by replaying the log
Dataflow model, BeamUnified model for bounded and unbounded data
CDCChange data capture: database changes as events
DebeziumCDC platform that reads database logs, usually on Kafka Connect
Replication slotPostgreSQL mechanism that retains WAL for a consumer
OutboxTable written in the same transaction as the state change, published later
Data meshDomain-owned data products with self-serve platform and federated governance
Data productA dataset with an owner, schema, SLA and documentation
ClickHouse, Pinot, DruidReal-time OLAP serving stores
Pre-aggregation (rollup)Stored sums by dimension to make reads cheap
Feature storeOffline and online store of ML input features
Point-in-time joinJoin that uses feature values as of the label time
LineageRecord of which job and inputs produced a dataset
PIIPersonally identifiable information
RetentionHow long data is kept
CompactionMerging small files or log segments
BackfillRerunning a pipeline for past periods
Schema registryService that stores schemas and enforces compatibility

References ​

Fetched and read on 2026-11-25; text saved under the scratchpad sources/big-data-architectures/.

Built by Morteza Negahi