~/case-studies/caresync.md
featured case study · ~10 min read

CareSync — quality-gated ELT platform for weekly clinic reporting

CareSync turns unreliable weekly clinic file deliveries into a trusted Snowflake reporting database. A third-party data aggregation agent drops six CSV exports into a shared Google Drive folder on a contractual schedule, outside Nexora's control over timing or format. The pipeline senses each file under a one-hour SLA, runs it through a pandas pre-validation gate before ingestion, loads validated files into Snowflake with idempotent, content-hashed writes, transforms them with dbt into a single-fact star schema, and runs a post-validation gate that verifies the reporting layer actually reconciles. Files that fail validation are quarantined and their dependent datasets are skipped automatically via the FK dependency graph, not failed outright, and stakeholders get a Slack and email alert the moment it happens, not just a mention buried in the end-of-run summary. All data is synthetic, generated with Synthea.

● featured Python 3.11 Google Drive API Snowflake + dbt GitHub Actions Slack + Email alerts
107K
source rows across 6 files
12
dbt models · 6 stg, 4 dim, 2 fct
53
passing checks · 38 dbt + 15 post-val
1h
SLA window for file arrival
2m 59s
end-to-end pipeline runtime
0
duplicate rows on re-run
~/problem.md
01 · the problem

A third-party agent drops six CSVs into Drive, on nobody's schedule but theirs

Nexora's partner clinics don't deliver data directly. A third-party data aggregation agent consolidates each clinic's weekly export and delivers six CSV files into a shared Google Drive folder on a contractual schedule. Clinic operations reviews, provider workload planning, and payer reconciliation all run off the weekly CareSync reports, so the timeliness and correctness of these files directly affect operational decisions across the clinic network.

Because a third party sits in the delivery chain, Nexora controls neither when files arrive nor what condition they arrive in. Delivery times drift, export formats change when clinic systems are upgraded, and files can arrive truncated or malformed. The brief was to deliver trustworthy weekly reporting by ensuring that only validated data enters the warehouse, only verified data reaches stakeholders, and every quality event (a late file, a rejected file, a failed business check, or a successful run) is communicated automatically. Because this project is intended for development and testing, Nexora uses synthetic healthcare data generated with Synthea, an open-source synthetic patient generator, giving realistic records with no exposure of real patient information.

// the architectural choice

Most pipelines gate quality once, at ingestion. I split the gate in two: a pre-validation pass before any file reaches Snowflake (schema, mandatory fields, UUID format, allowed values, chronology, duplicate IDs, row-count bounds), and a post-validation pass after dbt builds the reporting layer (table existence, row-count floors, and three cross-layer reconciliation queries). Passing the first gate only proves the input was well-formed; it says nothing about whether the warehouse the business actually queries is correct. The project is also deliberately staged in two tooling phases: everything is first built and proven with pandas validation orchestrated by GitHub Actions, then productionized by replacing every pandas check with Great Expectations suites and replacing GitHub Actions with Airflow: prove the logic is right cheaply, then move it onto industrial-grade tooling without redesigning the pipeline shape.

~/architecture.md
02 · architecture

Six stages, one dependency graph, cascade-skip all the way down

The whole pipeline runs as a single Python orchestrator calling six stages in order: sense, validate, load, transform, verify, notify. A Google Drive sensor checks for six expected files under a one-hour SLA and classifies each as found, missing, empty, too early, or late. A pandas pre-validation gate runs seven checks per file (parseability, expected columns, mandatory field format, UUID format, allowed values, chronology, row-count bounds). Anything that fails gets physically moved into a quarantine folder and fires its own Slack/email alert immediately, not just a line in the end-of-run digest. Healthy files load into Snowflake's RAW layer with idempotent, content-hashed writes. dbt transforms RAW into a staging layer and then a single-fact-grain star schema. A post-validation gate checks table population and three cross-layer reconciliation queries, then every stage's outcome rolls up into one unified Slack and email run report.

The six source files have real foreign-key dependencies on each other: an encounter references a patient, organization, provider, and payer, and a condition references an encounter and a patient, so the loader processes them in strict dependency order and propagates failures downstream automatically: if a file fails validation, everything that depends on it is skipped, not failed, while everything unaffected still loads, and the failure itself is quarantined and alerted on the moment it's detected, not held back for the final report.

sense
sensor.pyGoogle Drive API · 1-hour SLA · found / missing / empty / early / late
↓ 6 files ready
validate
pre_validation.pypandas · 7 checks per file · quarantine on fail
↓ load in strict FK dependency order
load · nexora_raw
organizationsno dependencies
payersno dependencies
providersno dependencies
patientsdepends on organizations
encountersdepends on patients, orgs, providers, payers
conditionsdepends on encounters, patients
↓ dbt build
transform · nexora_staging → nexora_prod
dbt_runner.py6 staging models → 4 dims + 2 facts · 38 dbt tests
↓ safety net
verify
post_validation.py12 table checks + 3 reconciliation queries
↓ every run, pass or fail
notify
notifications.pySlack + Email · immediate quarantine alerts + unified run report

The pattern that matters here is separation of concerns. The sensor only knows about file arrival. Pre-validation only knows about per-file correctness. The loader only knows about getting bytes into Snowflake exactly once. dbt only knows about modeling. Post-validation only knows about whether the finished warehouse actually answers the business's questions. Each stage can fail or quarantine independently without the others needing to understand why.

// the swappable source interface

sensor.py's docstring says it plainly: "DESIGNED FOR SWAPABILITY: All file-source logic is isolated. To swap → SFTP: replace ONLY the file-listing/timestamp section. SLA checks, reporting, alerts, and pipeline flow → ZERO changes." The Drive-specific code lives entirely behind two functions, fetch_source_files() and download_file(): a genuine interface boundary, not just a comment promising one. If Nexora's third-party agent ever moves from Google Drive to SFTP, only those two functions change.

~/schema.sql
03 · schema and storage

Three Snowflake layers, one single-fact-grain star schema

NEXORA_RAW.HL7 holds six tables defined by explicit DDL, not inferred from the CSV headers: the loader's COPY INTO maps file columns positionally into whatever columns the DDL already declares, plus four tracking columns (SOURCE_FILE, BATCH_ID, FILE_HASH, LOADED_AT) added automatically if they don't already exist. dbt then builds a staging layer in NEXORA_STAGING that drops or masks PHI, standardizes enums, and casts types, followed by a four-dimension, two-fact mart in NEXORA_PROD.

snowflake layer layout
NEXORA_RAW.HL7                          (raw, positionally loaded, hash-deduplicated)
├── ORGANIZATIONS                     (1,127 rows)
├── PAYERS                            (10 rows)
├── PROVIDERS                         (5,056 rows)
├── PATIENTS                          (1,163 rows)
├── ENCOUNTERS                        (61,459 rows)
└── CONDITIONS                        (38,094 rows)

NEXORA_STAGING.DBT_YISMAIL_HL7_HL7      (dbt staging · PHI dropped/masked, types cast)
├── stg_hl7__organizations
├── stg_hl7__payers
├── stg_hl7__providers
├── stg_hl7__patients                 (SSN, DRIVERS, PASSPORT, FIRST, LAST never pass through)
├── stg_hl7__encounters
└── stg_hl7__conditions

NEXORA_PROD.DBT_YISMAIL_HL7_HL7         (dbt marts · single-fact-grain star schema)
├── dim_organizations
├── dim_payers
├── dim_providers
├── dim_patients                      (masked initials, age, age_group, region)
├── fct_appointments                  (grain: one row per encounter)
└── fct_conditions                    (grain: one row per diagnosis)

The RAW→staging boundary is where privacy enforcement actually happens: SSN, DRIVERS, PASSPORT, FIRST, LAST, MAIDEN, and full street address never reach stg_hl7__patients at all: the staging model only selects the columns it needs, PHI columns are excluded by omission rather than deleted downstream. What stands in for a name is an initials-only patient_masked_name (e.g. J.S.), never a full surname.

mart tablegrainnotes
dim_patients1,163 rowspatient_id PK · masked initials, age / age_group (deceased patients aged as-of death), region, county
dim_providers5,056 rowsprovider_id PK · FK → dim_organizations · specialty_category, caseload_level
dim_organizations1,127 rowsorganization_id PK · revenue-based facility_size tier, utilization_level
dim_payers10 rowspayer_id PK · coverage_status, customer-count-based payer_size_tier
fct_appointments61,459 rowsgrain = encounter · FK → all 4 dims · coverage_percentage, encounter_duration_minutes
fct_conditions38,094 rowsgrain = diagnosis · FK → fct_appointments, dim_patients · condition_duration_days, is_active_condition
~/engineering.py
04 · engineering

SLA classification, content-hash idempotency, and cascade-skip

The sensor doesn't just check whether a file exists: it classifies arrival time against the SLA window on both ends. A file that shows up before the scheduled drop is just as suspect as one that's late: both get quarantined from the current run rather than silently accepted, with a dedicated Slack/email alert either way.

python/sensor.py · arrival classification against the SLA window
if arrived < scheduled_time:
    early_files.append(name)
    entry["sla_met"] = False
    entry["status"] = "TOO EARLY"
elif arrived > deadline_time:
    late_files.append(name)
    entry["sla_met"] = False
    entry["status"] = "LATE"
else:
    ready_files.append((name, info))
    entry["sla_met"] = True
    entry["status"] = "ON TIME"

The loader never truncates. Every file gets a SHA-256 hash of its filename plus its full byte content; before inserting, it checks whether that exact hash has already been loaded. Re-running the same week's file, intentionally or by a retriggered job, is a no-op, not a duplicate.

python/snowflake_loader.py · hash-based idempotency check
def compute_file_hash(file_path):
    hasher = hashlib.sha256()
    hasher.update(os.path.basename(file_path).encode("utf-8"))
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

# before inserting from the temp table...
cur.execute(f"SELECT COUNT(*) FROM {full_table} WHERE FILE_HASH = %s", (file_hash,))
if cur.fetchone()[0] > 0:
    logging.info(f"SKIP - {filename} already loaded")
    return 0  # FRESH, not LOADED: same content, no new rows

A file that fails pre-validation doesn't just get marked skipped in memory. It's physically moved out of the landing folder into a timestamped quarantine path, and its own Slack/email alert fires right there, independently of whatever else the run is still doing.

python/orchestrator.py · quarantine wired into the validation loop
passed, issues, row_count = validate_file(source_path)
if not passed:
    summary["pre_validation"]["quarantined"] += 1
    # move the file out of landing/ and fire the alert now,
    # not only as a line in the end-of-run summary
    quarantine_file(source_path, issues, row_count)

If one file in the dependency graph fails pre-validation, everything downstream of it is skipped, not failed, not silently processed with bad data, and the reason is traceable back to exactly which upstream file caused it.

python/orchestrator.py · cascade-skip resolution
# Skip Reason 1: this file's own validation failed
if filename in validated_results and not validated_results[filename]["passed"]:
    skip_status[filename] = f"SKIPPED: validation failed - {validated_results[filename]['issues']}"
    continue

# Skip Reason 2: an upstream dependency was itself skipped
skipped_deps = [dep for dep in deps if skip_status.get(f"{dep}.csv")]
if skipped_deps:
    skip_status[filename] = f"SKIPPED: upstream skipped - {', '.join(skipped_deps)}"
    continue

Post-validation runs after dbt succeeds, and checks something dbt's own tests can't: not just "did the models build" but "does the finished warehouse actually reconcile." Three business-level queries run independently of dbt's generic tests: staging-to-fact row count parity, no future-dated encounters, and patient count consistency across staging and dim layers.

python/post_validation.py · a reconciliation check, not just a row count
{
    "name": "Encounter reconciliation - STAGING = FACT",
    "query": f"""
        SELECT
          (SELECT COUNT(*) FROM NEXORA_STAGING.{STAGING_SCHEMA}.STG_HL7__ENCOUNTERS)
        = (SELECT COUNT(*) FROM NEXORA_PROD.{PROD_SCHEMA}.FCT_APPOINTMENTS) AS reconciled
    """
}
~/decisions.md
05 · decisions

Seven decisions I made, with honest tradeoffs on each

01 · quarantine + cascade-skip over fail-fast

A naive pipeline would abort the whole run if any one file failed validation. Instead, a failing file is physically quarantined, its own alert fires immediately, and only its dependents (via the real FK graph) are skipped; everything unaffected still loads. Tradeoff: more orchestration logic to track what depends on what. Gain: a bad payers.csv export doesn't block organizations from loading.

02 · idempotent loads via content hash, not truncate

The loader never truncates the RAW tables. Every file gets a SHA-256 hash of its filename plus full byte content, checked against FILE_HASH before inserting. Tradeoff: extra hashing and a lookup query on every load. Gain: re-running the same week's file is a safe no-op, never a duplicate row.

03 · key-pair auth over password for snowflake

The loader and validators connect via an RSA private key (cryptography's PKCS8 serialization), not a stored password. Tradeoff: key generation and rotation is more setup. Gain: no plaintext credential, and key-pair auth is Snowflake's own recommended pattern for service accounts.

04 · a genuinely swappable source interface

The Google Drive-specific code lives entirely behind fetch_source_files() and download_file() in sensor.py. Tradeoff: a thin abstraction layer even though only one source exists today. Gain: when the agent moves to SFTP, only two functions change.

05 · phi minimized at the staging boundary

SSN, DRIVERS, PASSPORT, FIRST, LAST, MAIDEN are excluded by omission in stg_hl7__patients rather than loaded and filtered later. Tradeoff: a future PHI need must be deliberately re-added. Gain: PHI has nowhere downstream to leak from, by construction.

06 · prove it cheap before going industrial

Validation and orchestration logic is built once with pandas checks and a GitHub Actions trigger, before being productionized onto Great Expectations and Airflow. Tradeoff: the first build isn't the final tool. Gain: the pipeline shape gets proven fast; the later swap is tooling, not redesign.

07 · post-validation as a second, independent gate

dbt's own generic tests run as part of dbt build, but post_validation.py runs separately with its own connection and reconciliation queries. Tradeoff: duplicated-looking checks, a second round-trip. Gain: a bug in the dbt project itself still gets caught.

~/impact.log
06 · impact and runtime

A real end-to-end run, every stage timed and logged

The pipeline runs end-to-end in under 3 minutes against real Snowflake infrastructure. Every stage logs structured timestamps, and the full run (sensor through final notification) is captured below from an actual run on October 18, 2026.

run timing
Sensor check + download (check_and_download)
~13s
Lists the Drive folder, classifies all 6 files as on-time, writes the SLA report, and downloads all 6 to the landing folder.
Pre-validate + load to NEXORA_RAW (6 files, strict order)
~85s
1,127 + 10 + 5,056 + 1,163 + 61,459 + 38,094 rows validated and loaded one file at a time, in FK dependency order.
dbt build (12 models, 36 dbt tests)
~31s
6 staging models build and test in parallel (6 threads), then 4 dimensions + 2 facts build on top. dbt's own reported execution time was 12.29s; the rest is dbt's own startup (parsing 689 macros, 36 nodes).
Post-validation (12 table checks + 3 reconciliation queries)
~43s
Independent Snowflake connection per check, verifying every staging and mart table is populated and that all reconciliations hold.
End-to-end pipeline runtime
2m 59s
Sensor start to final Slack/email notification. 36 of 36 dbt tests passed, 15 of 15 post-validation checks passed, 0 files quarantined.

All 6 files arrived on time and passed pre-validation. All 6 loaded to NEXORA_RAW with their exact source row counts. dbt built all 12 models and ran all 36 generic tests: PK uniqueness and not-null on every dimension and fact, relationship tests across every FK in the star schema, an accepted_values test on encounter_class, all without a single failure. Post-validation then independently re-verified table population and all three business reconciliation checks, and the unified run report went out over both Slack and email within seconds of the pipeline finishing. The marts layer has since picked up more PK/FK coverage and a singular grain test for fct_conditions, bringing the current suite to 38 dbt tests.

// on the two-stage roadmap

This run is Stage 1: pandas validation, GitHub Actions scheduling. Stage 2, the same validation rules re-expressed as Great Expectations suites, the same orchestration re-expressed as an Airflow DAG, is the deliberate next step, not a hypothetical. The pipeline shape (sense → validate → load → transform → verify → notify) and the swappable-interface discipline behind it are designed so that swap changes tooling, not architecture.

~/stack.json
07 · tech stack

The tools, and what each one does here

GitHub Actions
Orchestration trigger · scheduled weekly run
Google Drive API
File sensing · isolated behind a swappable interface
Python 3.x
Sensor, validation, loading, orchestration, notifications
pandas
Pre-load schema + type validation against expected columns
Snowflake
RAW → STAGING → PROD warehouse across 3 layers
snowflake-connector-python
Loading + post-validation · key-pair (RSA/PKCS8) auth
cryptography
Loads the private key for Snowflake key-pair auth
dbt-snowflake
12 models · staging + marts · 38 generic tests
dbt generic tests
unique, not_null, relationships, accepted_values
hashlib (SHA-256)
Content hash per file · idempotent re-run detection
Slack Incoming Webhook
Run report · friendly check descriptions · pass/fail summary
smtplib
Email run report · same summary as Slack
Synthea
Synthetic patient generator · no real PHI anywhere in the pipeline
PyYAML
dbt _tests.yml schema + test declarations
// if i were scaling this up

The honest next step is Stage 2 of the roadmap already designed into this pipeline: Great Expectations replacing the hand-written pandas checks in pre-validation, and an Airflow DAG replacing the GitHub Actions cron trigger for real dependency-aware scheduling and retries; both slot into the same six-stage shape without a redesign. Beyond that: SCD Type 2 on dim_patients so address and provider changes retain history instead of being overwritten; incremental dbt models rather than full-table rebuilds as source volume grows; column-level encryption and query audit logging for genuine HIPAA posture, not just PHI minimization; and a thin BI layer on top of the star schema.

~/limits.md
08 · honest limits

What this project does not do (yet)

No HIPAA compliance

PHI is minimized by omission at the staging boundary and names are masked to initials, but there's no column-level encryption, no query audit logging, and no formal access control layer. That's PHI-conscious design, not HIPAA compliance: worth naming as scope, not oversight, especially since the data is synthetic Synthea output anyway.

Stage 1 only: no Great Expectations or Airflow yet

Validation is hand-written pandas checks and orchestration is a GitHub Actions cron trigger. Both are deliberately designed to be swapped for Great Expectations and Airflow without reshaping the pipeline, but that swap hasn't happened yet.

No unit tests on the Python layer

Data quality is enforced at runtime by pre-validation and post-validation, but the sensor, loader, and orchestrator code itself has no pytest coverage. There's no CI-time check that a refactor of the cascade-skip logic or the SHA-256 dedup check still behaves correctly.

No SCD Type 2 on dim_patients

If a patient's region, county, or payer coverage changes between weekly loads, the previous value is overwritten. Real reporting often needs history. Adding SCD Type 2 would need effective-from/effective-to columns and updated load logic.

No backfill tooling

The pipeline expects one file set per week and quarantines what fails pre-validation. If a file is missed or quarantined, there's no automated reprocessing job: re-running means manually re-uploading to the source folder for the next scheduled run to pick up.

let's talk

Need a data engineer who ships quality-gated ELT pipelines?

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

read next

Other case studies