An incremental Spark Structured Streaming pipeline that ingests GH Archive
events into Delta Lake bronze / silver / gold tables, with per-stream
checkpointing and idempotent MERGE upserts for exactly-once recovery.
Backfilled 131M events (four weeks of GH Archive, January 1β28 2024) on a
single 8-core machine, and keeps up hour by hour afterwards, processing only
what is new.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GH Archive (data.gharchive.org) β
β Hourly .json.gz ~50 MB/file (NDJSON format) β
βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β download_gharchive()
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β data/raw/ 2024-01-15-0.json.gz, 2024-01-15-1.json.gz, ... β
βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β stream 1: bronze_ingest
β file source Β· maxFilesPerTrigger Β· ckpt/bronze
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BRONZE data/bronze/ (Delta Lake, partitioned by date) β
β β’ Verbatim event in _raw_json + id, type, created_at, _source_file β
β β’ Insert-only MERGE on id β append-only, never duplicated β
β β’ Malformed lines β quarantine/bronze (txnAppId/txnVersion append) β
βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β stream 2: silver_transform
β Delta source Β· ckpt/silver
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SILVER data/silver/ (Delta Lake, partitioned by date, CDF on) β
β β’ Explicit PySpark schema applied (GH_EVENT_SCHEMA) β
β β’ Upsert MERGE on id, pruned to the batch's date partitions β
β β’ Computed columns: date, repo_name, actor_login, event_type β
β β’ Data-quality checks + quarantine for bad records β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ¬βββββββββββ
β stream 3: gold_incremental β
β Change Data Feed Β· ckpt/gold β
β recompute touched keys β MERGE β
βΌ β
ββββββββββββββββββββββββββββββββββββββββββββββ β
β GOLD data/gold/ (Delta Lake) β β
β β’ daily_active_repos/ β DQ checks β
β β’ pr_merge_time/ β data/quarantine/
β β’ top_growing_repos/ β β
β β’ contributor_retention/ β β
ββββββββββββββββββββββββββββββββββββββββββββββ β
github-activity-lakehouse/
βββ .github/workflows/ci.yml # GitHub Actions CI (Python 3.11, Java 11)
βββ conf/config.py # Central configuration (paths, settings)
βββ src/
β βββ pipeline.py # Orchestrates the 3 streams (availableNow / continuous)
β βββ bronze/ingest.py # Raw files β Bronze stream (insert-only MERGE)
β βββ silver/schema.py # Explicit GH event StructType
β βββ silver/transform.py # Bronze β Silver stream (upsert MERGE, CDF)
β βββ silver/dq.py # Data quality checks + quarantine
β βββ gold/aggregations.py # Gold table definitions + batch rebuild
β βββ gold/incremental.py # Silver CDF β Gold stream (scoped recompute MERGE)
β βββ utils/streaming.py # Triggers, idempotent MERGE / append helpers
β βββ utils/spark_session.py # SparkSession factory with Delta config
βββ tests/
β βββ conftest.py # Shared pytest fixtures (spark, sample_df)
β βββ fixtures/sample_events.json # 10 realistic fake GH events
β βββ test_bronze.py
β βββ test_silver.py
β βββ test_gold.py
β βββ test_streaming.py # Incremental runs + crash/replay recovery
βββ scripts/
β βββ download_data.py # CLI to download GH Archive files
β βββ run_pipeline.py # CLI to run pipeline stages
βββ requirements.txt
βββ Makefile
βββ README.md
# 1. Clone the repo
git clone https://github.com/saisha-l/github-activity-lakehouse-.git github-activity-lakehouse
cd github-activity-lakehouse
# 2. Install dependencies (requires Python 3.11, Java 17)
make install
# 3. Download 3 days of data (72 hourly files)
make download
# 4. Run the incremental pipeline (processes only new data, then exits)
make pipeline
# Four-week backfill (2024-01-01..28, ~131M events, ~70 GB of Delta tables).
# Downloads 3 days at a time and deletes raw files once ingested; override
# the window with BACKFILL_START / BACKFILL_END
SPARK_DRIVER_MEMORY=12g make backfillmake backfill over 2024-01-01 β 2024-01-28 on one 8-core / 30 GB machine
(local Spark 3.5.1, Delta 3.1.0, Java 17):
| Table | Rows |
|---|---|
| bronze | 131,170,447 |
| silver | 131,170,447 |
| gold/daily_active_repos | 21,898,681 |
| gold/contributor_retention | 5,035,240 |
| gold/pr_merge_time | 2,910,093 |
| gold/top_growing_repos | 1,820,944 |
- Data quality: 0 % null ids, 0 % duplicates, no schema drift, 0 quarantined rows.
- ~28 min per 3-day chunk (~13M events); ~6 h end to end. Bronze ingests ~14k events/s.
- Storage: ~0.54 GB per million events for Bronze + Silver with zstd (Bronze keeps every event's raw JSON).
- The run was interrupted six times (four out-of-memory crashes, two deliberate restarts) and resumed from its checkpoints each time; Bronze and Silver still match row for row with no duplicates, i.e. exactly-once in practice.
Tuning knobs that matter at this scale (environment variables, see
conf/config.py):
| Variable | Default | Why |
|---|---|---|
SPARK_DRIVER_MEMORY |
4g |
Local mode runs everything in the driver JVM; 12g was used above. |
MAX_FILES_PER_TRIGGER |
24 |
Raw files per Bronze micro-batch; 8 (one per core) was used above. |
SILVER_MAX_FILES_PER_TRIGGER |
3 |
Bronze files (~600k events each) per Silver micro-batch. |
RAW_CLEAN_SOURCE |
off |
delete removes raw files after their batch commits (make backfill sets it). |
SPARK_PARQUET_CODEC |
zstd |
Half the size of snappy for Bronze's raw JSON. |
SPARK_PARQUET_BLOCK_SIZE_MB |
32 |
Raw JSON expands ~8x on read; 128 MB row groups need ~1 GB heap per task. |
SPARK_LOCAL_CORES |
* |
Fewer cores = more memory per task when replaying an oversized batch. |
# Download a specific date range
PYTHONPATH=. python scripts/download_data.py --start 2024-01-01 --end 2024-01-07
# Incremental: drain whatever is new through all three streams, then exit.
# Re-run after every download (cron / Airflow / Databricks Job).
PYTHONPATH=. python scripts/run_pipeline.py --streaming --bronze --silver --gold --stats
# Long-running: all three streams concurrently, 1-minute micro-batches
PYTHONPATH=. python scripts/run_pipeline.py --streaming --bronze --silver --gold \
--trigger-interval "1 minute"
# Batch full rebuild / repair (idempotent; does not touch checkpoints)
PYTHONPATH=. python scripts/run_pipeline.py --bronze --silver --dq --gold| Stream | Source | Sink write | Checkpoint |
|---|---|---|---|
bronze_ingest |
data/raw/ file source (maxFilesPerTrigger, default 24 = 1 day) |
MERGE β¦ WHEN NOT MATCHED INSERT on id |
checkpoints/bronze |
silver_transform |
Bronze Delta table | MERGE upsert on id, update only if _ingested_at is newer |
checkpoints/silver |
gold_incremental |
Silver Change Data Feed | recompute touched keys β MERGE (update / insert / delete-stale) |
checkpoints/gold |
Why it's exactly-once. Structured Streaming checkpoints record each micro-batch's source offsets before it runs and a commit marker after it finishes. If the job dies between the Delta commit and the checkpoint commit, the restart replays the same batch with the same input. Every sink write is idempotent, so the replay changes nothing:
- Bronze: insert-only MERGE, so already-present ids are skipped. Delta runs an
insert-only merge as a pure append, so Bronze stays a valid append-only
streaming source. Quarantine appends carry
txnAppId/txnVersion=batchId, and Delta drops a write whose version it has already committed. - Silver: matched rows update only when
source._ingested_at > target._ingested_at. A replay matches every row and updates none. - Gold: each batch recomputes the affected
(date, repo),event_id,repoandactorslices from Silver with the same functions as the batch rebuild, then MERGEs them in. The output is a pure function of Silver, so a replay rewrites identical values.
tests/test_streaming.py checks this directly. It deletes the newest
commits/<id> file from each checkpoint (a crash after the sink commit), restarts,
and asserts the tables are unchanged. It also checks that incrementally
maintained Gold equals a full batch rebuild.
Scaling notes
- GH Archive files are gzip and can't be split (one task per file).
maxFilesPerTriggerbounds each micro-batch, so memory stays flat however long the backlog is. - MERGE conditions include a literal
date IN (...)predicate built from the batch, so Delta prunes the target down to the 1β2 partitions a batch touches instead of scanning the whole 100M+ row table. - Downloads land as hidden
.partfiles and are renamed atomically, so the file stream never reads a half-written file. - On first start the Gold CDF stream reads the full Silver snapshot, so no separate Gold backfill is needed.
- Source: GH Archive NDJSON files downloaded to
data/raw/ - Reader:
readStream.format("text")with a checkpoint, so each file is read once - Writer:
foreachBatchβ insert-onlyMERGEonid(pruned bydate) - Output: Delta table at
data/bronze/, partitioned bydate - Columns:
id,type,created_at,date,_raw_json(verbatim event),_source_file,_ingested_at - Bad lines: no
id/created_atβdata/quarantine/bronze/
- Source: Bronze Delta table (streaming source)
- Writer:
foreachBatchβMERGE INTOonid, so late duplicates, reruns and replays are idempotent - Change Data Feed: enabled (
delta.enableChangeDataFeed=true) to drive incremental Gold - Output: Delta table at
data/silver/, partitioned bydate - Transforms: explicit
GH_EVENT_SCHEMAapplied, computesrepo_name,actor_login,event_type, adds_processed_at - DQ checks: null_rate, schema drift, row count, duplicate rate, quarantine of bad records
Maintained incrementally by gold/incremental.py. make rebuild recomputes everything in batch from the same definitions.
| Table | Description |
|---|---|
daily_active_repos |
Events per repo per day + distinct actor count |
pr_merge_time |
Hours from PR creation to merge for merged PRs (keyed by event_id) |
top_growing_repos |
WatchEvent (star) counts per week + week-over-week growth |
contributor_retention |
Actors active in 2+ consecutive weeks flagged as retained |
Apply Z-ordering on the most common query predicates to co-locate related data:
OPTIMIZE delta.`data/silver/` ZORDER BY (repo_name, actor_login);
OPTIMIZE delta.`data/gold/daily_active_repos/` ZORDER BY (repo_name);AQE is enabled by default in this project (spark.sql.adaptive.enabled=true).
It handles:
- Coalescing shuffle partitions β avoids thousands of tiny partitions after joins
- Skew join handling β automatically splits oversized partitions from repos like
torvalds/linux
GH Archive data is inherently skewed β a handful of popular repos (e.g. microsoft/vscode)
generate orders of magnitude more events than average repos. Mitigations:
spark.sql.adaptive.skewJoin.enabled=true(default in this project)- Salt the join key with
F.concat(F.col("repo_name"), (F.rand() * 10).cast("int"))for heavy aggregations on repo_name - Use broadcast joins for small lookup tables (< 10 MB)
- Bronze / Silver: partitioned by
dateβ typical queries filter by date range - Gold: most Gold tables are small enough to skip partitioning;
daily_active_reposis partitioned bydatefor time-range queries
Override via env var: SPARK_SHUFFLE_PARTITIONS=400 make pipeline
Default is 200 for single-node; increase to 8 Γ num_cores for cluster mode.
The run_dq_checks() function in src/silver/dq.py validates:
| Check | Threshold | Action on failure |
|---|---|---|
null_rate |
< 5% null ids | Raises DataQualityError |
schema_drift |
All expected columns present | Warning logged |
row_count |
> 0 | Warning logged |
duplicate_rate |
Informational | Logged |
| Quarantine | null id or null created_at | Written to data/quarantine/ |
Adjust the threshold: conf/config.py β DQ_NULL_RATE_THRESHOLD.
# Full test suite
make test
# Specific test module
PYTHONPATH=. pytest tests/test_silver.py -v
# With detailed output on failure
PYTHONPATH=. pytest tests/ -v --tb=longTests use tmp_path fixtures so they never pollute data/.
- Bronze: audit columns, date partitioning, dedup, idempotent rerun, null-id quarantine, raw JSON retained
- Streaming: only new files are read, cross-file dedup, in-flight downloads ignored, crash-replay idempotency for Bronze / Silver / Gold, incremental Gold == batch rebuild
- Silver: global dedup, MERGE idempotency, derived columns, date extraction, DQ null-rate detection, quarantine
- Gold: daily_active_repos row uniqueness, pr_merge_time merged-only filter, top_growing_repos star counts, contributor retention logic
-
Upload the project to your Databricks workspace (or clone via Repos).
-
Create a cluster with:
- Databricks Runtime 14.x LTS (includes Spark 3.5 + Delta 3.x)
- Python 3.11
-
Install extra libraries (only
tqdmandrequestsare needed on Databricks β PySpark and Delta are pre-installed):tqdm==4.66.4 requests==2.32.3 -
Set environment variables in the cluster config:
LAKEHOUSE_ROOT=dbfs:/mnt/github-lakehouse -
Run the pipeline via a Databricks Job or notebook:
import sys sys.path.insert(0, "/Workspace/Repos/your-repo/github-activity-lakehouse") from src.utils.spark_session import get_spark from src.pipeline import run_incremental_pipeline spark = get_spark(local=False) # use existing Databricks cluster session run_incremental_pipeline(spark) # bronze β silver β gold, availableNow
-
Optimise with Delta features:
spark.sql("OPTIMIZE delta.`dbfs:/mnt/github-lakehouse/silver/` ZORDER BY (repo_name, date)") spark.sql("VACUUM delta.`dbfs:/mnt/github-lakehouse/silver/` RETAIN 168 HOURS")
I wanted to work with data engineering tools and Medallion architecture in practice.