~/case-studies/wfi.md
featured case study · ~14 min read

World Football Insights — cloud-native serverless ELT on Google Cloud Platform

A cloud-native serverless ELT pipeline I built on Google Cloud Platform for a global sports analytics scenario. Cloud Composer 2 orchestrates 14 tasks with parallel fan-out and quality gates. Dataproc Serverless runs the PySpark medallion transformations without any cluster management. Bronze raw data stays in a Google Cloud Storage lakehouse; Silver and Gold materialize as BigQuery external tables. Async aiohttp extraction from TheSportsDB API. Explicit BigQuery schemas replace autodetect. Real production deployment: managed infrastructure, real cost, real runtime data.

● featured Cloud Composer 2.17.7 Apache Airflow 2.11.1 Dataproc Serverless 2.1 BigQuery lakehouse GCS medallion
14
orchestrated tasks
3
entity streams
6
BigQuery tables
11m 53s
optimized runtime
84%
runtime cut after debug
0
clusters managed by hand
~/problem.md
01 · the problem

A sports analytics company outgrows manual reporting

World Football Insights (WFI) is a global sports analytics company that provides football statistics, tournament insights, and historical performance data to broadcasters, sports journalists, football federations, and research institutions. Their existing reporting process meant analysts spent considerable time manually extracting football data from public sources, consolidating into spreadsheets, and preparing datasets before analysis could begin.

The brief was direct. WFI wanted a cloud-native ELT platform that could automatically extract football data from a REST API, land raw JSON in Google Cloud Storage, transform it into analytical datasets, and make the results queryable through BigQuery. Cloud Composer would orchestrate. The infrastructure had to be scalable, fault-tolerant, and generate trusted analytical tables that support historical comparisons and future predictive analytics initiatives.

Two constraints made this different from previous projects I have built. First, the platform had to be fully cloud-native on GCP: no on-premise components, no locally-managed clusters, no infrastructure I had to maintain by hand. Second, the pattern had to be ELT (extract, load, transform) rather than ETL. Raw data lands first, then transformations happen in a compute layer separate from the warehouse. That is a meaningfully different discipline from the on-premise ETL work I had shipped before.

// the architectural choice

For this GCP deployment, I chose a cloud-native serverless pattern with managed services (Cloud Composer for orchestration, Dataproc Serverless for Spark, GCS lakehouse, BigQuery warehouse), no infrastructure to own, and a lakehouse-medallion layout where Bronze stays in object storage while Silver and Gold materialize in the warehouse. That is the opposite architectural pattern to Nova Retail (on-premise Docker Compose, PySpark on a single host writing to PostgreSQL). Both patterns are correct in their contexts: on-premise Docker suits controlled-environment cost predictability and full-stack ownership; cloud-native serverless suits elastic scale and zero infrastructure maintenance. Together they show two credible production shapes for a modern data platform.

~/architecture.md
02 · architecture

A serverless topology with 14 orchestrated tasks

The whole pipeline runs on managed GCP services. Cloud Composer (which is managed Apache Airflow on GKE) hosts the DAG. Dataproc Serverless runs the PySpark transformations without me creating or managing a single cluster. Google Cloud Storage stores raw NDJSON, Silver Parquet, and Gold Parquet. BigQuery materializes Silver and Gold as external tables. No servers. No clusters. No infrastructure I have to maintain.

The DAG has a fan-out / merge / validate / fan-out / merge / fan-out shape. Three entity streams (teams, standings, matches) flow through in parallel where they can, and converge at the two Dataproc jobs and the quality gate.

extract
extract_and_upload_rawPythonOperator · async aiohttp + GCSHook
↓ fans out
gate 1 · file existence
wait_teamsGCSObjectExistenceSensor
wait_standingsGCSObjectExistenceSensor
wait_matchesGCSObjectExistenceSensor
↓ converge
bronze → silver
bronze_to_silverDataprocCreateBatchOperator · PySpark 2.1
↓
gate 2 · data quality
validate_silver_dataPythonOperator · row + column checks
↓ fans out
load silver to bigquery
load_silver_teamsGCSToBigQueryOperator
load_silver_standingsGCSToBigQueryOperator
load_silver_matchesGCSToBigQueryOperator
↓ converge
silver → gold
silver_to_goldDataprocCreateBatchOperator · PySpark 2.1
↓ fans out
load gold to bigquery
load_gold_teamsGCSToBigQueryOperator
load_gold_standingsGCSToBigQueryOperator
load_gold_matchesGCSToBigQueryOperator

The Bronze layer is deliberately absent from BigQuery. It stays in GCS as raw NDJSON. This is the honest lakehouse pattern: raw data lives in object storage as the single source of truth, only cleaned and enriched layers live in the warehouse. Analysts who need to audit raw responses can query GCS Parquet through BigQuery External Tables, but the warehouse itself does not carry duplicate storage cost.

// the honest bucket sprawl

Managed GCP services create their own supporting buckets. My project ended up with four: worldcup-football-bucket (my main lakehouse), us-central1-worldcup-footba-... (Composer's DAG and log bucket), dataproc-staging-us-central1-..., and dataproc-temp-us-central1-.... Only the first is mine to think about. The other three are the honest cost of running on managed infrastructure: Composer and Dataproc each need their own scratch space to stage jobs and cache logs. Worth naming because it is exactly the kind of thing tutorials skip and production diagrams gloss over.

~/schema.sql
03 · schema and storage

Six BigQuery tables, three GCS layers, one honest medallion

The worldcup-football-bucket holds four top-level folders visible in the GCS browser: raw/, silver/, gold/, and scripts/. Raw NDJSON files land in raw/ from the extract task. The two Dataproc Serverless jobs read from GCS and write partitioned Parquet to silver/ and gold/. The scripts/ folder holds the PySpark job files that Dataproc executes.

gcs lakehouse layout
gs://worldcup-football-bucket/
├── raw/
│   ├── worldcup_teams.ndjson
│   ├── worldcup_standings.ndjson
│   └── worldcup_matches.ndjson
├── silver/
│   ├── teams/       ← partitioned Parquet, snappy compression
│   ├── standings/   ← partitioned Parquet, snappy compression
│   └── matches/     ← partitioned Parquet, snappy compression
├── gold/
│   ├── teams/       ← curated Parquet, snappy compression
│   ├── standings/   ← curated Parquet, snappy compression
│   └── matches/     ← curated Parquet, snappy compression
└── scripts/
    ├── bronze_to_silver.py
    └── silver_to_gold.py

BigQuery materializes six tables in the worldcup_dataset dataset: three Silver, three Gold. Every table is an external table pointing at its GCS Parquet folder, which means the warehouse never duplicates storage. When Dataproc writes a new Parquet file, the next BigQuery query sees the latest data automatically.

tablerowsnotes
silver_teams32gs://.../silver/teams/*.parquet · cleaned team profiles, schema faithful to TheSportsDB
silver_standings32gs://.../silver/standings/*.parquet · group-stage standings, STRING-typed counts
silver_matches64gs://.../silver/matches/*.parquet · all fixtures, fixed schema
gold_teams32gs://.../gold/teams/*.parquet · curated with performance metrics
gold_standings32gs://.../gold/standings/*.parquet · points_per_game, win_percentage, running_total_points via window functions
gold_matches64gs://.../gold/matches/*.parquet · result classification, total_goals, home/away goal differentials

Every schema is declared explicitly in the DAG. No autodetect=True. Silver keeps most fields as STRING to stay faithful to TheSportsDB API's raw form. Gold introduces FLOAT-typed derived metrics (points_per_game, win_percentage, total_goals, home_goal_diff, away_goal_diff, running_total_points) that come from PySpark division and window aggregation. Every table has an ingested_at or gold_loaded_at TIMESTAMP for traceability.

// why string, not int, for count fields

TheSportsDB API returns numeric fields (goals scored, points, played games) as strings. Silver honestly reflects this. In Gold, PySpark's implicit string-to-double coercion makes arithmetic work correctly ("2" + "1" produces 3.0, not "21"), which I verified with a spot-check query against gold_matches. The tradeoff: analysts running SUM or AVG on a raw count field need to CAST to INT64 first. Casting to numeric types across the board would be more correct but adds real churn. I chose to accept the imperfection and document it here rather than optimize prematurely.

~/engineering.py
04 · engineering

Async extraction, quality gates, and explicit schemas

The extract task is an aiohttp async loop that fetches three endpoints from TheSportsDB: all teams in the competition, the league table (standings), and all fixtures for the season. Each response is normalized into newline-delimited JSON and uploaded to GCS via GCSHook. The loop has built-in retry with exponential backoff on HTTP 429 rate limits and non-200 responses.

dags/worldcup_elt_pipeline.py · async extraction with backoff
async def fetch_json(url):
    for attempt in range(RETRIES):
        try:
            async with aiohttp.ClientSession(
                timeout=aiohttp.ClientTimeout(total=30)
            ) as session:
                async with session.get(url) as response:
                    if response.status == 200:
                        data = await response.json()
                        if any(data.values()):
                            return data
                    elif response.status == 429:
                        wait_time = DELAY * (2 ** attempt)
                        logging.warning(f"Rate limited, wait {wait_time}s")
                        await asyncio.sleep(wait_time)
                    else:
                        logging.warning(f"HTTP {response.status}, retry {attempt+1}")
                        await asyncio.sleep(DELAY)
        except Exception as error:
            wait_time = DELAY * (2 ** attempt)
            logging.error(f"Error: {error}, retry {attempt+1}")
            await asyncio.sleep(wait_time)
    return None

Three GCSObjectExistenceSensor tasks wait in parallel for each raw file to land, in reschedule mode so a slow upstream doesn't tie up Composer resources. Bronze-to-Silver then runs as a Dataproc Serverless PySpark batch: reads NDJSON, explodes nested arrays, casts types, writes partitioned Parquet. Between Silver and Gold, a Python validation task checks row counts and required columns — if any check fails, the whole DAG fails before Gold is touched.

dags/worldcup_elt_pipeline.py · Silver quality gate
def validate_silver(**context):
    gcs = GCSHook()
    errors = []
    for entity in ["teams", "standings", "matches"]:
        folder_prefix = f"{PATHS['silver']}/{entity}/"
        all_files = gcs.list(BUCKET, prefix=folder_prefix)
        parquet_files = [p for p in all_files if p.endswith(".parquet")]
        if not parquet_files:
            errors.append(f"{entity}: no Parquet files found")
            continue
        file_bytes = gcs.download(BUCKET, parquet_files[0])
        df = pq.read_table(BytesIO(file_bytes)).to_pandas()
        if len(df) == 0:
            errors.append(f"{entity}: zero rows")
        required = REQUIRED_COLUMNS[entity]
        for col in required:
            if col not in df.columns:
                errors.append(f"{entity}: missing column {col}")
    if errors:
        raise ValueError(f"Validation failed: {errors}")

The final loads to BigQuery use GCSToBigQueryOperator with external_table=True and schema_fields=... pointing at pre-declared dictionaries derived from SchemaField objects. Every column has its type and mode declared before the load runs. BigQuery does not infer anything.

dags/worldcup_elt_pipeline.py · explicit schema declaration (gold_standings excerpt)
GOLD_SCHEMAS = {
    "standings": [
        SchemaField("standing_id", "STRING", mode="NULLABLE"),
        SchemaField("position", "STRING", mode="NULLABLE"),
        SchemaField("team_id", "STRING", mode="NULLABLE"),
        SchemaField("team_name", "STRING", mode="NULLABLE"),
        # ... 12 more fields ...
        SchemaField("points_per_game", "FLOAT", mode="NULLABLE"),
        SchemaField("win_percentage", "FLOAT", mode="NULLABLE"),
        SchemaField("goals_scored_per_game", "FLOAT", mode="NULLABLE"),
        SchemaField("goals_conceded_per_game", "FLOAT", mode="NULLABLE"),
        SchemaField("running_total_points", "FLOAT", mode="NULLABLE"),
        SchemaField("gold_loaded_at", "TIMESTAMP", mode="NULLABLE"),
    ],
    # teams and matches schemas omitted for brevity
}

# Convert SchemaField objects to JSON-safe dicts for the operator
GOLD_SCHEMA_DICTS = {
    name: [field.to_api_repr() for field in schema_list]
    for name, schema_list in GOLD_SCHEMAS.items()
}
~/decisions.md
05 · decisions

Ten decisions I made, and honest tradeoffs on each

01 · bronze stays in the lake

An earlier iteration loaded raw NDJSON into BigQuery as bronze_* tables; I removed those loads. Tradeoff: analysts can't SQL-query raw responses directly. Gain: no duplicated storage cost, cleaner medallion story.

02 · dataproc serverless over clusters

I submit a batch, GCP provisions ephemeral compute, runs the job, tears it down. Tradeoff: cold starts add 2–3 minutes per batch. Gain: no cluster sizing, no cost when idle.

03 · external tables over native bigquery

Every load uses external_table=True; BigQuery reads GCS Parquet, never duplicates it. Tradeoff: slightly slower reads than native storage. Gain: changes appear in the next query without a copy step.

04 · explicit schemas, no autodetect

I declared SchemaField objects for every column instead of autodetect=True. Tradeoff: runtime went from 11m 53s to 24m 53s (~2x). Gain: deterministic, validated loads.

05 · reschedule-mode sensors

All three GCS sensors use mode="reschedule", not poke, releasing the worker slot between checks. Gain: three parallel sensors don't starve a modest Composer executor pool.

06 · validation gate before gold, not after

If Silver is bad, Gold never runs and never gets overwritten with garbage. Gain: the pipeline fails loudly at the right moment, not after reaching analysts.

07 · write_overwrite for idempotency

Every load uses write_disposition="WRITE_OVERWRITE". Gain: re-runs produce deterministic table state. Note: not a documented BigQuery disposition, but the Airflow provider accepts it and it works.

08 · async extraction with backoff

aiohttp + asyncio instead of synchronous requests, with HTTP 429 exponential backoff. Overkill for 3 endpoints today, but the pattern generalizes to hundreds.

09 · empty execution_config after a debug session

An early run failed: a Dataproc-selected machine type didn't exist in my zone. An empty execution_config: {} forced zone-appropriate defaults, cutting runtime from 1h 13m to 12m.

10 · fan-out then converge, at every layer

Three entity streams run in parallel where they can, converge at both Dataproc batches (cross-reference needs), then fan back out to three parallel BigQuery loads.

~/impact.log
06 · impact and runtime

Three runs, one debugging story, honest numbers

The pipeline shipped end-to-end on Cloud Composer. Below are three real runs I captured, in the order I made them. Each row is a real Composer run ID; each duration is what Airflow measured.

run history
Run 1 · initial deployment
1h 13m 25s
First end-to-end run. Dataproc Serverless auto-selected an e4-custom-4-15872 machine unavailable in us-central1-a; provisioning failed and fell back to slower defaults with retries baked in.
Run 2 · after execution_config fix
11m 53s
An empty execution_config: {} on both Dataproc batches stopped auto-selection of bleeding-edge machine families. 73 minutes → 12 minutes: an 84% reduction from a two-line config change.
Run 3 · after explicit BigQuery schemas
24m 53s
Replaced autodetect=True with schema_fields=... on all six load tasks, adding roughly 13 minutes for per-field validation. Correctness costs runtime — the right tradeoff for a nightly pipeline.

The pattern is real and worth naming honestly. First run: 1h 13m. Fix a two-line config bug: 11m 53s. Add production-grade schemas: 24m 53s. Each move was a genuine engineering decision with a genuine tradeoff. The final production shape (Run 3) is slower than the peak-optimized run, and that is the correct answer for what the pipeline needs to do.

// on honest cost

Cloud Composer is not free. My environment burned roughly $1 to $2 per end-to-end run in Dataproc Serverless compute plus Composer's ambient overhead, funded from the GCP free trial credit. This complements Nova Retail's on-premise Docker approach: Nova runs at zero marginal cost on a single host; WFI runs on managed infrastructure with real cloud spend. A modern data platform typically needs both patterns depending on scale, elasticity requirements, and infrastructure ownership preferences.

~/stack.json
07 · tech stack

The tools, and what each one does here

Cloud Composer 2.17.7
Managed Airflow on GKE · hosts the 14-task DAG
Apache Airflow 2.11.1
Orchestration · fan-out/converge/validate/fan-out shape
Dataproc Serverless 2.1
Ephemeral PySpark batches · zero clusters managed
PySpark 3.x
Distributed transform · Bronze to Silver, Silver to Gold
Google Cloud Storage
Lakehouse · Bronze NDJSON + Silver/Gold Parquet
Google BigQuery
Warehouse · 6 external tables with explicit schemas
aiohttp + asyncio
Async API extraction · HTTP 429 backoff retry
pandas + pyarrow
Python-side Parquet validation · quality gate
Parquet + snappy
Columnar storage · Silver and Gold layers
NDJSON
Newline-delimited JSON · raw Bronze layer
GCS Existence Sensor
File-readiness gates · reschedule mode
GCSToBigQueryOperator
Loads to BigQuery · WRITE_OVERWRITE idempotency
SchemaField (BigQuery)
Explicit schema declarations · no autodetect
TheSportsDB API
Public REST API · teams, standings, matches endpoints
Python 3.11
Extract, validate, DAG code · Composer-provided runtime
// if i were scaling this up

For production against a broader competition catalog: parameterized league and season so the same DAG runs per league and consolidates at Gold; incremental loads replacing WRITE_OVERWRITE with partition-by-date and merge-on-key; numeric casting at the Spark layer so analysts can SUM(points) without a CAST; pytest coverage on extraction, transforms and schemas; dbt models on top of Silver; watermarks and idempotency keys for late-arriving data; and a Looker Studio or business API layer to close the loop to decisions.

~/limits.md
08 · honest limits

What this project does not do (yet)

No unit tests

Neither the DAG code nor the PySpark jobs have pytest coverage. Data quality is enforced through the runtime validate_silver_data gate, but there's no CI-time check against fixtures.

No incremental loads

Every run does WRITE_OVERWRITE, right for a bounded competition (32 teams, 64 fixtures) but wrong for a growing source. A live-season pipeline needs partition-by-date, watermarks, and merge-on-key.

Numeric fields stored as STRING

Silver keeps base fields like points, played_games, goals_for as STRING to match TheSportsDB's raw form. Analysts running SUM or AVG need to CAST to INT64 first.

No dbt on top

Gold logic is baked into silver_to_gold.py as PySpark code rather than SQL-authored, version-controlled, tested dbt models on top of Silver.

Only one league, one season

Hardcoded to LEAGUE_ID = "4429" and SEASON = "2026". A production platform would parameterize league and season and consolidate across leagues at Gold.

No downstream consumer story

Gold tables land in BigQuery. Looker Studio dashboards, a business-facing API, or embedded product charts don't exist yet — this is a foundation, not the whole platform.

let's talk

Need a data engineer who ships cloud-native pipelines?

I'm currently looking for Data Engineer / Analytics Engineer roles. UK-based, open to remote or hybrid.

read next

Other case studies