Spark 4.3 on Amazon EMR: Custom Data Source and Auto CDC

Spark 4.3 on Amazon EMR: Custom Data Source and Auto CDC

A hands-on walkthrough of zero-staging REST API ingestion, a four-layer pipeline and CDK deployment, built end to end with Formula 1 race data.

A hands-on walkthrough of zero-staging REST API ingestion, a four-layer pipeline and CDK deployment, built end to end with Formula 1 race data.
A customer upgrades from the basic plan to premium in March and cancels in June. Finance asks: which plan were they on when they cancelled?
If your pipeline only keeps the latest row, you can't answer. The upgrade overwrote the old plan, and the history is gone.
This problem is everywhere. Which sales rep owned the account when the deal closed? Which manager did an employee report to last quarter? Which warehouse was a product assigned to in October? The usual fix is to keep one row per version, each with a start date and an end date. That's called a Slowly Changing Dimension Type 2, or SCD2.
Spark 4.3 can now do this with one declaration, called Auto CDC. Doing it by hand with MERGE statements is easy to get wrong, and Part 3 shows why. There are two catches. First, the Spark in a managed service is usually a few versions behind. AWS Glue 6.0 is powered by Spark 4.1, and the EMR release I used ( emr-spark-8.0.0 ) ships Spark 4.0.2. Second, the data you want to track often comes from a REST API that has no ready-made connector.
So this post walks through four things:
  1. Install Spark 4.3 on Amazon EMR, next to the Spark EMR already ships (Part 1).
  1. Write a small custom data source, so Spark reads an API directly and you don't need a staging area (Part 2).
  1. Run a real pipeline on top: four layers, with Auto CDC keeping the history (Part 3).
  1. Check the result, and know what to do when something breaks: each error message and its fix sits in the step where you would hit it (Part 4 and the steps before it).
For the example data I used Formula 1, because it has the same problem as the customer plans: which team was a driver racing for at each race? Here's what the finished pipeline produced for Lawson, who raced for rb, moved to red_bull and went back to rb, all within three of the races I loaded:
driver_Id
team_id
 __START_AT 
 __END_AT 
lawson
rb
2024-12-08
2025-03-16
lawson
red_bull
2025-03-16
2025-04-06
lawson
rb
2025-04-06
(empty: current)
Nothing in that table was typed in. It's what my last validation run read back from the  dim_drivers  table.

Before you start

This is a personal hobby project, not official AWS or Apache Spark content. The code, the runs and the failures described here are from my own AWS account, and the code blocks come from the repository (some are trimmed), except the MERGE sketch in Part 3, which is only an illustration:  aws-emr-spark-declarative-pipelines .
Who this is for. You write Python and SQL, you have run Spark somewhere before (a laptop, Glue, anywhere), and you're comfortable in a terminal with the AWS CLI. You don't need to know Amazon EMR, Apache Iceberg or Spark Declarative Pipelines: each one is explained where it first appears.
A note on voice. I write "you" for the steps, and "I" when I explain a choice or report something I measured, so you can tell instructions from evidence.
Get the code first. Every command below runs from the root of the repository, so clone it and set up Python the way its README's Prerequisites section does:
git clone https://github.com/vikneshwara-r-b/aws-emr-spark-declarative-pipelines.git
cd aws-emr-spark-declarative-pipelines
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements-dev.txt


You'll need
An AWS account with a CLI profile, Docker, Node.js with the CDK CLI, and Python 3.11 or newer
Time
The first bundle build is about 5 to 10 minutes (the repository README's estimate). My full validation run, five races, took about 24 minutes
Cost
About $0.78 an hour in  us-east-1  while everything is up (see below)
About the cost: with the defaults (one primary and two core  m5.xlarge  nodes, all on-demand), compute is about $0.72 an hour by the list prices I checked on 2026-11-08, plus about $0.055 an hour for the NAT gateway (it lets a cluster with no public address reach the internet) and a VPC endpoint (a private door to an AWS service) until you destroy the platform stack. Check current prices first. The cluster shuts itself down after an hour of idle time, and the cleanup commands are at the end.
The scripts print  Using profile=... account=... region=...  before they do anything. Read that line every time, so you never deploy into the wrong account.
If Spark Declarative Pipelines (SDP) is new to you, my earlier post  One Glue Job, Zero Orchestrators: My First Spark Declarative Pipeline on AWS Glue  covers the basics. The short version: you declare tables and flows in Python or SQL files, and Spark works out the order and runs them.



Part 1: Install Spark 4.3 on Amazon EMR

EMR has no switch for "use a different Spark version". So you install a second Spark next to the one EMR ships. EMR's own Spark stays untouched, and yours lives in  /opt/spark-sdp . The name has no version in it on purpose, so moving to a later Spark won't mean renaming things.
Bringing your own Spark has a price: you now own the upgrades and the compatibility checks, and nobody at AWS will fix them for you. For this project the trade is worth it. Spark 4.2 can only overwrite rows (SCD1), and keeping history (SCD2) is the point of the exercise, so you need Spark 4.3.
There are three moving pieces:
  • A Docker image builds one tarball (a single compressed archive, a  .tar.gz  file) containing Spark, the Iceberg jars (Apache Iceberg is the table format Auto CDC needs, because it can update and delete individual rows) and a Python environment.
  • S3 stores that tarball.
  • A bootstrap action (a script EMR runs on every node while the cluster starts) unpacks it.
Why build a tarball instead of installing at boot? Every node gets identical files, startup is fast, and the big downloads happen on your laptop, not on a cluster you pay for by the hour.

Build the bundle

The builder image is based on Amazon Linux 2023, the same OS the EMR nodes run, so the Python environment built inside it works on them. These are the settings that matter:
FROM public.ecr.aws/amazonlinux/amazonlinux:2023

ENV SPARK_VERSION=4.3.0 \
ICEBERG_SPARK_SERIES=4.2 \
INSTALL_DIR=/opt/spark-sdp
You may have spotted the odd line: Spark 4.3, but the Iceberg build for Spark 4.2. When I built this, there was no Iceberg build for Spark 4.3 yet, so I pinned an exact snapshot of the 4.2 one. (Support for 4.3 is tracked in  apache/iceberg#18749 .)
A mismatch like that can fail in ugly ways. One version lower, an Iceberg runtime built for Spark 4.1 running on Spark 4.2 gave me  IncompatibleClassChangeError: class org.apache.iceberg.spark.SparkView can not implement org.apache.spark.sql.connector.catalog.View . So before anything gets uploaded, the build runs a quick local test: it creates an Iceberg table, inserts rows, then runs a  MERGE INTO  and a  DELETE , the same kind of operations Auto CDC uses. If the test fails, the build stops and nothing is uploaded. It takes a few minutes on your laptop and costs nothing.
Two limits to know about. The jars are installed by the bootstrap action, so a running cluster keeps the old ones: after you fix the bundle, create a new cluster. And I've only tested this pairing at small size: no large tables, no compaction, no concurrent writers.

Install it with a bootstrap action

The bootstrap script is short. It copies the tarball from S3 and unpacks it:
aws s3 cp "$BUNDLE_URI" /tmp/spark-bundle.tar.gz
sudo tar -xzf /tmp/spark-bundle.tar.gz -C /opt # creates /opt/spark-sdp
(Bootstrap scripts run as the  hadoop  user, not root, so anything outside your home folder needs  sudo .)
Then comes the part that matters most: EMR sets  SPARK_HOME  and  PYTHONPATH  to its own Spark, and  spark-submit  obeys them. If you just call  spark-submit , you can quietly end up on the wrong Spark. So the script also creates small wrapper commands that reset those variables first:
#!/usr/bin/env bash
unset PYTHONPATH PYTHONHOME
export SPARK_HOME=/opt/spark-sdp
export PYSPARK_PYTHON=/opt/spark-sdp/venv/bin/python
exec /opt/spark-sdp/bin/spark-submit "$@" # saved as /usr/local/bin/spark-sdp-submit
Now  spark-submit  is still EMR's Spark, and  spark-sdp-submit  is Spark 4.3. The same trick gives you  spark-sdp-sql  and  spark-sdp-pipelines .
The script that runs a pipeline as an EMR step (a unit of work you submit to a running cluster) also guards against this: it prints the version it is about to use (a line starting with  Spark: ) and exits with an error if that line doesn't say  version 4.3 .
If you see  Running Spark version 4.0.2-amzn-0  in a step log, or  ImportError: cannot import name 'pipelines' from 'pyspark'  with a path under  /usr/lib/spark , EMR's Spark ran instead of yours: the trap from a few paragraphs up, this time inside a step, so a correct install can still lose. The wrappers and step scripts pin  SPARK_HOME  and drop EMR's  PYTHONPATH . Nothing crashes when this goes wrong, so check the version whenever you touch the setup. To change a step script on a running cluster, copy it to the bootstrap folder in S3. Wrappers are written when a node boots, so changing one means a new cluster.
Two more things about running pipelines on EMR.
First,  spark-pipelines  always runs through Spark Connect, Spark's client-server mode: your pipeline code is the client and a Spark server does the work. With  --remote local , which the command always passes, that server starts on the primary node itself, so the pipeline doesn't use the core nodes at all. I gave that server a 4 GB driver ( spark.driver.memory ) and left it there, because one race is a few hundred kilobytes. If your data is much bigger, this is the first thing to revisit; I haven't tried it.
Second,  spark-pipelines  needs Python 3.11 and the system Python on these nodes is 3.9, so the step script points it at the bundled one.

The infrastructure

You deploy two stacks with the AWS CDK (infrastructure as code, written in Python here). There are two so you can destroy the expensive part and keep the rest:
  • Platform stack: the long-lived part. A VPC (your private network in AWS) with a public and a private subnet, a NAT gateway, an S3 gateway endpoint (a private route to S3), the EMR service endpoint, the S3 bucket, an ECR repository (where the builder image is stored), IAM roles and the Glue database.
  • Cluster stack: the EMR cluster, with the bootstrap action and an auto-termination policy. An EMR cluster has a primary node, which coordinates the work and, in this project, runs your pipeline, and core nodes, the workers that also store data. This one has one primary and two core  m5.xlarge  nodes, the smallest size this EMR release offers.
Here is the whole setup at the level you need for the rest of the post. The Athena box is optional and isn't deployed by the stacks: you'll use it later to look at the tables.

It shows: The setup: you, S3, an EMR cluster with two Sparks, Iceberg tables and the Glue catalog.

Spark 4.3 sits next to EMR's own Spark on the cluster, reads the API through the custom data source and writes Iceberg tables that the Glue catalog knows about.
For the whole architecture, with the VPC and subnets, the S3 layout, the IAM roles and the numbered steps of one run, see the  detailed architecture diagram in the repository README .
A few decisions in these stacks aren't obvious, and some were learned the hard way:
  • No public address. The cluster sits in the private subnet. Nothing needs to connect to it from the internet, so I didn't open that door. It only has to go out: to the API through the NAT gateway and to S3 through the gateway endpoint. The price is the NAT gateway's hourly fee, which keeps running until you destroy the platform stack.
  • On-demand core nodes, not Spot. Spot is spare EC2 capacity at a discount that AWS can take back. I tried it, and the core nodes were reclaimed two minutes after the cluster reached  WAITING . EMR ends the whole cluster when it loses every core node, even with a healthy primary, and the error is  INSTANCE_FAILURE: All slaves in the job flow were terminated due to Spot . Use  -c core_market=SPOT  only when losing the cluster doesn't hurt.
  • An hour of idle time, then it shuts itself down. A forgotten cluster costs at most one extra hour of compute. The catch: a cluster that idled out and one that died of the Spot failure give the same error when you add a step,  A job flow that is shutting down, terminated, or finished may not be modified . Check  aws emr list-clusters  for the real reason, then redeploy the cluster. Raise  idle_timeout_seconds  if you want a long session.
  • Two IAM and VPC traps.  Service role ... has insufficient EC2 permissions  hides the real denial,  iam:PassRole  (the permission to hand a role to a service), which only showed up in CloudTrail, AWS's log of API calls. The platform stack now lets the EMR service role pass the instance role to EC2. And if you see two  emr-service-cell01  VPC endpoints and the VPC won't delete, EMR created its own because private DNS was off on ours. Delete the copy without the CloudFormation tag. Ours now has private DNS on, so EMR reuses it.

Deploy it

P=<your-aws-profile>

scripts/deploy.sh --profile $P --stage platform # VPC, S3, ECR, IAM, Glue database
scripts/build_and_push_image.sh --profile $P # builder image -> ECR
scripts/build_bundle.sh --profile $P # runs the image, uploads the bundle to S3
scripts/deploy.sh --profile $P --stage cluster # EMR cluster; bootstrap installs Spark 4.3
The order matters, because the cluster needs the bundle in S3 before it starts. The first bundle build downloads about 470 MB.
Once the cluster is up, check that you really have two Sparks. You don't need a shell on the node for this.
EMR's own Spark: ask the EMR API what it installed.
aws emr describe-cluster --cluster-id <cluster-id> --profile $P \
--query 'Cluster.Applications[?Name==`Spark`]' --output table
| Name | Version |
| Spark | 4.0.2 |
The Spark 4.3 you installed: every pipeline step prints the version it is running before it starts the pipeline, and stops if it isn't 4.3 (the check from earlier). Open the step's  stdout  in the EMR console (Steps tab) and look for the  Spark:  line, which ends in  version 4.3.0 .

It shows: EMR's own Spark, as reported by the EMR API.

EMR's own Spark: 4.0.2.
It shows: Curated layer.


It shows: The Spark: line in a pipeline step's stdout.

The Spark you installed, in the first lines of a pipeline step's stdout (here, the run for 2025 round 3):  version 4.3.0 .
Your turn. Before you open a step log: which version do you expect the  Spark:  line to show, 4.0.2 or 4.3.0? If it shows 4.0.2, stop here. The bootstrap action or the wrappers aren't doing their job, and every later step would quietly run on the wrong Spark.



Part 2: A custom data source

The Jolpica F1 API returns JSON over HTTP, and no Spark connector exists for it. The usual workaround is a job that downloads the JSON, writes it to S3 and lets Spark read the files. An earlier version of this project did exactly that: it staged each API response as JSON in S3. The data source removes that whole layer.
Spark 4's Python Data Source API lets you write a small class, register it under a name, and then use it like any built-in source:  spark.readStream.format("f1_api") .
You need two classes. One describes the source, and one reads from it. Here's a simplified version:
class F1ApiDataSource(DataSource):
@classmethod
def name(cls):
return "f1_api" # the name you use in .format(...)

def simpleStreamReader(self, schema):
return F1ApiStreamReader(schema, self.options)

class F1ApiStreamReader(SimpleDataSourceStreamReader):
def initialOffset(self):
return {"run": ""} # nothing read yet

def read(self, start):
if start["run"] == self.options["runId"]:
return iter([]), start # already read in this run, so stop
row = fetch_race(self.options) # call the API
return iter([row]), {"run": self.options["runId"]}
I used the "simple" reader, which Spark's docs describe as the one for low-volume sources. One race is a few hundred kilobytes, so that fits.
The clever part is the offset. Spark remembers an offset between runs, which is how it knows what it has already read. I store a run id in it. Each pipeline run generates a new random id. When  read()  sees that the stored id matches the current one, it returns nothing, so Spark sees "no more data" and finishes. When the ids differ, it's a new run, so it fetches the race. That's how a streaming source turns into "fetch once per run". Here's what  read()  does across two pipeline runs:
Call to  read() 
Offset Spark has stored
 runId  option
What happens
1st
 ""  (nothing yet)
 abc 
Ids differ: fetch the race, store  abc 
2nd, same run
 abc 
 abc 
Ids match: return nothing, so Spark sees "no more data" and finishes
1st call of the next run
 abc 
 xyz 
Ids differ: it's a new run, fetch the race again
Your turn. What does  read()  return on a third call in the same run? Work it out from the table. (The same as the second call: nothing. The stored id still matches the current one, so Spark sees "no more data" and the run finishes.)
The API part is plain Python: it follows the pages (100 rows at most per call), retries on 429 and 5xx errors, and respects  Retry-After . The Jolpica API is run by volunteers and allows 4 requests a second and 500 an hour, so the code pauses between pages and sends a descriptive  User-Agent . Please keep that if you reuse it.
Two things to get right when registering the source:
cloudpickle.register_pickle_by_value(sys.modules[__name__]) # ship the class to the Python workers
spark.dataSource.register(F1ApiDataSource)
  • Register it at the top of your pipeline file. Inside a flow function Spark Connect won't allow it.
  • Register the module "by value", as above, so Python workers don't need your project files. The price is that the module can only import the standard library,  requests  and  pyspark .
A flow then reads from the source like any built-in one, with  spark.readStream.format("f1_api")  and a few options: the endpoint ( results ,  qualifying  or  pitstops ), the season, the round and the run id.
Each pipeline run reads one race: three calls, one per endpoint. The source returns one row holding the API's own JSON, and flattening it is an ordinary Spark job in the next layer. I tested the source with pytest and a fake HTTP session, because the retry paths are hard to trigger on demand on a real cluster.
Two things can go wrong here:
If you see the log say  Run is COMPLETED  and then the step fail with  [UNKNOWN_RESPONSE] Unknown response: Plan observed(__python_accumulator__ ... , you've hit a bug in the Spark 4.3.0 Spark Connect client. It's triggered whenever a Python worker, which is what a custom data source is, takes part in the run. It's fixed on Spark's master branch ( SPARK-59135 ) but not in 4.3.0. The repository's  connect_compat.py  skips those messages. It switches itself off if Spark's internals look different or the bug is already fixed, so you can delete it once your Spark includes the fix.
One limit I haven't solved: an  OptionalDataException  appeared once in the local Spark Connect run. Running the same race again was safe, because a failed run leaves the stream offset unchanged, but I never found the cause.



Part 3: The pipeline

The pipeline has four layers:
Layer
What's in it
Raw
The API payload as returned, plus columns saying where and when it came from
Prepared
Flattened and typed
Curated
Six Auto CDC tables: three SCD2 dimensions (drivers, teams, circuits) and three SCD1 facts (results, qualifying, pit stops)
Gold
Five summary views, such as driver and team performance
All of it is stored as Apache Iceberg tables in the AWS Glue Data Catalog, AWS's shared registry of table definitions, which is how Athena and other services find the tables. Iceberg is there because Auto CDC needs a table format that supports row-level changes. SDP doesn't pick the format; the catalog does, and here that's Iceberg on Glue. The pipeline spec says so in three lines:  catalog: glue_catalog ,  database: f1_sdp_db , and a storage path in S3 for checkpoints, the bookmarks Spark keeps so a streaming table knows what it has already processed.
The entity diagrams for the raw, prepared and gold layers are in the repository under  docs/er-diagrams/ . The curated one is further down.
The prepared layer turns strings into real types. Spark 4 runs in ANSI mode by default (strict SQL rules), so a value that can't be cast, such as the text  N/A  where a number is expected, fails the whole run. Everything parsed from the API goes through  try_cast  and friends, so a bad value becomes  NULL  and the run carries on.

Why not just write the MERGE yourself?

I didn't hand-build an SCD2 merge for this project. My old Glue version only needed the latest row per key, and a  ROW_NUMBER()  view handles that. History is a different animal, and it's what pushed me to try Auto CDC. So here are the four things that would hurt most if you wrote it yourself. These are the usual pain points, not a list of bugs I fixed.
1. One MERGE can't close the old row and open the new one. An SCD2 change needs two actions on the same key: put an end date on the current row, and insert a new row. A MERGE matches each source row once, so the common workaround is to feed it every changed row twice. One copy has the real key and closes the old version. The other has a NULL key, which never matches anything, so it inserts. It works, but it's hard to read and easy to get subtly wrong. This is the usual shape (a sketch, I didn't run this one):
MERGE INTO dim_drivers t
USING (
SELECT driver_id AS merge_key, * FROM staged -- closes the current version
UNION ALL
SELECT NULL AS merge_key, s.* FROM staged s -- opens the new version
JOIN dim_drivers t ON t.driver_id = s.driver_id AND t.end_at IS NULL
WHERE t.team_id IS DISTINCT FROM s.team_id
) u
ON t.driver_id = u.merge_key AND t.end_at IS NULL
WHEN MATCHED AND t.team_id IS DISTINCT FROM u.team_id THEN
UPDATE SET end_at = u.race_date
WHEN NOT MATCHED THEN
INSERT (driver_id, team_id, start_at, end_at) VALUES (u.driver_id, u.team_id, u.race_date, NULL)
2. Deciding what counts as a change. You have to compare the old and new row column by column. NULLs make that tricky:  team_id <> 'ferrari'  is NULL, not true, when  team_id  is NULL, so a real change can slip through unnoticed. That's why the sketch above uses  IS DISTINCT FROM . You also have to decide which columns count at all.
3. Late data. A hand-written merge compares each new row with the current row. Say Hamilton's 2024 Mercedes race arrives after his 2025 Ferrari race. The merge sees "Mercedes is different from Ferrari", closes the Ferrari row and opens Mercedes as the current team. That's wrong, and nothing complains. Doing it properly means slotting the row into the middle of the history and fixing the dates of its neighbours. This is what  sequence_by  is for in Auto CDC. (I loaded my races in date order, so I haven't tested a late arrival myself.)
4. Mistakes are silent. A bug here doesn't crash anything. It leaves a gap or an overlap in the dates, or two "current" rows for one driver, and the reports still look plausible. You need your own checks. Mine confirm that each  __END_AT  equals the next  __START_AT , and that each driver has exactly one open version.
Auto CDC doesn't remove the need to think. You still choose the keys, the sequence column and which columns count as a change, and you still check the result. But it takes over most of the fiddly SQL in that list.

Auto CDC in one declaration

All of that collapses into one declaration. Here's the SCD2 flow for drivers (trimmed):
dp.create_streaming_table("dim_drivers")

dp.create_auto_cdc_flow(
target="dim_drivers",
source="race_drivers", # one row per driver per race
keys=["driver_Id"], # what identifies a driver
sequence_by=F.col("race_Date"), # which row is newer
stored_as_scd_type=2, # 2 means keep history
track_history_except_column_list=["race_Date"],
)
  •  keys  says what counts as "the same thing".
  •  sequence_by  says which row is newer. If an older race arrives late, it can't overwrite a newer one.
  •  stored_as_scd_type=2  keeps every version, with  __START_AT  and  __END_AT . Use  1  to just overwrite.
  •  track_history_except_column_list  lists columns that shouldn't start a new version. The race date changes every race, so without this line every race would create a new version of every driver.
SCD2 isn't in Spark's own documentation until 4.3.1 and 4.4.0 ( SPARK-58570 ), so what this section says about it is confirmed by the validation run in Part 4, not by the docs.
Your turn. Think about your own data. Which column should open a new version when it changes, and which should not (like the race date here)? The second kind goes in  track_history_except_column_list .
The three fact tables use the same call with  stored_as_scd_type=1 , because nobody needs the old value of a corrected race result. Auto CDC also needs the target declared without a schema, since it adds hidden columns of its own.
One detail that isn't obvious: the facts' sequence column ( refreshed_at ) is left out of the output with  except_column_list . Auto CDC already keeps the sequence it used in a hidden  __spark_autocdc_metadata  column, and showing it would mean a second copy. The validation checks the hidden  upsertSequence  instead.
If you see every step green but  fact_race_results  always one run behind (after race 2 it still holds only race 1), look for a temporary view between a table and an Auto CDC flow. SDP can't see a dependency through a view, so the fact flow ran before its source had new rows. The fix is to read the prepared tables directly, and a unit test in the repository fails if a fact source isn't a prepared table.  dim_circuits  still reads through a temporary view, the same pattern. It hasn't failed and its checks pass, but I haven't proved it's safe, so if you copy this project, look at that file twice.
In the diagram below, look at the three dimension tables: they carry  __START_AT  and  __END_AT , and the facts don't.

It shows: Curated layer.

The curated layer. The three dimensions carry  __START_AT  and  __END_AT .

Where the history comes from

Here's a problem I didn't expect. The API only returns the current state, and when I probed round 1 of 15 seasons between 1996 and 2025, I found no change in any driver, constructor or circuit attribute. Names, codes, numbers and locations never change. A plain SCD2 table would hold one version of everything and prove nothing.
What does change is which team a driver races for. So  team_id  is the tracked column, and I picked races that contain real transfers: 2024 rounds 1, 2 and 24, and 2025 rounds 1 and 3, loaded in date order. This is what the table held afterwards:
driver
stint 1
stint 2
stint 3
hamilton
mercedes (2024-03-02 to 2025-03-16)
ferrari (from 2025-03-16)

sainz
ferrari (2024-03-02 to 2025-03-16)
williams (from 2025-03-16)

tsunoda
rb (2024-03-02 to 2025-04-06)
red_bull (from 2025-04-06)

lawson
rb (2024-12-08 to 2025-03-16)
red_bull (2025-03-16 to 2025-04-06)
rb (from 2025-04-06)
ocon
alpine (2024-03-02 to 2025-03-16)
haas (from 2025-03-16)

Nothing is simulated or edited. I like this much better than injecting fake changes, because every expected row in my checks is something that really happened.

It shows: dim_drivers history for Lawson, queried in Athena.

Lawson's three versions in  dim_drivers , queried in Athena. The open version has an empty  __END_AT .

Gold reads only the current version

If you join a fact table to a history table, every fact row gets multiplied by the number of versions. So the gold layer reads small views of the open versions only:
CREATE TEMPORARY VIEW dim_drivers_current AS
SELECT * FROM dim_drivers WHERE __END_AT IS NULL;
The five gold views and their columns are in  docs/er-diagrams/gold-layer.md .



Part 4: Run it and check it

Load the reference data and ingest one race:
scripts/run_pipeline.sh --profile $P --upload-reference-data initial --season 2024 --round 1 --wait
The script packages the pipeline, uploads it to S3, adds an EMR step and follows it. There's also a dry run that checks the whole graph without reading any data:  scripts/run_pipeline.sh --profile $P --mode dry-run .
If you see  f1.season.year and f1.season.round are both required  even though you passed  --conf , you're probably calling  spark-pipelines  yourself. Flows read their settings from the Spark Connect session, which is built only from the  configuration:  block of the pipeline spec, not from  spark-submit --conf . The run script copies every  --conf spark.f1.*  value into a per-run copy of the spec, so use the script.

It shows: The end of a pipeline run.

The end of the step log: each flow goes PLANNING, STARTING, RUNNING, COMPLETED, and the run finishes with  Run is COMPLETED .

Look at what it built

Open the Glue console (or Athena) and look at the database before you trust any of it. The queries below ran in Athena.

It shows: Tables in the f1_sdp_db Glue database.

The  f1_sdp_db  database in the Glue console: 27 tables over two pages. This is page 1.

It shows: Page 2 of the table list.

Page 2: the last seven tables, including the three  raw_*  tables and  team_performance_summary .
Besides the tables you declared, you'll see a few  __spark_autocdc_aux_state_*  tables. Auto CDC creates those itself, so don't be surprised by them.
A raw table holds the API's answer as it came, one row per run, plus four columns that say where and when it came from (the query is in the screenshot):

It shows: Rows of raw_results in Athena.

Six runs, six rows. Race 2 of 2024 appears twice because the validation loads it a second time on purpose.
A curated table is the same data after cleaning, with one row per driver per version (again, the query is in the screenshot):

It shows: Rows of dim_drivers in Athena.

The first rows of  dim_drivers . Bearman has two versions: Ferrari until 2025-03-16, then Haas.
The gold views are ordinary tables to Athena, so you can query them the same way. The screenshot runs  SELECT * FROM f1_sdp_db.driver_performance_summary ORDER BY total_points DESC LIMIT 10 

It shows: A gold view in Athena

 driver_performance_summary , after the five races: points, wins and podiums per driver and season.

How I checked it

I didn't want to trust "the step succeeded", so  scripts/validate.sh  runs the pipeline in a fixed order (two races, the second one again, then the three history races) and compares the curated tables with a separate calculation using plain window functions. It also checks that each version's  __END_AT  equals the next version's  __START_AT , that loading the same race twice changes nothing, and that the expected transfers are there. The comparison earns its keep: it is the only thing that caught the "one run behind" bug from Part 3, because every step was green.
My last full run passed 160 of 160 checks. After the five races:
  •  fact_race_results  had 100 rows (5 races of 20 drivers),  fact_qualifying  100 and  fact_pit_stops  193.
  •  dim_drivers  had 27 current drivers and 35 versions. Seven drivers had more than one version: the five transfers above and two others.
  • Loading race 2 again changed nothing in any table.
Those are small numbers on purpose. They show the pattern gives the right answer on this data. They don't show it's fast, because I didn't measure throughput or try bigger data.

It shows: Part of the validation report.

The top of  docs/validation-report.md : the overall result, then one line per check. The header only names the first three loads (rounds 1 and 2, then 2 again). The  [history]  checks further down cover the three extra races.
Your turn. Run the same race twice ( run_pipeline.sh  with the same  --season  and  --round ) and compare the row count of  fact_race_results  before and after. It should not change. The validation does exactly this with race 2 and found nothing different in any table.
If you hit something this post doesn't cover, the  troubleshooting section of the README  has the rest.

Clean up

scripts/destroy_cluster.sh --profile $P # only the cluster (keeps VPC, NAT, S3, ECR and your tables)
scripts/destroy.sh --profile $P # everything; this is what stops the NAT and endpoint billing



Reuse it for your own data

The same shape works for the customer plans from the start of this post: swap the Jolpica API for your own source, change the keys, and track the column that matters, such as the plan, the owner or the manager.
If you try it, I'd love to hear what you run into. The code, the CDK stacks, the Dockerfile, the bootstrap scripts and the checks are in the repository:  vikneshwara-r-b/aws-emr-spark-declarative-pipelines .

References

  •  Whole architecture diagram : the full AWS-icon diagram of the project (VPC and subnets, S3 layout, IAM roles and the numbered flow of one run), in the repository README.
  •  Jolpica-F1 API : the data source. Data derived from Ergast, CC BY-NC-SA 4.0 (non-commercial). Keep the attribution and respect its rate limits.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article