<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ausaf Fatima  on Medium]]></title>
        <description><![CDATA[Stories by Ausaf Fatima  on Medium]]></description>
        <link>https://medium.com/@ausaf.fatima.10?source=rss-a6171eee3a1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j2HZD3Y7qfjyfNY-</url>
            <title>Stories by Ausaf Fatima  on Medium</title>
            <link>https://medium.com/@ausaf.fatima.10?source=rss-a6171eee3a1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:00:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ausaf.fatima.10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Production-Grade Data Pipeline: Data Modeling, Quality, and System Design]]></title>
            <link>https://medium.com/@ausaf.fatima.10/building-a-production-grade-data-pipeline-data-modeling-quality-and-system-design-9c250f36cfdf?source=rss-a6171eee3a1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c250f36cfdf</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Ausaf Fatima ]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 15:55:43 GMT</pubDate>
            <atom:updated>2026-04-29T16:15:12.779Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>From raw clinical CSVs to an analytics-ready star schema in Snowflake, using Databricks, PySpark, Delta Lake, and Unity Catalog.</em></h4><p>Having worked with data pipelines, I wanted to go deeper into the design tradeoffs that make them production-ready. This project focuses on those decisions (architecture, data modeling, data quality), applied to a real healthcare pipeline.</p><p>This article walks through exactly what I built, why I made each design decision, and what I would add next.</p><h3>The Dataset: MIMIC-IV</h3><p>I used MIMIC-IV, a publicly available de-identified EHR (electronic health record) dataset from Beth Israel Deaconess Medical Center, covering over a decade of real patient admissions. It includes hospital admissions, ICU stays, diagnoses coded in ICD-9 and ICD-10, procedures, and patient demographics.</p><p>Working with real clinical data adds meaningful constraints: schema quirks, inconsistently coded categorical fields, and many-to-many relationships that can’t be flattened without losing information. I find that an interesting engineering problem.</p><h3>The Architecture: Medallion (Bronze → Silver → Gold)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dqNBQq943CuREZ1JKSU_g.png" /></figure><p>I chose Medallion Architecture because it solves a real problem: in a multi-stage pipeline, when something goes wrong, you need to know <em>which stage</em> it went wrong at.</p><p>Each layer has a single, clearly scoped responsibility:</p><p><strong>Bronze:</strong> Preserve the raw data with minimal transformation. Rename columns, trim whitespace, infer types. Write to Delta. Nothing else.</p><p><strong>Silver:</strong> Enforce data quality. Handle nulls, detect duplicates, standardize messy categoricals, derive computed columns, validate referential integrity across datasets. This is where clinical data gets messy.</p><p><strong>Gold:</strong> Model the data for analytics. Transform clean Silver tables into a star schema with facts, dimensions, and bridge tables. Export to Parquet for Snowflake ingestion.</p><p>This separation means I can rerun Silver without re-ingesting from S3. I can rebuild Gold without touching Silver. Each layer is independently auditable.</p><h3>Bronze: Ingesting 7 Raw CSV Files</h3><p>The source data is seven raw CSV files landing in S3:</p><p>admissions.csv: one row per hospital admission<br>icustays.csv: one row per ICU stay (an admission can have multiple)<br>patients.csv: demographic info per patient<br>diagnoses_icd.csv: ICD-coded diagnoses per admission<br>d_icd_diagnoses.csv: the ICD diagnosis code reference/lookup table<br>procedures_icd.csv: ICD-coded procedures per admission<br>d_icd_procedures.csv: the ICD procedure code reference/lookup table</p><p>The Bronze logic is intentionally minimal:</p><pre>df_admissions = spark.read.format(&#39;csv&#39;) \<br> .options(header=True, inferSchema=True) \<br> .load(&#39;s3://bucket/raw/admissions.csv&#39;)</pre><pre>df_admissions = df_admissions.select(<br> trim(col(&quot;subject_id&quot;)).alias(&quot;subject_id&quot;),<br> trim(col(&quot;hadm_id&quot;)).alias(&quot;hadm_id&quot;),<br> trim(col(&quot;admittime&quot;)).alias(&quot;admission_time&quot;),<br> …<br>)</pre><pre>df_admissions.write.format(&quot;delta&quot;) \<br> .mode(&quot;overwrite&quot;) \<br> .option(&quot;path&quot;, &quot;s3://bucket/landing/admissions/&quot;) \<br> .saveAsTable(&quot;mimic.bronze.admissions&quot;)</pre><p>A few intentional choices here:</p><p><strong>inferSchema=True:</strong> I let Spark infer types at this stage rather than hardcoding a schema as the Bronze layer is about raw preservation, and the files had straightforward schema.</p><p><strong>trim() on every column: </strong>Clinical source systems are famous for trailing whitespace. Catching it here means it doesn’t ruin joins downstream.</p><p><strong>Delta forma:</strong> ACID transactions and time-travel from the start. If a downstream run corrupts a table, I can roll back.</p><p><strong>Unity Catalog registration: </strong>Every table is registered under mimic.bronze.*, giving me a governed, lineage-aware metadata layer across all three stages.</p><h3>Silver: Where Real Data Engineering Happens</h3><p>Silver is where I spent the most time, and it’s where the interesting decisions live.</p><h4>Null Handling</h4><p>Not all nulls are equal. Some columns have nulls that are genuinely unknown, such as marital_status, discharge_location, so I fill those with “UNKNOWN” to keep the categorical distribution clean. Timestamp nulls like death_time are meaningful: a null means the patient didn’t die during that admission, so I leave those as-is.</p><pre>df_admissions = df_admissions.fillna({<br> &quot;marital_status&quot;: &quot;UNKNOWN&quot;,<br> &quot;discharge_location&quot;: &quot;UNKNOWN&quot;<br>})</pre><h4>Standardizing Messy Categoricals: The Race Column</h4><p>The race column in MIMIC is a perfect example of clinical data messiness. The raw values include things like “WHITE — OTHER EUROPEAN”, “WHITE — RUSSIAN”, “BLACK — AFRICAN AMERICAN”, “UNABLE TO OBTAIN”, and “PATIENT DECLINED TO ANSWER”.</p><p>I wrote a standardization step using when() chains to group these into clean, analysis-ready categories:</p><pre>df_admissions = df_admissions.withColumn(<br> &quot;race_grouped&quot;,<br> when(col(&quot;race&quot;).like(&quot;WHITE%&quot;), &quot;WHITE&quot;)<br> .when(col(&quot;race&quot;).like(&quot;BLACK%&quot;), &quot;BLACK&quot;)<br> .when(col(&quot;race&quot;).like(&quot;HISPANIC%&quot;), &quot;HISPANIC&quot;)<br> .when(col(&quot;race&quot;) == &quot;UNABLE TO OBTAIN&quot;, &quot;UNKNOWN&quot;)<br> .when(col(&quot;race&quot;) == &quot;PATIENT DECLINED TO ANSWER&quot;, &quot;UNKNOWN&quot;)<br> .otherwise(&quot;OTHER&quot;)<br>)</pre><p>Changes like these are domain and business-specific. We would need to clarify the business requirements to understand how these values are expected for the downstream systems or business users.</p><h4>Derived Columns</h4><p>Two key metrics are computed at the Silver stage rather than Gold, because they are properties of the raw event data and belong close to the source:</p><pre>df_admissions = df_admissions.withColumn(<br> &quot;length_of_stay_hospital_days&quot;,<br> round((unix_timestamp(col(&quot;discharge_time&quot;)) - unix_timestamp(col(&quot;admission_time&quot;))) / 86400, 2)<br>).withColumn(<br> &quot;length_of_stay_ed_hours&quot;,<br> round((unix_timestamp(col(&quot;ed_out_time&quot;)) - unix_timestamp(col(&quot;ed_reg_time&quot;))) / 3600, 2)<br>)</pre><h4>Referential Integrity Validation</h4><p>Before writing anything to Silver, I use a left_anti join to validate that child records actually have parent records, a step that’s essential for production:</p><pre>missing = df_diagnoses_final.join(df_admissions, &quot;hadm_id&quot;, &quot;left_anti&quot;).count()<br>print(missing) # Expected: 0</pre><p>This catches broken foreign keys before they silently corrupt downstream joins.</p><h3>Gold: Modeling a Star Schema</h3><p>The Gold layer is where the data becomes analytics-ready. I modeled a star schema with bridge tables to handle the many-to-many relationships inherent in clinical data.</p><h4>Why Bridge Tables?</h4><p>A hospital admission can have dozens of diagnoses. The same ICD code can appear across thousands of admissions. You can’t model this as a simple foreign key on fact_admissions. A bridge table is an appropriate pattern:</p><p>fact_admissions (hadm_id)<br> ↕<br>bridge_diagnosis (hadm_id, diagnosis_id, seq_num, is_primary)<br> ↕<br>dim_diagnosis (diagnosis_id, icd_code, icd_version, diagnosis)</p><p>The bridge_diagnosis table also carries seq_num (the clinical priority ordering of diagnoses) and an is_primary flag derived from seq_num == 1.</p><h4>Surrogate Key Generation</h4><p>ICD codes are not unique across ICD versions: the same code can mean different things in ICD-9 vs ICD-10. I generated surrogate keys using PySpark’s row_number() window function:</p><pre>window = Window.orderBy(&quot;icd_code&quot;, &quot;icd_version&quot;)<br><br>temp = diagnoses.withColumn(&quot;diagnosis_id&quot;, row_number().over(window)) \<br> .select(&quot;diagnosis_id&quot;, &quot;hadm_id&quot;, &quot;icd_code&quot;, &quot;icd_version&quot;, &quot;seq_num&quot;, &quot;diagnosis&quot;, &quot;is_primary&quot;)<br><br>dim_diagnosis = temp.select(&quot;diagnosis_id&quot;, &quot;icd_code&quot;, &quot;icd_version&quot;, &quot;diagnosis&quot;)<br>bridge_diagnosis = temp.select(&quot;hadm_id&quot;, &quot;diagnosis_id&quot;, &quot;seq_num&quot;, &quot;is_primary&quot;).dropDuplicates()</pre><h4>Pre-Aggregating Metrics in fact_admissions</h4><p>Rather than forcing every downstream query to join and aggregate, I pre-computed key metrics directly into the central fact table:</p><pre>icu_temp = fact_icu_stays.groupBy(&quot;hadm_id&quot;) \<br>.agg(sum(&quot;length_of_stay&quot;).alias(&quot;icu_stay_total_days&quot;) \<br>,count(&quot;*&quot;).alias(&quot;num_icu_stays&quot;)<br>)</pre><p>fact_admissions ends up carrying icu_flag, icu_stay_total_days, num_icu_stays, num_diagnoses, and num_procedures: all pre-joined and aggregated. A BI tool querying this table doesn’t need to touch a single bridge or fact_icu_stays row to get admission-level summaries.</p><h3>Snowflake: Serving the Star Schema</h3><p>The Gold layer writes two outputs: Delta tables registered in Unity Catalog, and Parquet files exported to a separate S3 prefix for Snowflake ingestion. This is because Snowflake does not natively support Delta files.</p><p>On the Snowflake side, the load uses COPY INTO from an S3 external stage:</p><pre>COPY INTO health.mimic.fact_admissions<br>FROM @my_s3_stage/fact_admissions/<br>FILE_FORMAT = (TYPE = PARQUET)<br>MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE<br>PATTERN = &#39;.*\.parquet&#39;;</pre><p>MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE means Snowflake maps Parquet column names to table columns regardless of case, which adds resilience to minor upstream schema drift.</p><h3>What the Final Data Model Looks Like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3UggvAcs8WIHmXeGom6DQ.png" /></figure><p>The full star schema delivers seven tables:</p><p>fact_admissions: 1 row per hospital admission (central fact table)<br>fact_icu_stays: 1 row per ICU stay<br>dim_patient: 1 row per patient<br>dim_diagnosis: 1 row per unique ICD diagnosis code + version<br>dim_procedure: 1 row per unique ICD procedure code + version<br>bridge_diagnosis: 1 row per admission–diagnosis pair<br>bridge_procedure: 1 row per admission–procedure pair</p><p>A clinician or analyst working with this schema can answer questions like:</p><p>What’s the average hospital length of stay for patients with a primary diagnosis of pneumonia?<br>What percentage of admissions resulted in an ICU stay?<br>What are the most common procedures performed on patients over 65?</p><p>…without writing a single join to raw source tables.</p><h3>What I Would Add Next</h3><p>This project is an MVP. In a production context, I would extend it with:</p><p><strong>Handling PII: </strong>Since MIMIC-IV is already de-identified, handling Personally Identifiable Information (PII) wasn’t required here. But in a production setting, this would include column-level access control, data masking, or encryption when storing the data.</p><p><strong>Incremental processing: </strong>The current pipeline runs full overwrites. A production version would use Delta Lake’s merge capabilities or watermark-based incremental loads keyed on admission_time.</p><p><strong>Orchestration: </strong>Apache Airflow to sequence Bronze → Silver → Gold with dependency management, retry logic, and alerting.</p><p><strong>Data quality framework: </strong>Great Expectations or Databricks’ built-in quality checks wired to a monitoring dashboard, rather than ad-hoc assertions in notebooks.</p><p><strong>CI/CD: </strong>A GitLab CI pipeline to run a lightweight test suite against sample data before any notebook changes are merged.</p><h3>Closing Thoughts</h3><p>Healthcare data engineering is genuinely hard. The data is messy, the domain requires careful handling, and the stakes for data quality are real. Building this pipeline forced me to think carefully about null semantics, many-to-many relationships, surrogate key design, and the tradeoffs between modeling choices.</p><p>The tech stack (PySpark, Delta Lake, Unity Catalog, Databricks, Snowflake) is what you would find at most mature data organizations today. More importantly, the patterns (Medallion Architecture, star schema modeling, bridge tables, referential integrity validation, data quality) transfer regardless of the specific tools.</p><p>If you’re on a data engineering team building analytics pipelines using sensitive data, and want to talk about this work, I would love to connect.</p><p>All code for this project is available on <a href="https://github.com/ausaffatima/mimic-health-data-engineering-pipeline">GitHub</a>. The MIMIC-IV dataset requires credentialing via PhysioNet (details mentioned in the readme file).</p><p>Tags: #DataEngineering #PySpark #Databricks #Snowflake #DeltaLake #UnityCatalog #Healthcare #MedallionArchitecture #DataModeling #DataPipeline</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c250f36cfdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>