A way to answer
Part of the free LogicWiz Data Engineering course, Module 17: Pipeline design. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Thursday, 4:30 p.m. Your manager forwards one line from the head of marketing: "We need a dashboard of what customers do in the app." That is the whole requirement, and the design review with Nora is tomorrow at 10. You open a blank page and draw a Kafka box. Then you stop. How many events is "what customers do"? The design round of an interview starts the same way: one vague sentence and 45 minutes.
You'll learn to
- Follow seven steps from a vague request to a design
- Turn the request into volume, peak and freshness numbers
- Say which trade-off you are making, and why
- Plan for a slow stage, a rebuild and a bad month
Learn
One sentence and a blank page
Nora's first rule of design: there is never one right picture. A reviewer, like an interviewer, is checking how you think. Do you ask before you build? Do you size things with numbers? Do you plan for what goes wrong, and know what it costs?
Under pressure people forget half of that. So use the same seven steps for every design, and say each one out loud. This lesson takes marketing's dashboard through all seven. The next three lessons use them on the three designs interviewers ask for most.
The method in seven steps
| Step | Ask | SwiftKart example |
|---|---|---|
| 1. Requirements | Who uses it, for which decision, at what grain? | Marketing: views, carts, purchases per hour |
| 2. Numbers | Volume, peak, freshness, history | 20 million events a day, 15 minutes fresh |
| 3. Sources and sinks | Where does data come from and land? | App events in; a dashboard out |
| 4. Sketch | Source, ingest, store, transform, serve | Kafka, bronze, silver, gold, dashboard |
| 5. Failure modes | Late data, duplicates, reruns, backfills, schema change | Dedup by event id; MERGE; lookback |
| 6. Cost | What runs all day, what is stored? | A micro-batch, not an always-on cluster |
| 7. Monitoring | How will you know it is healthy? | Freshness, row counts, lag, tests |
Write the seven headings down at the start of an interview and fill them in as you go.
Step 1: ask before you draw
You go back to marketing with questions. Ask until you can write the requirement in one sentence:
- Who reads it, and what decision does it drive?
- Which metrics, at what grain (per event, per session, per day)?
- How fresh? Ask what they would do differently if it were fresher.
- How far back, and what is the source of truth?
- Is there personal data?
If an interviewer says "you decide", decide out loud: "I will assume it is read hourly, so 15 minutes is fresh enough. Does that sound right?"
Step 2: count it, roughly
Marketing's answers: views, carts and purchases per hour, no more than 15 minutes behind. Now the numbers. Size four things: volume (rows and bytes a day), peak (the busiest minute is often 3 to 10 times the average), freshness and history.
Rough is fine. A day is 86,400 seconds: call it 100,000. What you need is the order of magnitude, because that picks the tools. 10 GB a day fits on one machine in Postgres or DuckDB. 10 TB a day needs Spark.
And measure what you can. You do not have to guess the size of an event: the store has real ones.
Measure, do not guess: the size of a real event
SELECT COUNT(*) AS events,
COUNT(DISTINCT event_ts::date) AS days,
ROUND(AVG(octet_length(row_to_json(e)::text)), 1) AS avg_bytes
FROM events e;
row_to_json turns a row into JSON and octet_length counts its bytes: about 160 an event. The busiest hour on 1 June held almost 7 times the average hour, so a peak factor of 5 is realistic.
From users to partitions, on the back of an envelope
import math
daily_users = 500_000 # assumption: say it out loud
events_per_user = 40
bytes_per_event = 160 # measured above
peak_factor = 5 # the busiest minute vs the average
per_consumer = 500 # events a second one consumer handles
events_per_day = daily_users * events_per_user
avg_per_sec = events_per_day / 86_400
peak_per_sec = avg_per_sec * peak_factor
raw_gb = events_per_day * bytes_per_event / 1e9
parquet_gb = raw_gb / 8 # columnar and compressed, roughly
partitions = math.ceil(peak_per_sec / per_consumer) * 2 # x2 headroom for growth
print(f'events per day: {events_per_day:,}')
print(f'average {avg_per_sec:,.0f}/s, peak {peak_per_sec:,.0f}/s')
print(f'raw JSON {raw_gb:.1f} GB/day, Parquet {parquet_gb:.2f} GB/day')
print(f'Kafka partitions: {partitions}')
print(f'a year of Parquet: {parquet_gb * 365:,.0f} GB')
Read the output top to bottom: each line uses the one before it. The verdict is small data. A year fits on a laptop disk. Streaming would be a freshness decision here, not a size one.
Turn the numbers into choices
| If the number is | Then lean towards | Because |
|---|---|---|
| Freshness of hours | A daily or hourly batch | Cheapest, simplest to rerun |
| Freshness of 5 to 15 minutes | Micro-batches (availableNow) | No cluster running all day |
| Freshness of seconds | An always-on stream | Only when acting late costs money |
| Under about 50 GB a day | One warehouse or one machine | Spark adds moving parts |
| Terabytes a day | Spark, partitioned Delta tables | Work must spread out |
| A peak of P events a second | About P / per-consumer rate partitions, doubled | Partitions cap parallelism |
Starting points to say out loud, not laws.
Steps 3 and 4: draw it, one box at a time
Now you may draw. Step 3 names the two ends: where the data comes from (the source) and where it must land (the sink). Here: app events in, a dashboard out.
Step 4 is the sketch: the boxes in between. Every pipeline has the same five stages: source, ingest, store, transform, serve. Fill them in from left to right, and give each box a tool and one reason. The reason should point at a number from step 2.
The map below is the empty skeleton. The walkthrough after it fills the skeleton in for marketing's dashboard.
The data lifecycle from source through ingest, store, transform and serve, with quality, orchestration, security and cost underneath, used as the skeleton of a design sketch.
Click a stage to see the tools that fit it. A sketch is this map filled in: one box per stage, each with a tool and one reason.
The sketch for marketing's dashboard, box by box
A left-to-right graph built one box at a time: the apps and the dashboard first, then a collector, a six-partition Kafka topic, bronze, silver and gold, ending with every box carrying its volume or schedule.
Start from the two ends. Step 3: the apps on one side, the dashboard on the other. Everything you add next exists to connect them.
A collector. The apps post events over HTTPS to a small service. It validates each event and adds
received_at, the time it arrived.A buffer. The collector produces to a Kafka topic, keyed by visitor id. Six partitions, because the sizing said so. Seven days of retention, so a slow evening or a broken consumer loses nothing.
Bronze. A micro-batch every 15 minutes lands the raw events as Parquet, 0.4 GB a day. Raw and unchanged, so anything after it can be rebuilt from it.
Silver, then gold. Silver keeps one row per
event_id, so the app's retries are gone. Gold counts views, carts and purchases per hour, merged by hour so that a rerun changes nothing.The finished sketch. The dashboard reads gold. Seven boxes, and each one carries a number or a schedule from step 2: peak 1,157 events a second, 3.2 GB of raw JSON a day.
Follow the arrows from the apps to the dashboard. Grey boxes are not drawn yet; each step colours in one more and says why it is there. Every later lesson in this module draws its design the same way.
Step 5: walk every arrow looking for trouble
Nora looks at the sketch and puts a finger on the first arrow. "What happens when this runs twice?" For every arrow, ask what happens when:
- it runs twice: writes must be idempotent (a MERGE or a partition overwrite, never a blind append);
- data is late: a lookback in batch, a watermark in streaming;
- data is duplicated: dedup on a real key such as
event_id; - a day must be rebuilt: every step takes a date and overwrites only that date;
- the schema changes: a contract, and quarantine for bad rows;
- the source is down: retries, an alert, catch-up.
This is what separates someone who has run a pipeline from someone who has read about one.
When one stage is slower than the next
Back-pressure is what happens when one stage is slower than the stage feeding it. A senior design says where the extra data waits, for how long, and who slows down when the wait is full.
- A buffer. Kafka holds 7 days and bronze 30.
- A throttle. A stream reads a bounded amount per batch (
maxOffsetsPerTriggeron a Kafka source; no limit by default). A backlog becomes many normal batches, not one giant batch that runs out of memory. - The end of the line. When a buffer is full, something must refuse. A Kafka producer buffers 32 MB (
buffer.memory), thensend()blocks for up to 60 s (max.block.ms) and throws. The collector should answer 503, and the app should keep the events and retry with backoff.
How long to catch up after an outage?
lag_hours = 2 # the consumer was down for 2 hours
avg_per_sec = 231 # events keep arriving meanwhile
capacity_per_sec = 6 * 500 # 6 partitions, 500 events a second each
backlog = lag_hours * 3600 * avg_per_sec
drain = capacity_per_sec - avg_per_sec # net speed of catching up
minutes = backlog / drain / 60
print(f'backlog {backlog:,} events')
print(f'drains at {drain:,} a second: {minutes:.0f} minutes to catch up')
print(f'Kafka retention left: {7 * 24 - lag_hours} hours')
The rule: catch-up time = backlog / (capacity - arrival rate). If capacity were 300 a second, barely above the 231 arriving, the same outage would take 6.7 hours to recover. That headroom is why partitions are doubled.
The same 2-hour outage, with and without headroom
Two bars of minutes to catch up after a two-hour outage: 10 minutes when the consumers can read 3,000 events a second, 402 minutes when they can read only 300.
Both bars start from the same backlog, 1,663,200 events, with 231 more arriving every second. Only the headroom differs.
Remember: catch-up time = backlog / (capacity - arrival rate). Size for the peak, then double it. Headroom is what makes an outage short.
Replay: rebuild a bad month on purpose
Five boxes: Kafka keeping 7 days, bronze keeping 30 days, the silver table, a new silver_v2 table and the dashboards; a bug makes a month of silver wrong, it is rebuilt from bronze into silver_v2, compared, and the dashboards are switched over.
A bug ships. Sooner or later one does, and a month of silver is wrong. The dashboards read silver, so they are wrong too. Plan this day before you need it.
From where? From a raw copy that outlives the bug. Kafka keeps 7 days, so it cannot rebuild a month. Bronze keeps 30. Data older than the oldest raw copy cannot be rebuilt at all.
Into what, and how fast? Into a new table,
silver_v2, built beside the old one. Never rebuild in place while dashboards read it. A replay runs at capacity: 600 million events take 56 hours at 3,000 a second, under 6 hours on a batch cluster doing 30,000.Compare, then swap. When
silver_v2passes its checks, the dashboards switch to it. Every write was idempotent, so a replay that dies halfway is run again.
Read the boxes left to right as the pipeline. The 600 million events are 30 days at 20 million a day.
Steps 6 and 7: what it costs, how you know
Cost is mostly compute that runs all the time: a stream costs 24 hours a day, a 10-minute batch costs 10 minutes. Then what you store and for how long, and how much each query scans (partition by date).
Monitoring answers "is it healthy?" before a user asks: freshness of the newest row, volume against a normal day, quality tests, consumer lag, job duration. Each alert needs an owner.
But how fresh is fresh enough? Write the target down. A measured number, such as the freshness of gold (now minus its newest event time), is an SLI. A target for it over a window is an SLO: "gold is under 30 minutes stale in 99% of 5-minute checks over 28 days". What the target allows to fail is the error budget.
A 99% freshness target, counted in checks
One bar of the 8,064 five-minute freshness checks in 28 days, split into 7,984 that must pass and 80 that may fail, the error budget.
The red sliver is the whole budget: 28 days hold 8,064 five-minute checks, and 1% of them is 80, about 6.7 hours of staleness. Deploys and incidents spend it. When it is gone, reliability work comes before new features.
One more question: where are the users?
SwiftKart sells in many countries, so step 1 gets one more question: where are the users, and where may their data live?
- Latency: a phone in Tokyo should not post to a collector in Virginia. Run collectors near users, and carry event time in every event so arrival delay never moves it to the wrong window.
- Residency: rules can require some customers' personal data to stay in their region. Then raw data stays regional and only aggregates travel.
- Failure: active-passive (one region processes, another stands by) or active-active (each region processes its own users). Give two numbers: RPO, how much acknowledged data you may lose, and RTO, how long until it works again.
- Cost: transfer between regions is billed per GB, so copy aggregates, not raw clicks.
The same question, two answers
| Weak answer | Strong answer |
|---|---|
| "Let's use Kafka and Spark." | "Who uses it, and how fresh must it be? What decision does it drive?" |
| "It will scale." | "About 230 events a second, peaking near 1,200: 6 partitions." |
| "We will handle errors." | "Dedup on eventid, a 3-day lookback, MERGE for safe reruns." |
| No word on cost | "A micro-batch every 15 minutes, not an always-on cluster." |
| No word on monitoring | "Alert if gold is 30 minutes stale or row counts halve." |
| "Kafka will buffer it." | "A 2-hour outage leaves 1.7 M events; we drain 2,769 a second net, so 10 minutes." |
| "It is highly available." | "Active-passive, RPO of a few seconds of events, RTO 15 minutes; 99% freshness SLO." |
Do not start with tools. Naming Kafka, Spark and Airflow in the first minute sounds like a shopping list. Tools come at step 4, each with one reason tied to a number from step 2.
Numbers to remember
| Number | Value | Use it for |
|---|---|---|
| Seconds in a day | 86,400, about 100,000 | events a day to events a second |
| Peak against average | 3 to 10 times | size consumers for the peak, not the average |
| One machine or Spark? | 10 GB a day: one machine. 10 TB a day: Spark | the order of magnitude picks the tool |
| Kafka producer buffer.memory | 32 MB | when it is full, send() blocks for max.block.ms (60 s), then throws |
| maxOffsetsPerTrigger | no limit by default | bounds how much a stream reads per batch |
| Retention in this design | Kafka 7 days, bronze 30 days | the oldest raw copy is how far back you can replay |
| Error budget of a 99% SLO | 80 of 8,064 five-minute checks in 28 days | about 6.7 hours of staleness a month |
| Other SLIs | completeness, correctness | rows against the source; tests passing |
At work this method becomes a short design document (often called an RFC) that the team reviews before anyone builds: the same seven headings, a diagram and the open questions.
What changed at SwiftKart
At 10 the next morning you do not show Nora a Kafka box. You show her seven headings, filled in: who reads the dashboard and why, 20 million events a day, a peak near 1,200 a second, six partitions, a micro-batch every 15 minutes, what happens on a rerun, what it costs, and how you will know when it is stale.
She asks three questions and approves it. In an interview, check in the same way as you go: "Shall I go deeper on dedup, or move on?"
The next three lessons are three more reviews with Nora. Lesson 17.2 is the design asked for most often: the daily batch.
In one line
Ask first, count roughly, then draw: requirements, numbers, sources and sinks, sketch, failure modes, cost, monitoring, with every trade-off said out loud.
Interview corner
You are asked to design a data pipeline. How do you start?
"Before I draw anything, I'd like to understand who uses the output and what decision it drives, which metrics and at what grain, and how fresh it needs to be. Then I'll estimate the volume and the peak, sketch the pipeline from source to dashboard, and go through what can go wrong: late data, duplicates, reruns, backfills and schema changes. I'll finish with cost and monitoring. Does that plan work for you?"
How would you estimate the size of this pipeline?
"I'd multiply users by events per user for a daily count, divide by about 100,000 seconds for the average rate, and multiply by a peak factor of around 5, ideally measured from real data. Bytes per event times events gives storage per day; Parquet usually shrinks raw JSON several times. From the peak I size partitions and consumers, and from the daily size I decide whether one machine is enough or I need Spark."
How do you know a pipeline you built is healthy, and how healthy is enough?
"I measure SLIs: freshness, meaning how old the newest row in gold is; completeness against the source; data tests; and for streams, consumer lag. Then I agree SLOs with the users, for example gold under 30 minutes stale in 99% of 5-minute checks over 28 days. That leaves an error budget of 80 checks, about 6.7 hours a month; while we are inside it we ship features, and when it is spent, reliability work comes first."
Your stream consumer was down for two hours. What happens, and how long until it is current?
"Nothing is lost while Kafka retention covers the outage: the events wait as lag. At 231 events a second that is about 1.7 million events. With 6 partitions at 500 a second each, capacity is 3,000 a second, so we drain 2,769 a second net: about 10 minutes. I would cap each batch with maxOffsetsPerTrigger so the first batch is not the whole backlog, and watch the lag fall. If capacity were only just above the arrival rate, recovery would take hours, which is why I size for the peak plus headroom."