# Batch Processing

**Also known as:** MapReduce · ETL jobs  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/data-storage/batch-processing

*One job over a fixed dataset: read it all, compute, replace the output.*

A batch job processes a dataset that has an end: yesterday's logs, last month's orders, a full table export. It reads all of it, computes, writes the result and stops. Nightly ETL, report builds, search-index rebuilds and machine-learning training sets work this way. Spark, Hadoop and SQL engines over a data lake, such as Trino or BigQuery, are common tools.

Batch trades latency for simplicity. Results are hours old, but the input does not change while the job runs, so there is no late data and no state to carry between runs. A run that fails, or that had a bug, is fixed by running it again on the same input. Protect that property in every job you write.

> **In one sentence.** A batch job reads a bounded input and replaces a whole output partition; because the input is fixed and the output is overwritten, any run can be repeated safely.

## Origin (2004)

Google's MapReduce paper (Dean and Ghemawat, 2004) showed how to run one job on thousands of cheap machines and retry failed tasks automatically. Hadoop made it open source. Apache Spark later kept intermediate data in memory, which made jobs with many steps much faster. Batch itself is far older: mainframes ran overnight jobs for decades before.

## How it works

### Split, shuffle, merge (Map · Shuffle · Reduce)

The input is split into chunks and each worker processes one chunk on its own (map). Records are then regrouped by key across the network, so every value for one key reaches one worker (shuffle). That worker combines them (reduce).

- The map step runs in parallel with no coordination
- The shuffle is the expensive step: sorting, disk and network
- Reduce sees every value for one key together

> map: order → (customerId, amount) · shuffle by customerId · reduce: sum(amount)

### Partitioning

Inputs and outputs are stored in partitions, usually by date and sometimes also by a key. A job reads only the partitions it needs and writes only its own.

- Partition by the column every job filters on, usually the date
- Thousands of tiny files slow down every reader
- One huge key makes one task run far longer than the rest

> s3://lake/orders/dt=2026-11-05/part-0000.parquet

### Idempotent, re-runnable jobs

A job is a function of its input: the same input partition always produces the same output partition. It writes to a staging location and then swaps the result in, replacing whatever was there.

- Overwrite a partition, never append to it
- Swap atomically, so readers see the old day or the new one, never half
- Pass the run date in; never read the clock inside the logic

### Backfills

Running a job again for past dates, after a bug fix or to fill a new column. When jobs are idempotent and take the date as a parameter, a backfill is just the normal job run for many dates.

- Run oldest first when a day depends on the day before
- Limit how many run at once, so the daily run is not starved

### Scheduling and dependencies

Jobs form a graph: the report runs after the cleaned orders, which run after the raw export lands. A scheduler such as Airflow or Dagster starts each job when its inputs exist, and retries it when it fails.

- Wait for data, not for a time of day
- Tie every run to the logical date it computes
- Retries are safe only because the jobs are idempotent

## Design rules

### Make the run date a parameter

A job computes the partition for a date it is given. It never asks for today's date. Then a retry, a rerun and a backfill are all the same operation as the daily run.

### Replace whole partitions

Write to a staging table or path, check it, then swap it in atomically. A job that appends rows doubles them on every rerun.

### Keep the raw input immutable

Store what arrived exactly as it arrived, and derive everything else from it. A bug in a derived table is then fixed by fixing the code and rerunning, with nothing lost.

### Check the output before you publish it

Compare row counts and key totals with the input and with the previous run. A job that succeeds and writes zero rows is the most common silent failure.

## Examples

### A daily job that replaces its partition, and a backfill that reuses it

```typescript
// Rebuild one day of revenue per customer. The scheduler passes the date in;
// the job never reads the clock, so a rerun for the same date gives the same rows.
export async function dailyRevenue(db: Db, runDate: string): Promise<void> {  // "2026-11-05"
  await db.transaction(async (tx) => {
    // 1. Replace, never append.
    await tx.query("delete from daily_revenue where day = $1", [runDate]);
    const { rowCount } = await tx.query(
      `insert into daily_revenue (day, customer_id, orders, revenue)
       select $1::date, customer_id, count(*), sum(amount)
       from orders_raw
       where created_at >= $1::date and created_at < $1::date + 1   -- bounded by the date
       group by customer_id`,
      [runDate],
    );
    // 2. Check before publishing: a "successful" run with no rows is the classic silent failure.
    if (rowCount === 0) throw new Error("no orders for " + runDate + ": did the input land?");
  });
  // 3. Readers saw the old day until commit, and the new day after it. Never half of one.
}

// A backfill is the same job, run for many dates.
for (const day of daysBetween("2026-10-01", "2026-10-31")) {
  await dailyRevenue(db, day);
}
```

Delete and insert in one transaction is the whole idempotency mechanism. On a data lake the same idea is INSERT OVERWRITE on a date partition, or writing to a new path and moving a pointer to it.

## When to use

- Results can be hours old: reports, billing runs, nightly exports
- The work needs the whole dataset at once: training sets, full reindexes, deduplication
- History must be reprocessed after a bug fix or for a new metric

## When not to use

- Users or systems must react within minutes: use stream processing
- Each record needs its own immediate action, such as a welcome email: use a queue
- The data is small enough for one query on the live database

## Benefits

- Simple to reason about: fixed input, no late data, no long-lived state
- A failed or buggy run is fixed by running it again
- High throughput on cheap capacity that only runs when needed

## Costs

- Results are as old as the schedule, often a whole day
- Large jobs need a cluster, and the shuffle dominates their cost
- Chains of jobs fail late: one slow input delays everything after it

## Pitfalls

- A job that appends rows, so a retry after a timeout doubles yesterday's revenue.
- Using now() or "today" inside the job, so a backfill for March computes November.
- Starting at 02:00 on the clock while the export lands at 02:20, and publishing half a day.
- One customer with millions of orders, so one task runs for hours while the others sit idle.
- Writing thousands of tiny files that make every later read slow.

## Related patterns

- [Stream Processing](https://layra4.dev/architectures/data-storage/stream-processing) — when results must be minutes old, not hours
- [Column-Oriented Storage](https://layra4.dev/architectures/data-storage/column-oriented-storage) — the storage layout that makes scans over big tables fast
- [Object Storage](https://layra4.dev/architectures/data-storage/object-storage) — where input and output partitions usually live
- [Idempotency](https://layra4.dev/architectures/key-design-principles/idempotency) — why a rerun must give the same result
- [Change Data Capture](https://layra4.dev/architectures/data-storage/change-data-capture) — copies database changes into the job's input

## Further reading

- *MapReduce: Simplified Data Processing on Large Clusters* — Jeffrey Dean & Sanjay Ghemawat (OSDI 2004) — The paper that made map, shuffle and reduce on cheap machines the default.
- *Designing Data-Intensive Applications, ch. 10* — Martin Kleppmann (2017) — Batch processing, joins, and why immutable inputs make reruns safe.
- *Resilient Distributed Datasets* — Matei Zaharia et al. (NSDI 2012) — The Spark paper: keep data in memory and rebuild lost parts from lineage.
