AAmit’s LibraryLEARN · PRACTISE · REFLECT
Subjects › Data engineering

Big Data & Data Engineering

Can a shop’s sales figure change after the shop closes, even when yesterday’s sales were recorded correctly? Follow two orders and two late refunds from raw records to a report you can explain. The example is small on purpose: you can inspect every row before trusting a larger pipeline.

1. Start local: SQL and Parquet

SQL is a language for asking questions about tables. Our table’s grain is one delivered message, not one order: the same refund can be delivered twice. The event ID identifies the sale or refund; the order ID ties it back to a purchase. All amounts are positive integer cents. The type tells us whether to add or subtract them.

Open a fresh local SQLite session by typing sqlite3 :memory: in a terminal with SQLite installed. Paste this block once. No account, network, or real customer data is needed. A temporary table disappears when you close the session.

-- Start in a fresh SQLite or DuckDB session. Amounts are whole cents.
CREATE TEMP TABLE arrivals(event_id VARCHAR, order_id VARCHAR, kind VARCHAR,
  effective_day VARCHAR, arrival_day VARCHAR, amount_cents INTEGER);
INSERT INTO arrivals VALUES
 ('S1','O1','sale','2026-11-01','2026-11-01',1200),
 ('S2','O2','sale','2026-11-01','2026-11-01',1800),
 ('R1','O2','refund','2026-11-01','2026-11-02',200),
 ('R2','O2','refund','2026-11-01','2026-11-03',200),
 ('R1','O2','refund','2026-11-01','2026-11-03',200);

-- Collapse exact business payload replays, retaining the first arrival.
CREATE TEMP VIEW first_seen AS
 SELECT event_id,order_id,kind,effective_day,amount_cents,
        MIN(arrival_day) AS seen_on
 FROM arrivals
 GROUP BY event_id,order_id,kind,effective_day,amount_cents;

-- Guardrail: zero rows expected. Stop on any conflicting ID.
SELECT event_id FROM first_seen GROUP BY event_id HAVING COUNT(*) > 1;

-- For a single effective day, reconstruct three historical dashboard views.
WITH cutoffs(as_of) AS (VALUES ('2026-11-01'),('2026-11-02'),('2026-11-03'))
SELECT as_of, COUNT(f.event_id) AS known_events,
       COALESCE(SUM(CASE WHEN kind='sale' THEN amount_cents
                         WHEN kind='refund' THEN -amount_cents END),0) AS net_cents
FROM cutoffs LEFT JOIN first_seen f
  ON f.seen_on <= as_of AND f.effective_day='2026-11-01'
GROUP BY as_of ORDER BY as_of;

The guardrail query should return no rows. The final query should show three rows; keep them for the reconciliation below. To start over, close the session with .quit and open a fresh one.

Optional: store the same records as a Parquet file

SQLite handles the core lab; this extension needs a local DuckDB command-line installation instead. Make a new empty practice folder, open a terminal there, run duckdb, then paste the first SQL block again before this one. The copy command creates a file in that folder.

-- DuckDB only. Run lab.sql in this same session first; use a new folder.
COPY (SELECT * FROM arrivals) TO 'shop-arrivals.parquet' (FORMAT PARQUET);
SELECT kind, COUNT(*) AS deliveries
FROM read_parquet('shop-arrivals.parquet') GROUP BY kind ORDER BY kind;
-- An empty difference in BOTH directions proves full rows and multiplicity match.
SELECT * FROM arrivals EXCEPT ALL SELECT * FROM read_parquet('shop-arrivals.parquet');
SELECT * FROM read_parquet('shop-arrivals.parquet') EXCEPT ALL SELECT * FROM arrivals;

Expect refund | 3 and sale | 2 delivery rows, not three distinct refunds. Neither difference query should return a row. A CSV file stores one record per text row and is easy to inspect, but its reader must interpret text as numbers or dates. Parquet records column types and stores values by column. A reader asking for only the type need not read the amount column; grouping rows into larger files can also reduce file-opening overhead. Five records demonstrate the format, not a speed advantage.

Worked example: Can the same Parquet rows make a query do different work?

A Parquet row group is a block of rows in a file. Within that group, each column has its own chunk. A reader may use a group’s stored minimum and maximum dates to skip that group. If the requested date falls outside the bounds, the group cannot match. If it falls inside, the group might match; we still need to check its rows.

Use four new fictional orders from the same shop. The order values on May 1, 2, 3 and 4 are 60, 112, 70 and 115 whole units. Imagine writing these same four rows in two different layouts and querying the sum for May 2.

Which row groups might contain a May 2 order?
LayoutGroup 1 datesGroup 2 dates
Date-orderedMay 1, May 2May 3, May 4
InterleavedMay 1, May 3May 2, May 4

Work it out: How many groups survive the date check in each layout? Which surviving group contributes nothing? What changes if you ask for May 4 instead?

Check the row-group answers
  • May 2, date-ordered: only group 1 survives. It contains the order worth 112.
  • May 2, interleaved: both groups survive. May 2 lies between the two dates in group 1 but is absent from its rows. Only group 2 contributes. The answer is still 112.
  • May 4: only group 2 survives in each layout; both answers are 115. Ordering need not reduce work for every filter.

This is a bounds simulation, not a speed benchmark. It counts groups the date bounds alone cannot rule out. Real readers may use other metadata; any speed difference depends on the files, query and engine.

Further reading: Parquet file concepts and filtering Parquet reads.

2. Batch or streaming? Decide what waits

In a batch, the shop groups arrivals and runs a report at closing. In a stream, it can update a running total when each message arrives. Both approaches must recognise a replay. Streaming the duplicate faster does not make its amount real.

Walk through the five raw deliveries in their listed order. Add 1,200 and 1,800. Subtract 200 for each new refund ID. The second delivery of R1 changes nothing. The stream reaches 2,600 cents as soon as both distinct refunds arrive; an end-of-day batch reaches the same result at its next run. Interim figures can differ even when both systems are correct.

Try it: what if the shop runs both jobs?

Use the streaming view for a provisional dashboard. Run a daily batch against the raw log to check it. Compare reports for the same effective day and arrival cutoff. If those differ, a mismatch alone is not evidence of an error.

3. Reconcile the late refunds

Effective day means the business day assigned to the transaction. Arrival day means when the reporting pipeline first heard about it. Here the refunds are effective on November 1, even though their messages arrive later. This is our example’s reporting policy, not a universal rule to backdate refunds to a sale.

November 1 net sales as known by each closing
As ofKnown eventsNet (cents)
Nov 123,000
Nov 232,800
Nov 342,600

Explain the difference: 3,000 − 200 − 200 = 2,600. Treat every delivery as a new transaction and you get 2,400. Treat equal amounts as duplicates and you lose a real refund. Instead identify events by ID, collapse exact replays of their business fields, and inspect conflicting versions of a reused ID before reporting.

Check your reasoning: why use the earliest arrival?

Keeping the latest R1 arrival would move a known refund from Nov 2 to Nov 3 in the reconstruction. Taking the earliest arrival preserves what the shop could actually have known at each closing.

The six-stage learning pathway

The three worked exercises above are available now. The map below distinguishes existing readings from suggested next investigations; it does not imply a separate lab has been published for every stage.

  1. SQL, Parquet and local analytics. Start with the shop lab. Compare row counts with distinct events. Use the SQL Atlas for practice.
  2. Distributed computing. A partition divides work. If almost all rows share a single key, one worker may do most of it. A join can require a shuffle: moving matching keys to the same worker. Read Big Data Engineering; ask which key would group an order and its refunds without making one shop dominate.
    Optional paper exercise: Can two workers count the same refund?

    Use the five shop deliveries known by the November 3 close. All amounts are changes to net sales in cents.

    • Worker A receives: S1, order O1, +1,200; R1, order O2, −200; R2, order O2, −200.
    • Worker B receives: S2, order O2, +1,800; an exact replay of R1, order O2, −200.
    1. Each worker discards repeats of an event ID it has already seen and sends a total. What are their totals? Is the combined result right?
    2. Start over. Route O1 to A and O2 to B first. How many deliveries does each worker receive, what total does each send, and what counting error does this prevent?
    3. What if you route by shop instead of by order? Does a correct total prove the work was evenly divided?
    Show the worked partition-key answer

    A sends 800 and B sends 1,600. Each sees R1 only once, so the combined 2,400 counts R1 twice. R2 must still count: it has the same amount but represents a different refund.

    Order routing sends one delivery to A and four to B. A keeps S1 and sends 1,200. B keeps S2, R1 and R2, drops the R1 replay and sends 1,400. The combined total is 2,600. Moving records to bring matching keys together is a shuffle. These routes were assigned by hand: a hash can send different orders to the same worker.

    All deliveries belong to one shop, so routing by shop puts all five on one worker. Even order routing gives a 1-to-4 delivery split. This uneven distribution is skew. Record counts suggest imbalance but are not a runtime benchmark.

    Check the assumption: Each event ID must identify one business event globally. A replay must preserve its order, type, effective date and amount even if it arrives later. If a copy of R1 wrongly names a different order, it could reach a different worker. To catch such conflicts, check records by event ID upstream and set conflicting versions aside before totaling.

  3. Batch and streaming. Compare the two update clocks and late-event reconciliation. Decide how long a dashboard should say “provisional”.
  4. Warehouses, lakehouses and analytics engineering. A warehouse serves structured reporting tables; a lakehouse adds table-management features over files. A Parquet folder by itself is not a lakehouse. Sketch a raw arrivals table, a cleaned events table and a daily sales table. Which one can reproduce an old report?
  5. Governance, quality, reliability and cost. Ask who owns each column, how a replay is detected and what it costs to recompute. Start with Data Governance. Keep a failing record for investigation rather than silently discarding it.
  6. Data for AI, search and machine learning. If predicting at the Nov 1 close, using the Nov 3 refund information leaks the future. Train and evaluate with a cutoff. For a later search project, compare keyword retrieval with embeddings (numeric representations) using the same relevance judgments.

Next: follow the data engineering chapter for pipeline foundations, or return to the subject map.