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 for | Go to |
|---|---|
| The whole chapter in a few tables | Everything in one minute |
| Why big-data architecture exists | Why it exists |
| Laney 2001, MapReduce, Marz, Kreps, Dataflow, Lakehouse, Mesh | Where it comes from |
| Volume, velocity, variety, veracity, value | The five Vs |
| Why you do not run reports on the order database | OLTP vs OLAP |
| Nightly jobs, MapReduce, Spark, warehouses, dbt | Batch processing |
| Event time, windows, watermarks, state, Flink, Kafka Streams | Stream processing |
| At-least-once, exactly-once, idempotent sinks | Delivery semantics |
| Batch + speed + serving layers, code duplication | Lambda |
| One log, replay, when it fails | Kappa |
| Dataflow model, Beam, "unbounded vs bounded" | Unified models |
| Lake, warehouse, lakehouse, Parquet, Iceberg, Delta | Storage tiers |
| Debezium, WAL, snapshots, outbox | CDC |
| Data mesh versus a central platform | Data mesh |
| ClickHouse, Pinot, Druid, pre-aggregation | Serving analytics |
| Feature pipelines for ML | ML features |
| Schemas, lineage, PII, retention | Governance |
| Cost and operational complexity | Cost |
| Go and Laravel code | Go, Laravel |
| Order analytics as batch, Lambda, Kappa | Worked example |
| Monolith to distributed scale | In architecture |
| Hands-on exercise | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked later.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Volume | How much data | 2 million orders a day, 700 million a year | Reports on the live database slow the shop down |
| Velocity | How fast it arrives and how fast answers are needed | 300 orders a second at peak, dashboard fresh within 10 s | Yesterday's numbers during a flash sale |
| Variety | Many shapes of data | Rows, JSON events, logs, images, CSV from partners | One rigid schema rejects half the sources |
| Veracity | How far you can trust it | Duplicate events, clock skew, bots | Confident dashboards that are wrong |
| Value | What the answer is worth | Churn prediction pays for the pipeline, or does not | A costly platform nobody uses |
| OLTP | Many small transactions that change data | INSERT INTO orders | Mixing it with scans stalls checkout |
| OLAP | Few big queries that read lots of data | Revenue by country by day | Analytics fight for the same locks and cache |
| Batch | Process a bounded set, then stop | Nightly "yesterday's orders" | Not fresh; but simple and exact |
| Stream | Process an unbounded flow as it arrives | Orders per minute, live | Complex: time, state, late data |
| Event time | When it happened | Order placed 10:00:50 | Wrong windows after a delay |
| Watermark | "No older event will arrive" claim | Newest 10:02:10 minus 30 s | Windows never close, or close too early |
| Lambda | Batch layer plus speed layer, merged at query | Nightly truth plus last-hours increment | Two codebases that disagree |
| Kappa | One stream job, replay the log to fix history | Rerun from offset 0 into a new table | Needs long retention and a fast replay |
| CDC | Turn database changes into events | Debezium reads the PostgreSQL WAL | Dual writes and polling updated_at |
| Lakehouse | Warehouse features on open files in object storage | Iceberg tables of Parquet files | Two copies of data and ETL between them |
| Data mesh | Domain teams own analytical data as products | orders team publishes orders_daily | A central team becomes the bottleneck |
The four paths from "an order happened" to "an answer".
| Path | Freshness | Complexity | Typical tools | Start here when |
|---|---|---|---|---|
| Read replica + SQL | seconds | lowest | PostgreSQL replica, materialized view | Data under about 1 TB, few analysts |
| Nightly batch ELT | hours to a day | low | Laravel command or Airflow, dbt, warehouse | Reports are daily or weekly |
| CDC + warehouse | minutes | medium | Debezium, Kafka, ClickHouse or BigQuery | Dashboards need minutes, source stays OLTP |
| Stream processing | seconds or less | high | Kafka, Flink, Kafka Streams, Pinot | Alerts, fraud, live counters |
Lambda, Kappa and "just batch" at a glance.
| Batch only | Lambda | Kappa | |
|---|---|---|---|
| Code paths | 1 | 2 (batch and speed) | 1 |
| Freshness | hours | seconds plus hours-accurate | seconds |
| Fix a bug in history | rerun the job | rerun the batch layer | replay the log |
| Needs a long-retention log | no | helps | yes (or lake replay) |
| Main risk | stale data | two implementations drift | replay 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 warehouse | Streaming with event time, state and replay |
| One storage system | Lake plus warehouse plus serving store |
| Central data team | Data mesh with domain ownership |
| Exact results next morning | Approximate or revisable results in seconds |
| Cheap, easy to debug | Expensive, 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
- "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.
- "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".
- "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."
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 clusterReal 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 windowReal 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.
| V | Question it asks | First tool to reach for | Typical failure |
|---|---|---|---|
| Volume | Does it fit one box and one query budget? | Partitioned PostgreSQL, then a column store | Scanning the OLTP database |
| Velocity | How fresh must the answer be? | Micro-batch before stream | Streaming a report read weekly |
| Variety | How many shapes and sources? | Raw landing zone plus schema registry | Rigid schema rejecting sources |
| Veracity | Can I trust it? | Idempotency, data tests, reconciliation | Wrong numbers with confidence |
| Value | Who uses it and what is it worth? | A named consumer per dataset | Platform 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 downReal scenario: a marketing export runs for 40 minutes on the primary at 09:00; checkout p99 triples; the incident review recommends a warehouse.
| Axis | OLTP | OLAP |
|---|---|---|
| Query shape | Point lookup, short write | Scan, aggregate, join of facts and dimensions |
| Rows per query | 1 to 100 | millions to billions |
| Storage layout | Row-oriented pages (heap, B-tree) | Column-oriented, compressed |
| Concurrency | thousands of small transactions | tens of heavy queries |
| Consistency need | Strong, serialisable where needed | Snapshot per query; eventual vs source |
| Examples | PostgreSQL, MySQL/InnoDB, SQL Server, Oracle | ClickHouse, BigQuery, Redshift, Snowflake, DuckDB |
| Freshness vs source | current | minutes to a day behind |
Fix, in order of cost.
-- 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 inputsReal 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).
| Concept | Meaning | Why it matters |
|---|---|---|
| Bounded input | Finite dataset known at start | You can compute exact results |
| Idempotent run | Same input gives the same output, rerun is safe | Retry without fear |
| Partition overwrite | Replace day=... as a unit | No half-written day visible |
| Backfill | Rerun for past dates | Fixing a bug in history |
| Shuffle | Redistribute rows by key across machines | The expensive step of joins and group-bys |
| DAG | Dependency graph of steps | Airflow, 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-- 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| Style | Transform where | Strength | Weakness |
|---|---|---|---|
| ETL | In a pipeline server before load | Sensitive data cleaned before storage | Pipeline code is the bottleneck |
| ELT | In the warehouse | Scales with the warehouse, SQL, reruns easy | Raw sensitive data lands first (mask it) |
| Reverse ETL | Warehouse back to SaaS tools | Activates analytics | Another 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 hereReal scenario: fraud rules, live inventory, alerting on error rates, per-minute order counts, session analytics.
| Engine | Model | State | Strength | Pick when |
|---|---|---|---|---|
| Apache Flink | True streaming, event time first | Managed keyed state, checkpoints | Low latency, rich windowing | Heavy stateful streaming |
| Kafka Streams | A Java library inside your app | State stores backed by changelog topics | No cluster to run beyond Kafka | JVM team, Kafka-centric |
| Spark Structured Streaming | Micro-batches (and continuous mode) | State in the Spark engine | Same API as batch Spark | You already run Spark |
| Apache Beam | Portable model, runs on Flink, Spark, Dataflow | Per runner | One program, many runners | Cloud Dataflow or portability |
| ksqlDB | SQL over Kafka | Kafka-backed | Quick SQL streams | SQL-first teams |
| Go consumer (franz-go) | Hand-written loop | In memory or your store | Tiny and explicit | Simple windows, see Go |
| Laravel queue worker | Job per message | Database or cache | Familiar | Low-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| Window type | Shape | Example | Product |
|---|---|---|---|
| Tumbling | Fixed, no overlap | Orders per minute | Flink, Kafka Streams, Beam |
| Sliding (hopping) | Fixed size, advances by a smaller step | Last 10 minutes, every minute | Flink, Kafka Streams, Beam |
| Session | Closes after an inactivity gap | A user visit | Flink, Beam |
| Global | One window for all, with triggers | Running total | Beam, Flink |
| Late-data policy | What happens | Cost |
|---|---|---|
| Drop | Ignore events behind the watermark | Under-count, simple |
| Allowed lateness | Keep the window state a while, re-emit updates | State memory, downstream must accept updates |
| Side output | Route late events to a separate stream | Reconcile in batch later |
| Bigger watermark delay | Wait longer before closing | Higher 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| Sink | How to get an effect-once result |
|---|---|
| PostgreSQL / warehouse | INSERT ... ON CONFLICT DO UPDATE keyed by event id |
| ClickHouse | ReplacingMergeTree 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 topic | Transactions with read_committed consumers |
| Search / cache | Idempotent 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."
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 discardedReal 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.
| Layer | Job | Typical tools (then and now) | Failure mode |
|---|---|---|---|
| Master dataset | Immutable raw facts | HDFS, S3 or GCS, Kafka | Mutated by mistake: "human fault-tolerance" lost |
| Batch layer | Recompute everything | Hadoop, Spark, warehouse SQL | Runs for hours, misses the last hours |
| Speed layer | Incremental, recent | Storm, Flink, Kafka Streams, Spark Streaming | Approximate or late-data errors |
| Serving layer | Merge and answer | HBase, Cassandra, Druid, ClickHouse | Merge logic bugs, double counting at the seam |
| Pros | Cons |
|---|---|
| Immutable input, easy human-error recovery | Same logic in two systems, kept in sync by hand |
| Batch result is exact and reproducible | Two clusters to run, monitor and pay for |
| Fresh answer for the last hours | The 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 engines | Obsolete 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.
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_v1Real 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.
| Situation | Why Kappa struggles | What to do |
|---|---|---|
| Years of history | Replaying a year through a stream job is slow and costly; broker storage is expensive | Tiered storage, or replay from a lake via the same engine in batch mode |
| Log compaction | A compacted topic keeps only the latest value per key, so history is gone | Keep a separate full-history topic or lake copy |
| Non-deterministic logic | Calls to external services give different answers on replay | Make the job a pure function of the log; snapshot lookups |
| Ordering across partitions | Replay races produce different results | Key by entity; use event time and watermarks |
| Heavy ML retraining | Needs scans and joins over all data | Batch on the lake or warehouse |
| Output store cannot absorb a bulk reload | Kreps: needs "a database that supports high-volume writes for the re-load" | Load to a new table, then switch |
| Schema changes in old events | Old events do not fit the new logic | Upcasters, schema registry, versioned decoding |
| Pros | Cons |
|---|---|
| One codebase, one engine | Needs long retention and replay throughput |
| Reprocessing is a redeploy | Temporary 2x output storage during replay |
| Easier to test and reason about | Weak fit for large historical joins and ML training |
| Rollback is a table switch | Stream 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| Question | Beam concept | Plain meaning |
|---|---|---|
| What | Transforms (ParDo, GroupByKey, Combine) | The computation |
| Where | Windowing | Grouping by event time |
| When | Triggers and watermarks | Emit moment |
| How | Accumulation mode | Do 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| Tier | Holds | Cost | Governance | Products |
|---|---|---|---|---|
| Data lake | Raw and curated files | lowest per TB | weak unless added | S3, GCS, Azure Blob + Parquet |
| Data warehouse | Modelled tables | higher per TB | strong: schema, access | BigQuery, Snowflake, Redshift, ClickHouse |
| Lakehouse | Table format over lake files | low | medium to strong | Iceberg, Delta Lake, Apache Hudi, Databricks |
| Serving store | Pre-aggregated, indexed | highest per TB | per product | ClickHouse, Pinot, Druid, Redis |
| File / table format | Kind | Notes |
|---|---|---|
| Parquet | Columnar file | The usual file; row groups, column chunks, dictionary encoding, predicate pushdown |
| ORC | Columnar file | Hive ecosystem |
| Avro | Row file with schema | Good for Kafka and raw landing |
| Iceberg | Table format | Snapshots, hidden partitioning, schema evolution |
| Delta Lake | Table format | Transaction log over Parquet |
| Hudi | Table format | Upserts, 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 pitfall | Symptom | Remedy |
|---|---|---|
| Small files | Thousands of 1 MB files, slow queries | Compaction jobs, larger batch writes |
| Wrong partition key | Scans everything or creates millions of directories | Partition by date, cluster by a high-cardinality key |
| No schema contract | Columns change type silently | Schema registry, table-format evolution rules |
| No delete path | Privacy deletion impossible | Table 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.
| Method | Captures deletes | Load on source | Ordering | Notes |
|---|---|---|---|---|
| Log-based CDC (Debezium) | yes | low | per primary key, from the WAL | Needs wal_level=logical, a replication slot |
| Trigger-based | yes | adds write cost | yes | Simple but invasive |
Query-based (updated_at polling) | no | scans | weak | Cheap start, lossy |
| Dual write | n/a | none | none | Unsafe: partial failure |
| Outbox | only what you write | 1 extra insert | yes | Publishes 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 team | Data mesh | |
|---|---|---|
| Who builds pipelines | One data team | Domain teams on a shared platform |
| Bottleneck | The central queue | Platform maturity and domain skills |
| Context knowledge | Weak (far from the domain) | Strong |
| Consistency | Easy: one team, one style | Hard: needs federated rules |
| Best size | Up to roughly a few dozen engineers | Many domains and teams |
| Risk | Slow, backlog | Duplicated 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-- 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;| Store | Strength | Update model | Typical use |
|---|---|---|---|
| ClickHouse | Very fast scans, SQL, simple ops | Append, merge-time dedupe (ReplacingMergeTree) | Product analytics, logs, order metrics |
| Apache Pinot | Low-latency user-facing queries at high concurrency | Real-time and offline segments, upsert tables | User-facing analytics at high concurrency |
| Apache Druid | Time-series rollups, ingestion-time rollup | Append with rollup, segment compaction | Event analytics, dashboards |
| Elasticsearch / OpenSearch | Search plus aggregates | Document upsert | Search-led analytics |
| Redis | Counters, sorted sets | in-place | Tiny hot aggregates |
| PostgreSQL + indexes / materialized views | Familiar | normal | Under 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 valuesGovernance
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| Control | What it prevents | Example tooling |
|---|---|---|
| Schema registry | Breaking consumers | Confluent Schema Registry, Apicurio |
| Data tests | Bad rows | dbt tests, Great Expectations |
| Lineage | Unknown blast radius | OpenLineage, dbt docs, DataHub |
| PII tagging and masking | Leaks | Column masking in the warehouse, tokenisation |
| Retention policy | Hoarding risk | Topic retention, table TTL, lifecycle rules |
| Access control | Over-broad reads | Roles, 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.
| Choice | Cost driver | Complexity added | Cheaper alternative |
|---|---|---|---|
| Streaming engine | Always-on cluster, state storage, on-call | High: time, state, replay | Micro-batch every few minutes |
| Lambda | Two stacks | Very high: two codebases | Kappa, or batch plus a small stream |
| Lake plus warehouse | Two copies of data | Medium: sync and ETL | Lakehouse or one warehouse |
| Kafka long retention | Broker disk or tiered storage | Medium | Replay from the lake |
| Real-time OLAP store | Memory and nodes | Medium | Pre-aggregate in the warehouse |
| Data mesh | Platform team plus domain staff | Organisational | Central team for small orgs |
| Warehouse full scans | Per-query bytes scanned | Low | Partitioning, 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), warehouseSolving the classic problems: how a product team starts small
| Stage | Trigger | What you build | Do not build yet |
|---|---|---|---|
| 0. Replica | Reports slow the primary | Read replica, materialized views | Anything else |
| 1. Nightly ELT | Analysts need joins, history | Laravel/Go export to a warehouse table, dbt marts | Streaming |
| 2. CDC | Reports need minutes of freshness | Debezium to Kafka to warehouse (or managed CDC) | A second compute engine |
| 3. Serving store | Product-facing dashboards | ClickHouse or Pinot with rollups | Lambda |
| 4. Stream jobs | A rule truly needs seconds (fraud, alerts) | Kafka Streams or Flink for that rule only | Rewriting every report as a stream |
| 5. Lake / lakehouse | Many sources, ML, cheap raw history | Object storage with Iceberg or Delta | A mesh before you have many teams |
| 6. Mesh | Many domain teams, central queue is the bottleneck | Platform, 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.
// 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.
// 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.
// 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.
// 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
| Need | Go choice | Notes |
|---|---|---|
| Kafka client | franz-go (kgo) | Consumer groups, transactions, fast; segmentio/kafka-go is an alternative |
| Parquet | parquet-go/parquet-go | Generic writer with struct tags |
| Avro / Protobuf | hamba/avro, google.golang.org/protobuf | Pair with a schema registry client |
| Warehouse insert | clickhouse-go, pgx CopyFrom, BigQuery client | Prefer big batches over single rows |
| Windows and state | Hand-written, or call Flink for hard cases | Beyond simple windows use a real engine |
| Concurrency | Goroutine per partition | Keep 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
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
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
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
| Need | Laravel 13 feature | Notes |
|---|---|---|
| Reliable emission | DB::transaction + outbox table | Publisher is outside Laravel (relay, Debezium) |
| Domain events in process | Events and listeners (queued with ShouldQueue) | Not durable analytics transport on its own |
| Nightly batch | Artisan command + scheduler (Schedule::command(...)->dailyAt('02:00')->onOneServer()) | One server runs it; make it idempotent |
| Large reads | lazyById, chunkById, cursor | lazyById for stable memory |
| Bulk load | upsert, insert in batches | Batch size 500 to 5000 rows |
| Warehouse connection | A second connection in config/database.php | Separate credentials, read-only for the source |
| Long jobs | Queue 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 agreeOption 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| Criterion | A: Nightly batch | B: Lambda | C: Kappa |
|---|---|---|---|
| Meets "last hour in 10 s" | No | Yes | Yes |
| Finance exact daily total | Yes | Yes (batch view) | Yes (after correct replay) |
| Code paths for the revenue rule | 1 (SQL) | 2 (SQL + Flink) | 1 (Flink) |
| Systems to run | Source DB, warehouse | Kafka, Spark or warehouse, Flink, serving store | Kafka, Flink, ClickHouse, lake archive |
| Fix a historic bug | Rerun the day | Rerun batch, patch speed layer | Replay the log into a new table |
| Team size needed (guess) | 1 engineer part-time | 3 or more | 2 to 3 |
| Failure surface | Small | Largest (seam, drift) | Medium (state, replay) |
| When it is right | Reports only | Legacy with separate batch and stream stacks | New 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
| Requirement | Recommended path | Extra technique | Reason |
|---|---|---|---|
| Daily and weekly reports | Nightly ELT into a warehouse | dbt tests, partition overwrite | Simple, exact, rerunnable |
| Dashboard fresh within minutes | CDC to warehouse or ClickHouse | Idempotent upsert, reconciliation counts | No second codebase |
| Product-facing analytics, many users | Real-time OLAP (ClickHouse, Pinot, Druid) | Pre-aggregated rollups | Sub-second at high concurrency |
| Fraud, alerts, live rules | Stream job (Flink, Kafka Streams) | Event time, state TTL, DLQ | Latency in seconds |
| Fix history after a logic change | Kappa replay or batch rerun | New output table, then switch | Avoids in-place corruption |
| Existing separate batch and stream stacks | Keep Lambda, hide the merge in one query layer | Shared test vectors for both paths | Rewrite cost is high |
| Many sources, ML, cheap raw history | Lake plus table format (Iceberg, Delta) | Compaction, catalog | Open formats, many engines |
| Many autonomous domain teams | Data mesh on a self-serve platform | Federated governance | Central team is the bottleneck |
| Data under about 1 TB, few analysts | PostgreSQL replica and materialized views | Partitioning | Do 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)
| Scale | Orders per day | Design | What changes |
|---|---|---|---|
| 1x | 20 thousand | Replica, materialized views | Nothing exotic |
| 10x | 2 million | Nightly ELT to one warehouse node, dbt | A second system, one owner |
| 100x | 200 million | CDC and Kafka, ClickHouse cluster or BigQuery, partitioned Parquet in a lake | Streaming ingest, compaction, schema registry |
| 1000x | 2 billion | Stream jobs for rules, tiered Kafka storage, lakehouse, possibly mesh | Platform 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.
- Source and replica of facts. Run PostgreSQL and create the table.
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- 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). - Add the materialized view from the OLTP section, refresh it, query
sales_daily(expected: under 5 ms). - Batch ELT. Run
go run ./parquetto 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). - Windows and lateness. Run
go run ./windows(expected:window 10:00 closed: 1500 cents,late events dropped: 1). ChangeAllowedLatenessto 90 seconds and predict, then check, which events are now kept. - Idempotency. Feed the same Debezium JSON to
Applytwice with an in-memorySinkthat stores rows by id; the count must stay the same. Break it by usingINSERTinstead of upsert and watch it double. - 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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| 3Vs | Laney 2001: volume, velocity, variety; veracity and value were added later |
| Start | PostgreSQL replica, then nightly ELT, then CDC; stream only when needed |
| OLTP vs OLAP | Rows and point lookups versus columns and scans; do not mix on one box |
| Batch | Bounded, idempotent, rerunnable; partition overwrite; backfill |
| ELT | Load raw first, transform in the warehouse with tested SQL (dbt) |
| Event time | Use it for windows; processing time breaks replays |
| Watermark | newest event time minus allowed delay; closes windows; late-data policy needed |
| Exactly-once | At-least-once plus idempotent sink or transactions |
| Lambda | Batch plus speed plus serving; cost is two codebases (Kreps) |
| Kappa | One job, retained log, replay into a new table, then switch |
| Dataflow/Beam | Bounded and unbounded are the same model; engines differ |
| Lakehouse | Parquet files plus Iceberg or Delta table format |
| CDC | Read the WAL (Debezium); events have before, after, op, ts_ms; watch replication slots |
| Mesh | Four principles: domain ownership, data as product, self-serve platform, federated governance |
| Serving | ClickHouse, Pinot, Druid; pre-aggregate; keep raw too |
| Governance | Schema registry, lineage, PII tags, retention, deletion path |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Volume, Velocity, Variety | Laney's three dimensions: how much, how fast, how many shapes |
| Veracity, Value | Later additions: trustworthiness and worth of data |
| OLTP | Online transaction processing: many small transactions |
| OLAP | Online analytical processing: large scans and aggregates |
| Data warehouse | Structured store for analysis (BigQuery, Snowflake, Redshift, ClickHouse) |
| Data lake | Object storage of raw and curated files |
| Lakehouse | Table format and engines giving warehouse behaviour on lake files |
| Parquet | Columnar file format with compression and predicate pushdown |
| Iceberg, Delta Lake, Hudi | Table formats with snapshots, schema evolution, row-level changes |
| ETL, ELT | Transform before load, or load first and transform in the warehouse |
| dbt | SQL transformation tool with dependency graph and tests |
| MapReduce | Map, shuffle, reduce batch model from Google (2004) |
| Spark | In-memory distributed batch and streaming engine |
| Batch, bounded | Finite input processed then stopped |
| Stream, unbounded | Continuous, never-complete input |
| Event time, processing time | When it happened versus when the job saw it |
| Window (tumbling, sliding, session) | Grouping of events by time |
| Watermark | Progress marker in event time: no earlier event is expected |
| Late data | Event arriving behind the watermark |
| Checkpoint | Consistent snapshot of state and source offsets |
| Exactly-once | Effect counted once, via checkpoints or idempotent sinks |
| Lambda architecture | Batch layer, speed layer, serving layer merged at query |
| Kappa architecture | Single stream path, reprocess by replaying the log |
| Dataflow model, Beam | Unified model for bounded and unbounded data |
| CDC | Change data capture: database changes as events |
| Debezium | CDC platform that reads database logs, usually on Kafka Connect |
| Replication slot | PostgreSQL mechanism that retains WAL for a consumer |
| Outbox | Table written in the same transaction as the state change, published later |
| Data mesh | Domain-owned data products with self-serve platform and federated governance |
| Data product | A dataset with an owner, schema, SLA and documentation |
| ClickHouse, Pinot, Druid | Real-time OLAP serving stores |
| Pre-aggregation (rollup) | Stored sums by dimension to make reads cheap |
| Feature store | Offline and online store of ML input features |
| Point-in-time join | Join that uses feature values as of the label time |
| Lineage | Record of which job and inputs produced a dataset |
| PII | Personally identifiable information |
| Retention | How long data is kept |
| Compaction | Merging small files or log segments |
| Backfill | Rerunning a pipeline for past periods |
| Schema registry | Service that stores schemas and enforces compatibility |
References
Fetched and read on 2026-11-25; text saved under the scratchpad sources/big-data-architectures/.
- Doug Laney, 3D Data Management: Controlling Data Volume, Velocity, and Variety, META Group, 6 February 2001 (Internet Archive copy of the Gartner blog PDF): https://web.archive.org/web/2012/https://blogs.gartner.com/doug-laney/files/2012/01/ad949-3D-Data-Management-Controlling-Data-Volume-Velocity-and-Variety.pdf
- Nathan Marz, How to beat the CAP theorem, 13 October 2011: http://nathanmarz.com/blog/how-to-beat-the-cap-theorem.html
- Jay Kreps, Questioning the Lambda Architecture, O'Reilly Radar, 2 July 2014: https://www.oreilly.com/radar/questioning-the-lambda-architecture/
- Akidau et al., The Dataflow Model, VLDB 2015: https://www.vldb.org/pvldb/vol8/p1792-Akidau.pdf
- Armbrust, Ghodsi, Xin, Zaharia, Lakehouse: A New Generation of Open Platforms that Unify Data Warehousing and Advanced Analytics, CIDR 2021: https://www.cidrdb.org/cidr2021/papers/cidr2021_paper17.pdf
- Zhamak Dehghani, Data Mesh Principles and Logical Architecture, 3 December 2020: https://martinfowler.com/articles/data-mesh-principles.html
- Apache Flink, Timely Stream Processing: https://nightlies.apache.org/flink/flink-docs-stable/docs/concepts/time/ and Stateful Stream Processing: https://nightlies.apache.org/flink/flink-docs-stable/docs/concepts/stateful-stream-processing/ and Generating Watermarks: https://nightlies.apache.org/flink/flink-docs-stable/docs/dev/datastream/event-time/generating_watermarks/
- Debezium reference and PostgreSQL connector: https://debezium.io/documentation/reference/stable/ and https://debezium.io/documentation/reference/stable/connectors/postgresql.html
- dbt introduction: https://docs.getdbt.com/docs/introduction
- ClickHouse introduction: https://clickhouse.com/docs/en/intro
- Apache Beam programming guide: https://beam.apache.org/documentation/programming-guide/
- Laravel 13: Collections (LazyCollection) https://laravel.com/docs/13.x/collections, Eloquent chunking and lazy https://laravel.com/docs/13.x/eloquent, Query builder https://laravel.com/docs/13.x/queries, Scheduling https://laravel.com/docs/13.x/scheduling, Strings (
Str::uuid7) https://laravel.com/docs/13.x/strings - Not re-fetched this session (the Kafka docs site served a JavaScript redirect): Kafka Streams
processing.guarantee; MapReduce and GFS papers; Kleppmann, Designing Data-Intensive Applications, chapters on batch and stream processing.