













Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!














Document status: This document is an original implementation report and portfolio artifact for the WGU D608 Data Processing ETL Pipeline project. It describes a reproducible pipeline using Amazon S3, Amazon Redshift, Apache Airflow, Python, and SQL, with integrated data quality gates. It does not claim that a WGU evaluator has approved this specific submission, and it does not claim that every AWS console action or Airflow run has been independently audited. The expected dataset characteristics and transformation logic reported here are consistent with the publicly documented Udacity Data Engineering course materials that underpin D608 and with the D608 assessment structure, which requires building an ETL pipeline and submitting code plus a written report. The exact current D608 Task 1 rubric wording remains unverified; the structure below is aligned to the publicly reported assessment expectations and to the Udacity S3-to-Redshift Airflow project requirements.
1. EXECUTIVE SUMMARY D608 requires students to demonstrate competence in building and optimizing data pipelines for large-scale analytics using Apache Airflow and AWS Redshift. The project typically involves staging data from Amazon S3 into Amazon Redshift, orchestrating the workflow with Airflow DAGs, applying transformations in SQL and Python, and validating data quality before and after load. This report documents an end-to-end ETL pipeline that extracts semi-structured event data from S3, stages it in Redshift, transforms it into a dimensional model, and enforces data quality gates at both the staging and final-table boundaries. Apache Airflow orchestrates the dependency graph: S3-to-Redshift staging, dimension and fact table loads, and SQL-based quality checks that halt the pipeline if row-count, uniqueness, or completeness thresholds are violated. The implementation uses Airflow’s S3ToRedshiftOperator, PostgresOperator (for Redshift SQL), and SQLColumnCheckOperator/SQLTableCheckOperator for data quality, with supporting Python callables for custom validation logic. The pipeline is designed for reproducibility: it uses parameterized SQL, idempotent DELETE+INSERT loading patterns, and explicit Airflow task dependencies so that re-runs do not duplicate data. A companion validation layer using Great Expectations-style assertions (implemented in Python and SQL) provides a second, independent check on data integrity.
2.1 Business Context The Udacity Data Engineering course that supports D608 frames the project around a music- streaming company (Sparkify) that needs to move event data from S3 into Redshift for analytics. The data includes song plays, user activity, and song metadata. The analytics team requires a reliable, scheduled pipeline that can answer questions about user listening behavior, song popularity, and session patterns. 2.2 Data Engineering Problem The source data resides in S3 as JSON log files. The target is a Redshift cluster with a star schema consisting of fact and dimension tables. The pipeline must:
│ WAREHOUSE — Amazon Redshift │ │ Staging: staging_events, staging_songs │ │ Final: songplays (fact), users, songs, artists, time (dimensions) │ └──────────────────────────────┬ ──────────────────────────────────────────────┘ │ ▼ ┌───────────────────────────────────────────────────────────────────────────── ┐ │ DATA QUALITY — SQL checks + Python assertions │ │ Row-count thresholds, primary-key uniqueness, null completeness, │ │ referential integrity between fact and dimensions │ └───────────────────────────────────────────────────────────────────────────── ┘ 3.2 Service Responsibilities Component Role Rationale Amazon S Durable storage for raw JSON logs and song metadata Decouples storage from compute; suppo Airflow’s S3 operators Amazon Redshift Columnar data warehouse for staging and star-schema tables Optimized for analytical SQL; supports CO from S3 at scale Apache Airflow Workflow orchestration, scheduling, retries, and dependency management DAG-based dependency modeling; rich operator ecosystem for AWS and SQL
Component Role Rationale Python Custom validation logic, data profiling, and operator callables Flexible for checks that are awkward in p SQL SQL Transformations and declarative data quality checks Set-based, auditable, and native to Redsh 3.3 Why This Architecture The S3-to-Redshift pattern is the canonical Udacity Data Engineering pipeline for this course and aligns with the D608 focus on “building and optimizing data pipelines for large-scale analytics using technologies like Apache Airflow and AWS Redshift” [citation:10]. Airflow provides the orchestration layer that D608 explicitly assesses, and Redshift provides the warehouse target that supports the SQL transformations and quality checks required by the rubric.
4. DATA SOURCES AND SCHEMA DESIGN 4.1 Source Data Source Format Content S log_data/ JSON (newline- delimited or nested) User activity events: artist, auth, firstName, gender, itemInSession, lastName, length, level, location, method, page, registration, sessionId song, status, ts, userAgent, userId S song_data/
Song metadata: artist_id, artist_latitude, artist_longitude, artist_locati artist_name, duration, num_songs, song_id, title, year 4.2 Staging Tables sql CREATE TABLE IF NOT EXISTS staging_events ( artist VARCHAR, auth VARCHAR,
title VARCHAR, duration DOUBLE PRECISION, year INTEGER ); 4.3 Final Star Schema Table Type Primary Key Foreign Keys songplays Fact songplay_id (identity) start_time → time, user_id → users, song_id → songs, artist_id → artists users Dimension user_id — songs Dimension song_id — artists Dimension artist_id — time Dimension start_time — The songplays fact table captures each song-play event, with level (free/paid) as a degenerate dimension and session_id and location as additional descriptive attributes.
5. IMPLEMENTATION 5.1 Airflow DAG Structure The DAG uses a linear dependency chain with explicit quality gates: text stage_events ──▶ stage_songs ──▶ load_users ──▶ load_songs ──▶ load_artists │ ▼ load_time ──▶ load_songplays ──▶ quality_checks
Each load task runs a SQL INSERT ... SELECT from staging into the target dimension or fact table. The quality_checks task group runs SQL check operators and Python assertions. If any check fails, the DAG halts and downstream tasks do not execute. 5.2 Staging Tasks (S3 → Redshift) Airflow’s S3ToRedshiftOperator handles the staging loads: python from airflow.providers.amazon.aws.transfers.s3_to_redshift import S3ToRedshiftOperator stage_events = S3ToRedshiftOperator( task_id="stage_events", schema="public", table="staging_events", s3_bucket="sparkify-data", s3_key="log_data/{{ ds }}", copy_options=["FORMAT AS JSON 'auto'"], redshift_conn_id="redshift_default", aws_conn_id="aws_default", dag=dag, ) stage_songs = S3ToRedshiftOperator( task_id="stage_songs", schema="public", table="staging_songs", s3_bucket="sparkify-data", s3_key="song_data/", copy_options=["FORMAT AS JSON 'auto'"],
year, duration FROM staging_songs WHERE song_id IS NOT NULL; INSERT INTO artists (artist_id, name, location, latitude, longitude) SELECT DISTINCT artist_id, artist_name AS name, artist_location AS location, artist_latitude AS latitude, artist_longitude AS longitude FROM staging_songs WHERE artist_id IS NOT NULL; Time dimension: sql INSERT INTO time (start_time, hour, day, week, month, year, weekday) SELECT DISTINCT ts AS start_time, EXTRACT(hour FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS hour, EXTRACT(day FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS day, EXTRACT(week FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS week, EXTRACT(month FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS month, EXTRACT(year FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS year, EXTRACT(weekday FROM TIMESTAMP 'epoch' + ts/1000 * INTERVAL '1 second') AS weekday FROM staging_events
WHERE ts IS NOT NULL; Songplays fact table: sql INSERT INTO songplays ( start_time, user_id, level, song_id, artist_id, session_id, location, user_agent ) SELECT e.ts AS start_time, e.userId AS user_id, e.level, s.song_id, s.artist_id, e.sessionId AS session_id, e.location, e.userAgent AS user_agent FROM staging_events e JOIN staging_songs s ON e.song = s.title AND e.artist = s.artist_name AND e.length = s.duration WHERE e.page = 'NextSong'; The three-key join on title, artist, and duration is the standard Udacity approach; a production system would likely use a canonical song_id in the event stream to avoid fuzzy matching. 5.4 Idempotency Each load task begins with a DELETE scoped to the load window (or uses a TRUNCATE for full refreshes): sql
conn_id="redshift_default", dag=dag, ) 6.2 Python Assertions for Referential Integrity SQL check operators are excellent for single-table constraints, but referential integrity across fact and dimension tables benefits from explicit Python assertions that query both sides and fail with a descriptive message. python from airflow.operators.python import PythonOperator import psycopg def check_referential_integrity(*context): conn = psycopg2.connect( host=context["params"]["redshift_host"], dbname=context["params"]["redshift_db"], user=context["params"]["redshift_user"], password=context["params"]["redshift_password"], port=5439, ) cur = conn.cursor() checks = [ ("songplays.user_id → users.user_id", "SELECT COUNT() FROM songplays s LEFT JOIN users u ON s.user_id = u.user_id WHERE u.user_id IS NULL"), ("songplays.song_id → songs.song_id",
"SELECT COUNT() FROM songplays s LEFT JOIN songs so ON s.song_id = so.song_id WHERE s.song_id IS NOT NULL AND so.song_id IS NULL"), ("songplays.artist_id → artists.artist_id", "SELECT COUNT() FROM songplays s LEFT JOIN artists a ON s.artist_id = a.artist_id WHERE s.artist_id IS NOT NULL AND a.artist_id IS NULL"), ("songplays.start_time → time.start_time", "SELECT COUNT(*) FROM songplays s LEFT JOIN time t ON s.start_time = t.start_time WHERE t.start_time IS NULL"), ] failures = [] for label, query in checks: cur.execute(query) orphan_count = cur.fetchone()[0] if orphan_count > 0: failures.append(f"{label}: {orphan_count} orphan rows") cur.close() conn.close() if failures: raise ValueError("Referential integrity failures: " + "; ".join(failures)) 6.3 Completeness and Freshness Checks
default_args = { "owner": "data-engineering", "depends_on_past": False, "email_on_failure": True, "email": ["[email protected]"], "retries": 2, "retry_delay": timedelta(minutes=5), } dag = DAG( dag_id="sparkify_etl", default_args=default_args, description="S3 to Redshift ETL with data quality gates", schedule_interval="@daily", start_date=datetime(2025, 1, 1), catchup=False, max_active_runs=1, tags=["d608", "etl", "redshift"], ) 7.2 Task Dependencies python stage_events >> stage_songs stage_songs >> [load_users, load_songs, load_artists, load_time] [load_users, load_songs, load_artists, load_time] >> load_songplays load_songplays >> quality_checks
The dimension loads are parallelizable because they read from staging tables and write to independent dimension tables. The fact load depends on all dimensions being present, and the quality gate depends on the fact load completing. 7.3 Retry and Alerting
Challenge Resolution Airflow-to-Redshift connectivity Used Airflow connections with encrypted credentials; noted that MWAA or a manag secrets backend should replace plaintext connection definitions in production. Idempotency of dimension loads Used DISTINCT and scoped DELETE to prevent duplicate dimension rows on retry; discussed the trade-off between full refresh and incremental merge. Data quality alert fatigue Thresholds were set conservatively; documented the need for baseline profiling bef tightening row-count or reconciliation thresholds. The central lesson is that orchestration without quality gates is incomplete. Airflow makes it easy to schedule tasks, but the value of the pipeline depends on failing fast when data does not meet expectations.
10. CONCLUSION This project delivers an Airflow-orchestrated ETL pipeline that extracts JSON event and song data from S3, stages it in Redshift, transforms it into a star schema, and enforces data quality at the staging and post-load boundaries. The DAG uses native Airflow operators for S3-to-Redshift transfer and SQL checks, supplemented by Python assertions for referential integrity. The design is idempotent, parameterized by execution date, and documented so that the transformation logic and quality gates can be reproduced. The pipeline satisfies the D608 emphasis on Apache Airflow orchestration and AWS Redshift processing [citation:10], and it addresses the data quality dimension that distinguishes a production-grade ETL implementation from a one-off script. The documented limitations—fuzzy song matching, JSON format assumptions, and threshold calibration—are explicit and provide a clear path for production hardening. APPENDIX A — REPOSITORY STRUCTURE text d608-etl-pipeline/ ├── README.md
├── dags/ │ └── sparkify_etl.py ├── plugins/ │ └── operators/ │ └── data_quality.py ├── sql/ │ ├── create_tables.sql │ ├── staging_to_dimensions.sql │ └── staging_to_fact.sql ├── tests/ │ ├── test_referential_integrity.py │ └── test_row_counts.py └── docs/ └── technical_report.md APPENDIX B — RUBRIC-ALIGNED CHECKLIST Rubric-Relevant Element Location in This Report Problem statement and business need Section 2 End-to-end architecture Section 3 S3 source and Redshift schema design Section 4 Airflow DAG implementation Section 5. S3-to-Redshift staging Section 5.