A containerized on-premise data platform I built for a multinational retail scenario. PostgreSQL, Spark, and Apache Airflow run as a five-service Docker Compose stack. A PySpark medallion pipeline (Bronze raw Parquet to Silver joined frame to Gold three-table dimensional model) flows through partitioned writes, broadcast joins, and explicit caching. Airflow orchestrates the pipeline daily with parameterized stock-vs-scaled execution from the same DAG.
Nova Retail Group is a fictional multinational retail and logistics organisation specialising in e-commerce, product distribution, and customer fulfillment. Their analysts and operations teams depend on a centralised PostgreSQL warehouse to answer questions about sales performance, regional behaviour, and product profitability. Their existing pipeline was a collection of manually executed Python scripts against fragmented database environments, with no historical preservation and no orchestration.
The brief identified four specific engineering constraints. Fragmented infrastructure: the organisation lacked a standardised environment for reproducible deployment. Manual ETL execution: workflows depended on operators remembering to run scripts in the right order. Limited historical data preservation: raw data was transformed in flight and discarded, so re-running analysis with new parameters meant re-ingesting from source. Runtime bottlenecks at growing volumes: pandas-based in-memory pipelines struggled past 100K-row datasets.
I was engaged as the on-premise data engineer responsible for transitioning Nova Retail from this fragmented, manual environment to a containerised, scheduled, distributed data platform. The deliverable had to do five things: deploy PostgreSQL reproducibly via Docker, build distributed PySpark ETL pipelines, implement Bronze/Silver/Gold medallion architecture, automate execution through orchestration, and support both production scheduling and ad-hoc scaled testing from the same DAG.
The platform had to be reproducible from a single command. Operations teams needed to bring up the entire stack (database, Spark engine, orchestrator) without per-machine setup. That meant containerising everything, declaring services as code, and gating dependent services on health checks. Anything less repeats the fragmentation that motivated the project.
Dataset note: Nova Retail uses the public Olist Brazilian e-commerce dataset. This same dataset appears in PayFlow earlier in this portfolio. PayFlow demonstrates classical normalised warehousing; Nova Retail demonstrates production-grade infrastructure (Docker, Airflow, medallion). Different engineering angles on the same dataset.
The entire platform runs as a five-service Docker Compose stack. PostgreSQL 15 as the warehouse, a custom Spark container as the execution environment, and Apache Airflow's three components (init, webserver, scheduler) as the orchestration layer. Persistent named volumes keep data across restarts. A health check on PostgreSQL gates dependent services from starting before the database is genuinely ready. One docker-compose up brings the whole stack online.
The Spark container is "sidecar Spark": it runs sleep infinity and stays alive as a long-lived execution environment. Airflow doesn't run Spark itself. When the DAG triggers, the BashOperator calls docker exec spark /opt/spark/bin/spark-submit ... to inject jobs into the running Spark container. This keeps orchestration decoupled from execution, lets Airflow restart independently of Spark, and matches the topology used when deploying against a managed cluster (Databricks, EMR, Dataproc) where docker exec becomes a cluster-submit API call.
The Airflow DAG accepts two parameters via Airflow's native Param API: scale_data (boolean, defaults to false) and scale_multiplier (integer 1-5, defaults to 2). Scheduled runs use the defaults, producing analytical truth from real Olist data. Manual triggers via the Airflow UI surface a form letting the operator request a scaled run for architecture validation. Both flow through the same DAG, the same Spark container, the same pipeline code.
with DAG( dag_id="retail_etl_pipeline", schedule_interval="0 6 * * *", # daily at 06:00 UTC params={ "scale_data": Param(False, type="boolean"), "scale_multiplier": Param(2, type="integer", minimum=1, maximum=5), }, ) as dag: run_spark_etl = BashOperator( task_id="run_full_etl_pipeline", bash_command=( "docker exec " "-e SCALE_DATA={{ 'true' if params.scale_data else 'false' }} " "-e SCALE_MULTIPLIER={{ params.scale_multiplier }} " "spark /opt/spark/bin/spark-submit " "--master local[*] " "/opt/retail_project/etl/run_pipeline.py" ), )
Bronze writes raw Parquet with mode="overwrite". Silver writes joined Parquet with mode="overwrite". Gold loads to PostgreSQL with mode="overwrite". The honest tradeoff: simple, deterministic, idempotent. Running the pipeline twice in a row produces the same warehouse state. Re-running after a failure picks up cleanly. The cost is that every run rebuilds every layer; for the data volumes Nova Retail operates at, that cost is negligible compared to the simplicity it buys.
The warehouse isn't a single-table mart. It's three purpose-built analytical tables, each at its own grain, each with its own primary key, each with its own indexes. Different queries hit different tables: fact_sales for transaction-level questions, sales_summary for state-by-category analysis, sales_by_month_state for time-series.
| table | grain / pk | columns |
|---|---|---|
| retail_gold.fact_sales | order_id + product_id | customer_id · seller_id · customer_state · payment_value DECIMAL(10,2) · payment_type · product_category_name · freight_value · order_purchase_timestamp · order_year/month/day · order_weekday |
| retail_gold.sales_summary | state + category | total_orders · total_revenue DECIMAL(12,2) · avg_order_value DECIMAL(10,2) |
| retail_gold.sales_by_month_state | year_month + state | total_orders · total_revenue DECIMAL(12,2) · avg_order_value DECIMAL(10,2) |
fact_sales answers "what happened in this order?" sales_summary answers "how does category X perform across states?" sales_by_month_state answers "how did state Y trend over time?" Separate tables with their own PKs and indexes let each query hit the right grain.
Revenue, payment values, and freight costs are consumed by analysts computing means, sums, and rolling averages. DECIMAL preserves precision through aggregation; FLOAT loses it. Same money-stays-money discipline as FibbieBanks.
Spark's JDBC writer can auto-create tables, but it auto-infers types and silently discards PRIMARY KEYs and indexes. By owning the schema in version-controlled SQL (sql/create_tables.sql), the warehouse gets full control: composite primary keys, NOT NULL constraints, DECIMAL precision, and five read-optimised indexes on fact_sales. The DDL auto-runs on first PostgreSQL container start via the /docker-entrypoint-initdb.d mount, so the schema exists before any data lands.
CREATE SCHEMA IF NOT EXISTS retail_gold; CREATE TABLE IF NOT EXISTS retail_gold.fact_sales ( order_id VARCHAR(255) NOT NULL, customer_id VARCHAR(255), product_id VARCHAR(255), seller_id VARCHAR(255), customer_state VARCHAR(100), payment_value DECIMAL(10,2), payment_type VARCHAR(100), product_category_name VARCHAR(255), freight_value DECIMAL(10,2), order_purchase_timestamp TIMESTAMP, order_purchase_date DATE, order_year INTEGER, order_month INTEGER, order_day INTEGER, order_year_month VARCHAR(7), order_weekday INTEGER, PRIMARY KEY (order_id, product_id) ); -- Read-optimised indexes for the 8 production queries CREATE INDEX IF NOT EXISTS idx_fact_sales_date ON retail_gold.fact_sales (order_purchase_date); CREATE INDEX IF NOT EXISTS idx_fact_sales_year ON retail_gold.fact_sales (order_year); CREATE INDEX IF NOT EXISTS idx_fact_sales_ym ON retail_gold.fact_sales (order_year_month); CREATE INDEX IF NOT EXISTS idx_fact_sales_state ON retail_gold.fact_sales (customer_state); CREATE INDEX IF NOT EXISTS idx_fact_sales_payment ON retail_gold.fact_sales (payment_type);
Three engineering patterns carry most of the scalability weight in this pipeline. Plus one pattern that catches silent failures most pipelines never notice.
The Bronze layer writes orders and order_items with .partitionBy("order_year", "order_month"), deriving partition columns from order_purchase_timestamp and shipping_limit_date respectively. Small dimension tables (customers, sellers, products) write unpartitioned. At current 555K-row scale this is invisible. At any volume beyond that, it's the single biggest architectural lever.
PARTITIONED_DATASETS = {
"orders": "order_purchase_timestamp",
"order_items": "shipping_limit_date",
}
def bronze_layer(datasets):
for name, df in datasets.items():
output_path = layer_path("bronze", name)
if name in PARTITIONED_DATASETS:
ts_col = PARTITIONED_DATASETS[name]
df_partitioned = (
df.withColumn("order_year", year(col(ts_col)))
.withColumn("order_month", month(col(ts_col)))
)
df_partitioned.write \
.mode("overwrite") \
.partitionBy("order_year", "order_month") \
.parquet(output_path)
else:
df.write.mode("overwrite").parquet(output_path)
The Silver layer joins seven tables. Two are small enough to broadcast to every Spark executor instead of shuffling: sellers at 3K rows and products at 33K rows. The customers table was tested as a broadcast target and removed when scaled testing showed it could exceed safe broadcast size; the discipline is to broadcast where the small side stays small, shuffle where it might grow.
silver_df = (
orders
.join(customers, "customer_id", "left")
.join(payments, "order_id", "left")
.join(items, "order_id", "left")
.join(broadcast(products), "product_id", "left") # 33K rows, safe
.join(broadcast(sellers), "seller_id", "left") # 3K rows, safe
.withColumn("payment_value", col("payment_value").cast("DECIMAL(10,2)"))
.withColumn("order_year", year(col("order_purchase_date")))
.filter(col("payment_value").isNotNull())
)
# Cache before reuse: count + write + downstream Gold all hit this frame
silver_df = silver_df.cache()
The Silver layer's joined output gets cached before any action. The Gold layer caches fact_sales after the column selection because it's used four times downstream (count + write + two summary aggregations). Without caching, Spark may recompute these chains on each subsequent action. This is the optimisation that made Gold at 2x scale finish in 59 seconds instead of several minutes.
After each PostgreSQL write, the loader reads back the target table via JDBC and counts rows. If the count matches the source DataFrame, validation passes; if not, a warning is logged. This catches silent failures: writes that "succeed" at the protocol level but lose rows due to constraint violations, transaction rollbacks, or driver bugs. Three Gold tables, three validation passes per pipeline run.
def load_df_to_postgres(df, schema_name, table_name, mode="overwrite"): row_count = df.count() df.write \ .format("jdbc") \ .option("url", jdbc_url) \ .option("dbtable", f"{schema_name}.{table_name}") \ .option("batchsize", 10000) \ .mode(mode) \ .save() # Validation: read back, count, compare check_df = df.sparkSession.read \ .format("jdbc") \ .option("url", jdbc_url) \ .option("dbtable", f"{schema_name}.{table_name}") \ .load() loaded = check_df.count() if loaded == row_count: logging.info("Validation OK: row count matches") else: logging.warning(f"Mismatch! Source: {row_count} | DB: {loaded}")
The same logger.py from XTD and FibbieBanks powers Nova's observability: @timed decorator for stage durations, cross-platform UTF-8 detection for emoji-safe console output, dual-handler setup, section() banners between stages. One pipeline.log file tells the whole story of any run.
2026-06-08 13:56:21 INFO Creating Spark Session 2026-06-08 13:57:02 INFO ============== Spark Session created successfully ============== 2026-06-08 13:57:02 INFO STEP 1: EXTRACT 2026-06-08 13:57:30 INFO orders: 99441 rows · customers: 99441 · order_items: 112650 order_payments: 103886 · reviews: 104162 · products: 32951 · sellers: 3095 2026-06-08 13:57:30 INFO STEP 2: BRONZE 2026-06-08 13:58:03 INFO Successfully written to Bronze: orders (partitioned by year/month) 2026-06-08 13:58:03 INFO Successfully written to Bronze: order_items (partitioned by year/month) 2026-06-08 13:58:03 INFO Successfully written to Bronze: customers · sellers · products · order_payments · reviews 2026-06-08 13:58:03 INFO STEP 3: SILVER 2026-06-08 13:58:37 INFO Valid records after cleaning: 118,431 2026-06-08 13:58:37 INFO STEP 4: GOLD 2026-06-08 13:59:14 INFO Fact Sales created: 118,431 records 2026-06-08 13:59:14 INFO Sales Summary created: 1,394 groups 2026-06-08 13:59:14 INFO Sales by Month + State created: 565 groups 2026-06-08 13:59:14 INFO STEP 5: LOAD TO POSTGRESQL 2026-06-08 13:59:43 INFO Load successful → retail_gold.fact_sales: 118,431 rows 2026-06-08 13:59:43 INFO Validation OK: row count matches 2026-06-08 13:59:53 INFO Load successful → retail_gold.sales_summary: 1,394 rows 2026-06-08 13:59:53 INFO Validation OK: row count matches 2026-06-08 14:00:05 INFO Load successful → retail_gold.sales_by_month_state: 565 rows 2026-06-08 14:00:05 INFO Validation OK: row count matches 2026-06-08 14:00:06 INFO PIPELINE COMPLETED 2026-06-08 14:00:07 INFO Step completed in 3m 11s
At ~500K rows (projected into the millions), full rebuilds cost minutes, not hours. "Every run produces the same warehouse state" is worth more than the gain from incremental loads. Past ~50M Silver rows, partition-aware updates become the natural next step.
Partition pruning only pays off at volume. orders/order_items grow with the business; dimension tables are bounded and would just add directory clutter if partitioned.
Inference does a full extra pass over each CSV. Seven CSVs means seven extra full reads per run. Explicit StructType schemas eliminate this and pin types correctly (e.g. review_score as integer, not string).
sellers (3K) and products (33K) are always safe to broadcast. customers (99K) was on the edge; scaled testing showed broadcast pressure, so it was reverted to a regular shuffle join.
fact_sales, sales_summary, sales_by_month_state each answer a different question at the right grain. The cost is three writes; the benefit is millisecond queries against the right table.
JDBC writes can fail silently. The pattern: write, read back the count, compare. Three Gold tables, three validation passes per run, catching failures before they become operational incidents.
Production needs real-data truth; architecture validation needs different volumes. One DAG with Param means the same orchestration code, two operating modes, controlled at trigger time — the same pattern real Airflow deployments use for backfills and replays.
SparkSubmitOperator couples Airflow's lifecycle to Spark's. The sidecar pattern keeps them independent — the same topology used when Airflow triggers Spark on a remote cluster.
Spark's JDBC writer silently discards PRIMARY KEYs and indexes on auto-create. Owning the schema in version-controlled SQL gives full control over constraints and read-optimised indexes.
Stock apache/spark:4.1.1 doesn't include the PostgreSQL JDBC driver. Baking it into a custom image makes "the right driver at the right version" part of the image contract, not a runtime risk.
Real numbers from two captured pipeline logs (June 2026): the stock production run that anchors analytical truth, and the 2x scaled validation run that proves the architecture handles substantially larger volumes than current production scale.
The 2x scaled run replicates source data via union, producing ~1.1M source rows that join-multiply to 7,533,104 Silver records. The pipeline processed all 7.5M rows end-to-end in 13m 14s with row-count validation passing on every Postgres load. Honest framing: this validates throughput, not analytical correctness. Row replication produces duplicate keys, which compound through joins; the 7.5M figure represents pipeline row-handling capacity, not distinct logical sales.
What it does prove, concretely: PySpark's distributed transform engine handled 7.5M rows through the medallion without intervention. The caching strategy paid off (Gold built three tables from a 7.5M-row cached fact_sales in 59 seconds total). Bronze partitioning scaled linearly (2x volume produced ~2x Bronze write time, not exponential). The JDBC load completed (7.5M rows over a single connection in ~5 minutes write + ~3.5 minutes validation).
The architecture has no hard ceiling within reach of single-machine deployment. The pipeline handled 13.5x more Silver rows than stock production scale on the same laptop. For Nova Retail's actual data growth trajectory (~500K rows now, projected millions), the design has substantial headroom. Beyond that, the same code deploys to a Spark cluster with only spark.master and memory config changes; the medallion separation, partitioning, broadcast strategy, and validation pattern all carry forward unchanged.
For production at higher volumes, the natural evolutions would be: parallel JDBC writes via Spark's numPartitions + partitionColumn to address the fact_sales load becoming the dominant cost at 2x scale and above; cross-platform Spark paths in spark_session.py (currently Windows-tuned hardcoded paths); incremental Silver via dynamic partition overwrite; Spark cluster deployment (Databricks, EMR, Dataproc), which the code is already shaped for; dbt models on top of Gold for analyst-authored transformations; migration tooling (Alembic, Flyway) for evolving DDL safely; and separated PostgreSQL instances for Airflow metadata vs warehouse, currently sharing one container for development simplicity.
I'm currently looking for Data Engineer / Analytics Engineer roles. UK-based, open to remote or hybrid.
Distributed PySpark ETL processing 1M synthetic banking transactions into a validated star schema with SHA-256 surrogate keys.
read-case-studyAsync aiohttp ingestion and PySpark medallion pipeline processing three years of UK carbon intensity data.
read-case-studyQuality-gated ELT platform turning unreliable weekly clinic file deliveries into a trusted Snowflake reporting database.
read-case-study