DataCorp has already decided how it is going to process its data: with an ELT approach and versioned SQL transformations (ADR-009), in daily batches and micro-batches (ADR-010). What remains is the question that is usually asked first, and is better asked last: with which tools.

The market offers hundreds, and the temptation is to choose the best known or the most powerful. It is an expensive mistake: an oversized tool does not process two gigabytes a day any better, but it does demand more people, more money and more knowledge. This lesson sorts the landscape into categories, explains what each one solves and from what size it makes sense, shows with code how they resemble each other and where they differ, and applies explicit criteria to select DataCorp's, which will be recorded in ADR-011.

Two limits on scope: orchestrators, which decide when and in what order each process runs, are the subject of lesson 04-05; and the choice of the analytical engine for consumption belongs to Module 6, so here we will talk about "the analytical engine" without naming a product.

Map of categories

Processing tools are grouped according to the part of the job they solve:

graph LR
    F["Sources"] --> ING["Ingestion<br/>(connectors, scripts)"]
    F --> MEN["Messaging<br/>(event log)"]
    ING --> B["Raw zone"]
    MEN --> B
    MEN --> FLU["Stream processing"]
    B --> PRO["Processing engines<br/>(SQL, single machine, distributed)"]
    TRA["Transformation tool<br/>(organizes the SQL)"] -.-> PRO
    PRO --> D["Cleansed and<br/>consumption zones"]
    FLU --> D
Category What it solves Examples
SQL engine / analytical store Running SQL transformations on large tables The analytical engine for consumption
Single-machine processing Transforming data that fits on a single computer pandas, Polars, DuckDB
Distributed batch engine Spreading a job across many machines Hadoop MapReduce, Apache Spark
Messaging Transporting and retaining event streams Apache Kafka and equivalent services
Stream processing Calculating continuously over events Kafka Streams, Apache Flink, Spark Structured Streaming
Ingestion Extracting from the sources and loading into raw Airbyte, Fivetran, custom scripts
Transformation Organizing, testing and documenting the SQL dbt

The same need can almost always be met by several categories. What decides is the volume, the required latency and who is going to maintain it.

The analytical engine as a transformation engine

In an ELT approach, the first processing tool is the destination itself. Columnar analytical engines run SQL in parallel across many cores or nodes without whoever writes the query having to think about it.

  • For: the data does not have to be moved to be transformed; SQL is the language most people know; parallelism, memory and fault tolerance are handled by the engine; it is a component you already have.
  • Against: anything that is not tabular (free text, images, calls to an API) is expressed badly or not at all; transformation compute competes with query compute if they are not separated; each engine has its own dialects and extensions.

Rule of thumb: everything that can be written in SQL is written in SQL and run on the analytical engine. The other categories cover what is left out: getting to the data (ingestion), whatever is not SQL and whatever has to happen before the data is in the engine.

Single-machine processing: pandas, Polars and DuckDB

For years it was taken for granted that analytical data required a cluster. Today an ordinary server has dozens of cores and hundreds of gigabytes of memory, and a generation of tools takes advantage of that capacity without the complexity of distributed systems.

pandas Polars DuckDB
What it is A Python library for in-memory tables A table library, written in Rust, with a Python interface An embedded analytical database: it runs inside the program itself, with no server
Interface Python methods Python methods, with optional lazy evaluation SQL
Use of cores One, in general All of them All of them
Data larger than memory No: it loads everything Yes, in streaming mode Yes: it spills to disk whatever does not fit
Reading Parquet Yes Yes, reading only the columns needed Yes, with partition and column pruning
Comfortable size Up to a few GB Tens of GB Tens to hundreds of GB
Strong point A huge ecosystem; everybody knows it Performance with a programming style Full analytical SQL with no infrastructure

All three are installed with one command and work on a laptop, in a container or in a serverless function. DuckDB deserves special attention in a project like DataCorp's: it queries Parquet, CSV or JSON files directly, including on object storage, so a small process can read the raw zone, transform with SQL and write Parquet to the cleansed zone without any intermediate database.

When is one machine enough? When each run handles, at most, tens of gigabytes and can be split up by partition. That is DataCorp's situation: 2 GB a day in total (RQ-01), which in a 15-minute clickstream micro-batch is about 20 MB. Reprocessing a whole year does not require more either: you go through it partition by partition, day by day.

When is it not enough? When a single indivisible operation (a global join or sort) far exceeds the memory and disk of the largest reasonable machine, or when the processing time on one machine does not fit in the available window.

Distributed batch engines: from MapReduce to Spark

The forerunner: Hadoop MapReduce

In the mid-2000s, processing the data of a web search engine was beyond any single machine. The answer was to spread the work across hundreds of cheap computers. Hadoop popularized that approach with two components: a distributed file system (HDFS) and a programming model, MapReduce, which splits every calculation into two steps:

  1. Map: each machine processes its chunk of data and emits key-value pairs (for each event, (type, 1)).
  2. Reduce: the pairs are grouped by key and combined (the ones for each type are added up).

MapReduce proved that fault-tolerant distributed processing was possible, but it was slow, because it wrote to disk between every step, and laborious to program. Today it is a historical forerunner; the Hadoop ecosystem and the concept of Big Data are covered in lesson 06-01.

Apache Spark

Spark is the most widely used general-purpose distributed engine. It keeps the idea of spreading the work, but it operates in memory and offers high-level interfaces. Its architecture:

graph TD
    D["Driver<br/>(main program:<br/>plans and coordinates)"] --> G["Cluster manager<br/>(allocates resources)"]
    G --> E1["Executor 1<br/>tasks + cache"]
    G --> E2["Executor 2<br/>tasks + cache"]
    G --> E3["Executor 3<br/>tasks + cache"]
    D -.->|"sends tasks"| E1
    D -.-> E2
    D -.-> E3
  • The driver runs the user's program, turns it into a plan and splits it into tasks.
  • The executors are processes spread across the machines of the cluster: they run the tasks on chunks of the data (partitions) and return results.
  • The cluster manager (Kubernetes, YARN or Spark's own) allocates machines.

Three concepts explain how you work with it:

  • DataFrame: a distributed table, with named, typed columns. It is handled with methods (filter, groupBy, join) or directly with SQL. Unlike a pandas DataFrame, its data is not in the program's memory, but spread across the executors.
  • Lazy evaluation: operations are divided into transformations (filter, groupBy), which only describe what to do, and actions (show, count, write), which trigger execution. Until an action arrives, Spark processes nothing: it accumulates the plan, optimizes it as a whole (for example, by moving the filters earlier) and then runs it.
  • Shuffle: when an operation needs to bring together data from different partitions (a groupBy, a join), the data travels over the network between executors. It is the most expensive part of a distributed job and the origin of almost all its performance problems.

Spark is the right tool when the data is measured in terabytes per run. Below that, its fixed cost outweighs its advantage: a cluster to start up and size, executor memory to tune and an execution model the team has to understand in order to diagnose failures.

Example: the same aggregation in DuckDB and in PySpark

Let's calculate the number of clickstream events by type and by hour for November 17, reading the cleansed zone. There, each event has the columns event_id, event_type, event_time (timestamp in UTC), customer_id, device_type, device_os, product_id and quantity, and the files are spread across date=YYYY-MM-DD folders (ADR-004).

With DuckDB:

import duckdb

con = duckdb.connect()          # in-memory database: there is no server

result = con.sql("""
    SELECT event_type,
           date_trunc('hour', event_time) AS event_hour,
           COUNT(*)                       AS num_events
    FROM read_parquet('datacorp-data-cleansed/clickstream/events/*/*.parquet',
                      hive_partitioning = true)
    WHERE "date" = DATE '2026-11-17'         -- column derived from the folder
    GROUP BY event_type, event_hour
    ORDER BY event_hour, event_type
""")

result.show()                                # prints the resulting table
result.write_parquet("events_by_type_and_hour.parquet")
  • read_parquet with a pattern (*/*.parquet) reads all the files as a single table.
  • hive_partitioning = true turns the name of the date=... folders into a date column (written in double quotes in the query because DATE is a reserved word). The filter on it means DuckDB only opens the files in that folder: it is the partition pruning of lesson 02-06.
  • date_trunc('hour', ...) rounds each timestamp down to the start of its hour.
  • Only two columns are read from each file (event_type and event_time), thanks to the columnar format.

With PySpark (Spark's Python interface):

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

# The session is the entry point; on a cluster, this is where it connects to the manager
spark = SparkSession.builder.appName("events_by_type_and_hour").getOrCreate()

# Transformations: they only describe the calculation. Nothing is read yet.
events = spark.read.parquet("datacorp-data-cleansed/clickstream/events")

result = (
    events
    .filter(F.col("date") == "2026-11-17")                      # partition pruning
    .groupBy("event_type", F.date_trunc("hour", "event_time").alias("event_hour"))
    .agg(F.count("*").alias("num_events"))
    .orderBy("event_hour", "event_type")
)

# Action: now Spark optimizes the whole plan and runs it
result.show()
result.write.mode("overwrite").parquet("events_by_type_and_hour")
  • spark.read.parquet recognizes the date= folders as a partition column by itself.
  • The filter, groupBy, agg and orderBy lines run nothing: they build the plan. Execution starts at show().
  • mode("overwrite") replaces the output if it exists: once again, idempotent writing.
  • The output is a folder with several part-NNNNN.parquet files, one per partition of the result.

The two programs do the same thing and look very much alike. The difference lies in what you cannot see: the first is a process on one machine that starts in milliseconds; the second needs a Java virtual machine, a driver, executors and, to perform, a cluster. With the 2 million events of one day at DataCorp, DuckDB answers on a laptop in under a second, and Spark spends more time starting up than calculating. With 2 billion events, the situation is reversed.

Messaging and stream processing

The concepts (topic, partition, consumer group, windows, watermark, state) were explained in lesson 04-03. Here we place the tools.

Tool What it is Model Use it when
Apache Kafka A distributed event log: it transports and retains It does not process by itself There are event streams with one or more destinations
Kafka Streams A Java library for processing Kafka streams Event by event; it is embedded in an application, with no cluster of its own The processing is part of a service and the data is already in Kafka
Apache Flink A distributed stream processing engine Event by event, with very elaborate state and event-time handling Millisecond latencies, complex windows and state
Spark Structured Streaming A Spark extension for streams Micro-batches (by default) Spark is already in use and latencies of seconds are enough

Operating a Kafka or Flink cluster requires specialists. That is why every cloud provider offers equivalent managed services:

Function AWS Azure Google Cloud
Event log Kinesis Data Streams; MSK (managed Kafka) Event Hubs (supports the Kafka protocol) Pub/Sub; Managed Service for Apache Kafka
Stream processing Managed Service for Apache Flink Stream Analytics Dataflow
Managed Spark EMR; Glue Fabric; Azure Databricks Dataproc

The commercial names change frequently; what is stable is the function. Many of these services also include automatic delivery to object storage: they group the events and write them as files every so often, with no need to program a consumer.

Example: a Kafka producer and consumer

To make the ideas concrete, this is the skeleton of the two ends of a topic, with Python's confluent-kafka library. The producer is what the website's server would do on receiving an event:

import json
from confluent_kafka import Producer

producer = Producer({
    "bootstrap.servers": "localhost:9092",   # address of the cluster
    "acks": "all",                           # wait for acknowledgment from all the replicas
    "enable.idempotence": True,              # retries do not duplicate the message
})


def delivery_report(error, message):
    """Called when the cluster acknowledges (or rejects) each message."""
    if error is not None:
        print(f"Delivery failed: {error}")
    else:
        print(f"Delivered to partition {message.partition()}, offset {message.offset()}")


event = {"event_id": "e-7f3a91", "type": "add_to_cart",
         "event_time": "2026-11-18T10:04:10Z", "customer_id": 1042,
         "product": {"product_id": 3301, "quantity": 1}}

producer.produce(
    "clickstream.events",                    # topic
    key=str(event["customer_id"]),           # key: decides the partition
    value=json.dumps(event),                 # content, as JSON text
    callback=delivery_report,
)
producer.flush()                             # waits until what is pending has been sent

The consumer reads the topic as a member of a group:

import json
from confluent_kafka import Consumer

consumer = Consumer({
    "bootstrap.servers": "localhost:9092",
    "group.id": "file-collector",            # consumer group
    "auto.offset.reset": "earliest",         # with no stored position, start from the beginning
    "enable.auto.commit": False,             # we commit the position ourselves
})
consumer.subscribe(["clickstream.events"])

try:
    while True:                              # a streaming consumer never ends
        message = consumer.poll(1.0)         # waits up to 1 s for a message to arrive
        if message is None:
            continue
        if message.error():
            print(f"Error: {message.error()}")
            continue
        event = json.loads(message.value())
        print(event["type"], event["customer_id"])       # the processing would go here
        consumer.commit(message=message)     # commit AFTER handling the event
finally:
    consumer.close()

The details that matter:

  • key: all the events of customer 1042 go to the same partition and are read in order.
  • acks="all" and enable.idempotence: the producer retries without fear of duplicating within Kafka.
  • group.id: if three copies of this program are started with the same group, they share out the partitions. With a different group, each program would read the whole topic on its own.
  • commit after processing: if the program goes down between handling the event and committing, on restart it will receive that event again. It is the at-least-once guarantee; committing before processing would give "at-most-once", with loss of events.

Ingestion and transformation tools

Ingestion. Extracting from a source and loading into raw is repetitive work: authentication, pagination, rate limits, schema changes. There are two paths:

Managed connectors (Fivetran, Airbyte and the like) Custom scripts
What they offer A catalog of hundreds of ready-made connectors for well-known databases and applications Full control
Initial effort Minutes per source Days per source
Maintenance The vendor's (if the source API changes, they fix it) Your own
Cost By row volume or by capacity; it can grow fast The team's time
Uncommon sources Not covered, or with a connector of doubtful quality No problem
Worth it when There are many standard sources, especially cloud applications There are few sources, or they are unusual

Fivetran is a fully managed service; Airbyte exists as open source that you deploy yourself and as a cloud service.

Transformation. The dbt-style tool was explained in lesson 04-02. Let's recall its place on the map: it is not an engine, but what organizes the SQL that the engine runs.

Comparison table

Tool Category Comfortable scale Latency Language Operating effort Weak point
Analytical engine (SQL) SQL engine From GB to petabytes Batch and micro-batch SQL Low, if managed Non-tabular data
pandas Single machine Up to a few GB Batch Python None Memory and a single core
Polars Single machine Tens of GB Batch Python None A younger ecosystem
DuckDB Single machine Tens to hundreds of GB Batch and micro-batch SQL None A single writer process; it is not a shared server
Hadoop MapReduce Distributed batch Terabytes and beyond Slow batches Java Very high Obsolete for new projects
Apache Spark Distributed batch (and micro-batch) Terabytes and beyond Batch; seconds in streaming Python, SQL, Scala High; medium if managed Overhead with small data
Apache Kafka Messaging Millions of events per second Milliseconds Clients in many languages High; low if managed It does not transform
Kafka Streams Streaming High Milliseconds Java Medium Tied to Kafka and to Java
Apache Flink Streaming Very high Milliseconds Java, SQL, Python Very high Complexity
Spark Structured Streaming Micro-batch streaming Very high Seconds Python, SQL, Scala High Limited minimum latency
Managed connectors Ingestion That of the sources Minutes to hours Configuration Very low Cost by volume
dbt Transformation That of the engine That of the engine SQL Low It only does the T

Selection criteria

Six criteria, in the order in which they are best applied:

  1. Real volume and velocity, not imagined ones. You start from RQ-01 and RQ-02, with their growth. DataCorp: 2 GB a day, 2.7 TB accumulated over three years, 23 events per second. That is small data for any current tool.
  2. Required latency (RQ-04). Already settled in ADR-010: batches and micro-batches.
  3. The team's skills. Marta and Íñigo are fluent in SQL and Python. A tool that requires Java or Scala starts at a disadvantage.
  4. Operating capacity (RQ-13). Every tool is one more thing to upgrade, monitor and understand when it fails at three in the morning. With two people, the number of components is the scarcest resource.
  5. Managed versus self-managed. ADR-003 already established the preference for managed or serverless services.
  6. Cost and vendor lock-in. The total cost includes people's hours; the economic detail is covered in lesson 07-04. Lock-in is limited with open formats (Parquet), standard SQL and open protocols (Kafka's).

One rule sums up all six: choose the simplest tool that meets the requirements with margin to spare, and write down the conditions under which it would stop being enough.

Selection for DataCorp and ADR-011

Need Tool chosen Reason
Extracting from PostgreSQL and from the APIs, and collecting files Custom Python scripts (ingestion/ folder of datacorp-data) Five sources, two of them unusual (the ERP and the support tool)
Transporting the clickstream The provider's managed messaging service, compatible with the Kafka protocol, with automatic delivery of files to the raw zone No cluster to operate; open protocol
Converting to Parquet the formats the engine does not read well (nested clickstream JSON, ERP CSV in ISO-8859-1), and the micro-batches Python with DuckDB SQL, no infrastructure, more than enough for 20 MB per micro-batch
Cleansed and consumption transformations SQL on the analytical engine, organized with dbt (ADR-009) Logic the stewards can read
Whatever is not SQL (classifying the ticket text, UC-05) Python The only case; it will be reviewed in Module 5
Distributed engine (Spark) Not adopted Volume far below what justifies it
Streaming engine (Flink, Kafka Streams) Not adopted ADR-010

From what point would Spark be justified? With growth of 20% a year, the 2 GB a day will be 2.9 GB in two years. The team sets an explicit threshold: a sustained volume above 50 GB a day (25 times the current one), or an indivisible transformation that does not fit on a machine with 64 GB of memory or that takes more than an hour.

ADR-011: Processing tools: SQL on the analytical engine,
         Python with DuckDB and managed messaging
Status: accepted            Date: 2026-12-02

CONTEXT
Volume of about 2 GB/day (RQ-01), 23 events/s (RQ-02), freshness of D+1,
15 minutes and 1 hour (RQ-04), a team of two people with SQL and Python
(RQ-13) and a preference for managed services (ADR-003).

DECISION
1. Transformations: SQL on the analytical engine, managed with dbt (ADR-009).
2. Ingestion: custom Python scripts in datacorp-data/ingestion, one per
   source, parameterized by load date and idempotent.
3. Format conversion and micro-batches: Python with DuckDB, reading and
   writing directly on object storage.
4. Clickstream: managed messaging service compatible with the Kafka
   protocol; topic clickstream.events; delivery of files every
   15 minutes to the raw zone using the service's native feature.
5. Spark, Hadoop, Flink and self-managed Kafka are not deployed.

ALTERNATIVES CONSIDERED
A. Apache Spark for all the processing. Rejected: the volume is two
   orders of magnitude below the level at which a cluster pays off.
B. Managed connectors (Fivetran, Airbyte and the like). Deferred: with
   five sources, two of them with no standard connector, they do not pay off.
C. Self-managed Kafka. Rejected: operation incompatible with RQ-13.
D. pandas for the micro-batches. Rejected as the norm: DuckDB offers SQL,
   uses all the cores and does not require loading whole files into memory.

REVIEW CONDITIONS
- Spark (managed): sustained volume above 50 GB/day, or an indivisible
  transformation that does not fit on a machine with 64 GB of memory or
  takes more than 1 hour.
- Managed connectors: more than 10 sources, or the addition of several
  cloud applications with a standard connector.
- Streaming engine: the conditions of ADR-010.

CONSEQUENCES
Positive: two languages (SQL and Python); no cluster to operate; everything
in open formats and protocols.
Negative: the ingestion scripts are custom code to maintain; a 25-fold
jump in volume would force a migration of the DuckDB processes.
Follow-up work: a common template for the ingestion scripts; choosing the
provider's specific messaging service.

Common Mistakes and Tips

  • Choosing by résumé. Adopting Spark or Flink because "it is what the big companies use" is the most common way of oversizing. The big companies have a thousand times more data and a hundred times more engineers.
  • Sizing by the accumulated volume. What each run processes is the daily increment, not the 2.7 TB of history. And the history is reprocessed partition by partition.
  • Using pandas for everything. It loads all the data into memory and uses one core. For reading Parquet and aggregating, DuckDB or Polars are several times faster for the same effort.
  • Treating a Spark DataFrame like a pandas one. Calling collect() or toPandas() brings all the data to the driver and cancels out the distribution.
  • Forgetting that Spark is lazy. An error in a transformation does not show up until the action, sometimes many lines later.
  • Committing the offset before processing. It turns the guarantee into "at-most-once": a failure loses events without a trace.
  • Piling up tools. Each one solves something, and all of them together are inoperable. Before adding one, ask yourself which of the ones you have already does the job reasonably well.
  • Tip: in every decision, write down the threshold that would invalidate it. It prevents both premature and overdue migrations.
  • Tip: test with your own data. An hour of testing with one real day of data tells you more than any benchmark.

Exercises

Exercise 1: Choosing the tool

State which category of tool you would use and why:

  1. A telecommunications company has to join 4 TB of call records with its customer base every night.
  2. An analyst wants to explore an 8 GB Parquet file on their laptop.
  3. An insurer needs to bring in data from twelve very well-known cloud applications (CRM, billing, advertising...).
  4. A bank wants to detect fraud patterns in card transactions in under 200 milliseconds.

Exercise 2: A query with DuckDB

Write with DuckDB the query that returns the 10 products most often added to the cart on November 17, 2026, with the number of events and the total units, reading the cleansed zone. Which two mechanisms prevent it from reading more than necessary?

Exercise 3: When will Spark be needed?

A vendor assures Sergio that DataCorp "will need Spark in a couple of years". With volume growth of 20% a year and the threshold of ADR-011, how many years would the daily volume take to reach it? What events could bring it forward?

Solutions

Exercise 1

  1. Distributed batch engine (managed Spark) or a high-capacity analytical engine. 4 TB per run, with a global join, exceeds what one machine handles comfortably.
  2. Single machine: DuckDB or Polars. They read only the columns needed and can work with data larger than memory. pandas would try to load the 8 GB (quite a lot more, once decompressed).
  3. Managed connectors. Twelve standard sources is the case they exist for: writing and maintaining twelve API integrations would cost far more than the service.
  4. Messaging plus a streaming engine (Kafka and Flink, or their managed equivalents). Millisecond latency, state per card and windows: no micro-batch can meet that.

Exercise 2

import duckdb

duckdb.sql("""
    SELECT product_id,
           COUNT(*)      AS num_events,
           SUM(quantity) AS units
    FROM read_parquet('datacorp-data-cleansed/clickstream/events/*/*.parquet',
                      hive_partitioning = true)
    WHERE "date" = DATE '2026-11-17'
      AND event_type = 'add_to_cart'
    GROUP BY product_id
    ORDER BY num_events DESC
    LIMIT 10
""").show()

The two mechanisms: partition pruning (because of the filter on date, only that day's folder is opened) and columnar reading (only event_type, product_id and quantity are read). On top of these, Parquet stores the minimum and maximum of each column per block, which makes it possible to skip whole blocks; we will see this in lesson 04-06.

Exercise 3

You have to solve 2 × 1.2^n = 50, that is, 1.2^n = 25:

import math
print(math.log(25) / math.log(1.2))    # 17.65...

About 18 years at the expected rate. The vendor's claim does not hold up against the growth data. It could be brought forward by changes of scale, not of pace: acquiring another company, opening international markets, recording far more detailed events (every mouse movement) or bringing in sensor data from the fulfillment warehouses. That is why the ADR does not set a date, but a threshold that is monitored.

Tip: when someone proposes a tool, ask for the number that justifies it. If there is none, the answer is "not yet".

Conclusion

Processing tools fall into a few categories: the analytical engine, which in an ELT approach is the first transformation engine; the single-machine libraries (pandas, Polars and DuckDB), which today cover volumes that ten years ago required a cluster; distributed batch engines, with Hadoop MapReduce as the forerunner and Spark, with its driver, its executors, its DataFrames and its lazy evaluation, as the standard for terabytes; messaging and streaming engines (Kafka, Kafka Streams, Flink, Spark Structured Streaming and their managed equivalents); and ingestion and transformation tools. The same calculation is written almost identically in several of them; what changes is the cost of operating them. That is why the selection is guided by the real volume, the required latency, the team's skills and capacity, the preference for managed services and the cost. ADR-011 chooses for DataCorp the simplest thing that complies: SQL on the analytical engine, Python with DuckDB and a managed messaging service, with explicit thresholds for reconsidering it.

We now have the pieces: ingestion scripts, SQL models, tests and micro-batches. But they are loose pieces. Someone has to launch them in the right order, wait for one to finish before starting the next, retry what fails, alert when something does not arrive on time and make it possible to repeat the load for a specific day. Today, at DataCorp, that is done by a cron job at 02:00. The next lesson explains why that is not enough and what an orchestrator brings.

© Copyright 2026. All rights reserved