Scalable Daily ETL for 25,000 Supplier CSVs

Medium · System Design · Data Analyst · Technical Screen

Prompt

Every day, external vendors upload 25,000 separate CSV files into your organization's cloud object storage bucket (such as Amazon S3). Across vendors, these exports use different column headers, inconsistent date representations, and occasional corrupt records. Design an automated ETL (Extract, Transform, Load) architecture that ingests, cleans, and loads this data into a central cloud analytics warehouse (such as Snowflake or BigQuery) for business reporting.

Your design must satisfy the following requirements:

  • Core capabilities: Pull raw vendor uploads from object storage; map heterogeneous vendor layouts onto a unified canonical schema; isolate invalid rows so corrupt records do not crash or stall healthy data; and guarantee idempotency so reprocessing an identical file never produces duplicate rows in the warehouse.
  • Operational guarantees: Finish ingesting all 25,000 daily files within a 4-hour processing window; maintain queryable per-file lifecycle state across Pending, Success, and Failed; and notify the data engineering team whenever validation fails without causing alert storms.

Scope & Expectations

  • End-to-end architecture & storage tiers: Map out the ingestion, staging, transformation, orchestration, and warehouse layers from raw object landing through analytics tables.
  • Throughput & idempotency: Show how workers, metadata tracking, and warehouse loads finish 25,000 files inside 4 hours while preventing duplicate loads across retries and re-uploads.
  • Schema drift management: Explain how the pipeline handles unannounced vendor layout changes, such as newly added columns or renamed headers.
  • Row-level & file-level error isolation: Describe how malformed rows and broken files are quarantined (for example, via dead-letter storage) and surfaced to engineers for inspection and replay.

Step-by-step walkthrough

  1. Clarify requirements and scope

    An ETL (Extract, Transform, Load) pipeline is an automated system that reads raw data from external sources, cleans it into a consistent format, and loads it into a central analytics database. Here, 25,000 CSV files per day is a modest volume of bytes (~50 GB), so raw bandwidth is not the hard problem. The real challenge is coordinating thousands of small, untrusted files from hundreds of independent suppliers: files arrive late, get uploaded twice, get resent with corrections, change column names without warning, or contain broken rows, and the pipeline must make a safe, auditable decision on every single file.

    Functional requirements

    • Ingest raw CSV uploads placed by vendors into a cloud object storage bucket (Amazon S3).
    • Standardize schemas across vendors by mapping inconsistent column headers, character encodings, delimiters, number formats, and date representations onto one canonical warehouse table.
    • Isolate bad data by quarantining invalid rows (and rejecting severely broken files) without crashing or blocking healthy files.
    • Guarantee idempotency — meaning that processing an identical file a second time produces the exact same warehouse state as processing it once, with zero duplicate rows.
    • Load clean records into a cloud analytics warehouse (Snowflake or BigQuery) for business reporting.

    Non-functional requirements

    • Throughput SLA: Complete ingestion of all 25,000 daily files under a strict 4-hour deadline.
    • Observability: Track every file's lifecycle state (Pending, Success, Failed), row counts, and failure reason.
    • Data quality and alerting: Notify data engineering on validation failures without flooding engineers with thousands of repetitive messages.
    • Lineage: Trace every warehouse row back to the exact raw file and physical line number it came from.

    Assumptions to confirm with the interviewer

    • Supplier count and file sizes: ~1,500 active wholesale vendors; file sizes range from 1 KB to 1 GB, with a median of ~200 KB and a mean of ~2 MB.
    • Arrival pattern: Most files land overnight, so we size for the worst case where all 25,000 files sit waiting when the 4-hour window starts.
    • Snapshot vs. incremental: Most feeds send one full daily snapshot per supplier, per feed, per business date (for example, catalog_20261202.csv). A corrected file for the same supplier, feed, and business date replaces the earlier file for that day.
    • Partial-failure rule: If up to 2% of a file's rows are malformed (configurable per supplier), quarantine the bad rows and load the good ones; if more than 2% are bad, reject the entire file so broken partial totals never reach dashboards.
  2. Back-of-the-envelope numbers

    Before choosing tools, estimate where time and resources actually go.

    Daily data volume
      files per day           25,000 files
      total raw bytes         25,000 x 2 MB mean          = ~50 GB/day
      total rows              50 GB / ~200 bytes per row  = ~250M rows/day
      quarantined rows        0.5% assumed bad-row rate   = ~1.25M bad rows/day
    
    CPU and I/O work across all 25,000 files
      per-file fixed cost     S3 download, metadata DB updates, Parquet write: ~2 s/file
                              25,000 files x 2 s          = 50,000 core-s (~13.9 core-hours)
      row parsing + checks    streaming Python CSV + validation + Parquet: ~10 MB/s per core
                              50,000 MB / 10 MB/s         =  5,000 core-s (~1.4 core-hours)
      total work              50,000 + 5,000              = 55,000 core-s (~15.3 core-hours)
    
    Worker sizing for a 4-hour window (target 2 hours to keep a 2-hour retry buffer)
      minimum workers         15.3 core-hours / 2 hours   = ~8 worker processes
      provisioned workers     32 long-lived worker processes
      expected completion     55,000 s / 32 workers       = ~1,720 s (~29 minutes)
      largest single file     1,000 MB / 10 MB/s          = ~100 s (< 2 minutes)
    
    Why naive per-file designs fail the 4-hour SLA
      1 container per file    25,000 cold starts x 10 s   = ~70 core-hours wasted on startup alone
      1 warehouse MERGE/file  25,000 sequential DMLs x 2s = ~14 hours (warehouses serialize or
                              tightly cap concurrent DELETE/MERGE statements on one target table)
    
    Metadata database load
      25,000 files x ~6 status updates each = ~150,000 tiny writes/day (< 2 writes/s average)
    

    What these numbers tell us: Fixed per-file overhead (~13.9 core-hours) is ten times larger than actual CSV parsing (~1.4 core-hours). Therefore, two architectural rules drive the entire design: 1. Use long-lived workers that loop over hundreds of files while reusing database and S3 connections, rather than spinning up a container or orchestrator task per file. 2. Load the warehouse in micro-batches (grouping thousands of staged files into one warehouse transaction every 15 minutes) rather than running one COPY or MERGE per file.

  3. Interfaces: landing contract, supplier mappings, status, and replay

    Even though an ETL pipeline is not a consumer web app, four explicit contracts keep suppliers, analysts, and data engineers aligned.

    1. Supplier landing contract in S3

    s3://company-raw-ingest/supplier=<supplier_id>/<original_file_name>
      - uploaded via an SFTP-to-S3 gateway or a supplier-specific pre-signed URL
      - S3 objects appear atomically only after upload completes, so workers never read half-written files;
        zero-byte objects and temporary suffixes (.tmp, .part) are ignored during discovery
      - S3 bucket versioning + object lock prevent raw files from ever being overwritten or deleted
    

    Bucket versioning keeps every historical upload of a key under a distinct version_id, and object lock enforces write-once immutability so raw supplier evidence can never be altered by a human mistake or a pipeline bug.

    2. Declarative supplier mapping (versioned YAML in Git)

    Each supplier's quirks live in a small configuration file reviewed in Git and synced into the metadata database on merge — never scattered as if supplier == "V104" branches in Python code:

    supplier_id: V104
    version: 3
    file_pattern: "catalog_{date:%Y%m%d}.csv"     # extracts feed = "catalog" and business_date
    encoding: cp1252
    delimiter: ";"
    decimal_separator: ","
    date_format: "%d/%m/%Y"
    columns:                                      # canonical_column <- accepted supplier header aliases
      product_code:  ["sku", "item code", "article no"]
      product_name:  ["description", "item"]
      delivery_date: ["delivery date", "date"]
      quantity:      ["qty", "quantity"]
      unit_price:    ["price", "unit price (eur)"]
    required: [product_code, delivery_date, quantity, unit_price]
    max_bad_row_rate: 0.02
    

    3. Observability and operator replay endpoints

    Read status (for operators and BI dashboards):
      GET  /ops/files?supplier=V104&business_date=2026-12-02&status=FAILED
      GET  /ops/files/{file_id}      -> state history, error code, row counts, 20 sample quarantined rows
      VIEW ops.file_status           -> warehouse mirror exposing Pending, Success, Failed
    
    Replay commands (after fixing a mapping or running a backfill):
      POST /ops/files/{file_id}/replay
      POST /ops/suppliers/{supplier_id}/replay?from=2026-11-01&to=2026-11-30
    

    Internally we track granular states (PENDING -> PROCESSING -> STAGED -> SUCCESS, plus DUPLICATE, SUPERSEDED, and FAILED), which map cleanly onto the three required business statuses: - Pending: PENDING, PROCESSING, STAGED - Success: SUCCESS, DUPLICATE (identical content already loaded), SUPERSEDED (replaced by a newer file for the same day) - Failed: FAILED

  4. Data model and immutable storage layers

    Following the staging-area pattern, we separate storage into immutable layers (write-once zones where files are never edited in place) so any downstream table can always be rebuilt from raw files:

    Layer 1: Raw (S3)         s3://company-raw-ingest/supplier=<id>/<filename>
                              Exact bytes as delivered by the supplier; never modified.
    
    Layer 2: Staged (S3)      s3://company-staged/supplier=<id>/dt=<date>/file_id=<id>/attempt=<n>/part.parquet
                              Standardized column names and types stored as Apache Parquet.
    
    Layer 3: Quarantine (S3)  s3://company-quarantine/supplier=<id>/dt=<date>/file_id=<id>/attempt=<n>/bad.jsonl
                              Dead-letter log of rejected rows with line numbers, raw values, and error codes.
    
    Layer 4: Warehouse        stage.supplier_rows     transient landing table for one 15-minute micro-batch
                              core.supplier_records   canonical table (one row per valid supplier row)
                              ops.quarantined_rows    queryable mirror of all bad rows for analysts
                              marts.*                 curated views read by business dashboards
    

    Apache Parquet is a compressed, column-oriented binary file format that stores explicit data types and loads into Snowflake or BigQuery an order of magnitude faster and more safely than text CSVs.

    Metadata database (PostgreSQL) serves as both the system of record for file status and the work queue. A SHA-256 checksum (a 64-character cryptographic hash computed over the file's raw bytes) lets us detect identical file content even when a supplier re-uploads it under a different file name:

    CREATE TABLE ingest_file (
        file_id          BIGSERIAL PRIMARY KEY,
        bucket           TEXT NOT NULL,
        object_key       TEXT NOT NULL,
        version_id       TEXT NOT NULL,
        supplier_id      TEXT NOT NULL,
        feed             TEXT,
        business_date    DATE,
        size_bytes       BIGINT NOT NULL,
        sha256           TEXT,                 -- computed while streaming download from S3
        status           TEXT NOT NULL,        -- PENDING, PROCESSING, STAGED, SUCCESS, FAILED, DUPLICATE, SUPERSEDED
        attempts         INT NOT NULL DEFAULT 0,
        worker_id        TEXT,
        lease_until      TIMESTAMPTZ,
        mapping_version  INT,
        rows_total       BIGINT,
        rows_good        BIGINT,
        rows_bad         BIGINT,
        error_code       TEXT,
        error_detail     TEXT,
        replaces_file_id BIGINT,
        load_batch_id    BIGINT,
        received_at      TIMESTAMPTZ NOT NULL,
        updated_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
        UNIQUE (bucket, object_key, version_id)
    );
    
    -- Allow at most one staged/loaded copy of identical bytes under the same mapping for a given day
    CREATE UNIQUE INDEX one_load_per_content
        ON ingest_file (supplier_id, feed, business_date, sha256, mapping_version)
        WHERE status IN ('STAGED', 'SUCCESS');
    

    Including mapping_version in one_load_per_content ensures that an accidental re-upload under the same mapping is skipped as DUPLICATE, while an intentional operator replay after updating a supplier's mapping to version v+1 is allowed through.

    Canonical warehouse table (core.supplier_records):

    CREATE TABLE core.supplier_records (
        supplier_id        STRING NOT NULL,
        product_code       STRING NOT NULL,
        product_name       STRING,
        delivery_date      DATE NOT NULL,
        quantity           NUMERIC(18, 3) NOT NULL,
        unit_price         NUMERIC(18, 4) NOT NULL,
        extra              VARIANT,        -- JSON map of unmapped columns (JSON type in BigQuery)
        source_file_id     NUMBER NOT NULL,
        source_row_number  NUMBER NOT NULL,
        mapping_version    NUMBER NOT NULL,
        loaded_at          TIMESTAMP NOT NULL
    );
    
  5. High-level architecture and orchestration

    An orchestrator such as Apache Airflow (or Prefect) manages schedules, task dependencies, retries, and SLA checks, while long-lived workers handle per-file streaming.

     Suppliers (SFTP gateway / pre-signed HTTPS upload)
            |
            v
     [ S3 Raw Bucket (versioned, object-locked) ]
            |
            |  S3 ObjectCreated events -> SQS queue (plus periodic S3 list reconciliation)
            v
     [ Airflow DAG: supplier_csv_ingest (runs every 15 min, max_active_runs = 1) ]
       |
       |-- 1. discover_files      drain SQS / list new S3 versions -> INSERT INTO ingest_file (PENDING)
       |-- 2. process_shard[0..31] 32 long-lived K8s worker pods loop for up to 12 min claiming files
       |-- 3. load_warehouse      1 micro-batch transaction: COPY staged Parquet -> DELETE old + INSERT new
       |-- 4. quality_checks      verify row-count reconciliation, key uniqueness, and volume anomalies
       '-- 5. report_and_alert    mark exhausted retries FAILED, send grouped alerts, check 4h SLA pace
            |
            v
     +--------------------+      claim / update      +-----------------------------+
     | PostgreSQL Meta DB | <----------------------> | 32 Python Worker Processes  |
     | ingest_file queue  |                          | stream CSV -> validate rows |
     | supplier_mapping   |                          +--------------+--------------+
     +--------------------+                                         |
                                               +--------------------+--------------------+
                                               |                                         |
                                               v                                         v
                                  [ S3 Staged (Parquet) ]                 [ S3 Quarantine (JSONL) ]
                                               |                                         |
                                               +--------------------+--------------------+
                                                                    |
                                                                    v
                                  [ Cloud Warehouse: stage -> core.supplier_records & ops.quarantined_rows ]
                                                                    |
                                                                    v
                                  [ dbt Mart Views (with schema contracts) -> BI Dashboards ]
    

    Why Airflow schedules 32 worker shards instead of 25,000 individual tasks: Creating one Airflow task per CSV file would spawn 25,000 task instances daily, exceeding Airflow's default max_map_length of 1,024 and spending more time scheduling tasks than parsing CSVs. Instead, Airflow launches up to 32 worker shards per 15-minute cycle. Each worker loops for up to 12 minutes, claiming one file at a time from PostgreSQL using FOR UPDATE SKIP LOCKED — a SQL row-locking clause that lets 32 workers pop different rows from the same table concurrently without blocking one another or needing a separate queue:

    UPDATE ingest_file
    SET status = 'PROCESSING',
        worker_id = %(worker_id)s,
        attempts = attempts + 1,
        lease_until = now() + interval '15 minutes',
        updated_at = now()
    WHERE file_id = (
        SELECT file_id
        FROM ingest_file
        WHERE (status = 'PENDING' OR (status = 'PROCESSING' AND lease_until < now()))
          AND attempts < 3
        ORDER BY size_bytes DESC
        LIMIT 1
        FOR UPDATE SKIP LOCKED
    )
    RETURNING file_id, bucket, object_key, version_id, supplier_id, attempts;
    

    Two details in this query prevent subtle operational failures: - ORDER BY size_bytes DESC processes the 1 GB files first so a giant file never starts at minute 238 and blows the deadline. - lease_until is a lease (a temporary time-bounded lock): a healthy worker renews its lease every 60 seconds, while a crashed worker's lease expires after 15 minutes so another worker automatically takes over.

  6. Deep dive 1: End-to-end idempotency and micro-batch replacement

    Duplicate data can enter an ETL pipeline in four distinct ways, so we pair each cause with an explicit safeguard:

    Duplicate scenario                              How the pipeline prevents duplicate rows
    ----------------------------------------------  --------------------------------------------------------
    1. Same S3 upload event delivered twice         UNIQUE (bucket, object_key, version_id) makes INSERT a no-op
    2. Worker crashes mid-file or task retries      Warehouse load deletes by source_file_id before inserting
    3. Identical file re-uploaded as new S3 version Partial unique index on (supplier, feed, date, sha256, map_v)
                                                    marks the second upload DUPLICATE before warehouse load
    4. Corrected file resent for same business day  Micro-batch deletes prior file_ids for (supplier, feed, date)
                                                    in the same transaction and marks old file SUPERSEDED
    

    Notice why the SHA-256 deduplication check is scoped to (supplier_id, feed, business_date) rather than across all dates: if a vendor's catalog does not change between December 1 and December 2, catalog_20261202.csv has the exact same bytes as catalog_20261201.csv, and scoping by business_date ensures December 2 still loads normally.

    Tracing one file through a worker and the micro-batch loader:

    Worker claims file_id = 904 (attempt = 1, worker_id = "w-07"):
      1. Stream S3 object to local disk while computing sha256 on the fly.
      2. Parse file_pattern -> feed = "catalog", business_date = 2026-12-02; fetch active mapping v3.
      3. Check if (V104, "catalog", 2026-12-02, sha256, 3) is already STAGED or SUCCESS -> if so, mark DUPLICATE.
      4. Stream CSV rows -> write clean rows to .../file_id=904/attempt=1/part.parquet
                            write bad rows   to .../file_id=904/attempt=1/bad.jsonl
      5. Fence-checked status update:
           UPDATE ingest_file SET status = 'STAGED', sha256 = ..., rows_good = ...
           WHERE file_id = 904 AND worker_id = 'w-07' AND status = 'PROCESSING';
         (If 0 rows update, w-07 stalled past its lease and another worker took over; w-07 discards its work.)
    
    Micro-batch loader (single-threaded via max_active_runs = 1):
      1. Select all STAGED files; if two STAGED files share (supplier, feed, business_date), keep only the
         most recently received one and mark older ones SUPERSEDED immediately.
      2. Build stage.batch_deletes containing each chosen file_id PLUS every older file_id ever recorded for
         the same (supplier_id, feed, business_date).
      3. TRUNCATE stage.supplier_rows; COPY INTO stage.supplier_rows FROM the chosen attempt=<n> Parquet paths.
      4. Run ONE atomic warehouse transaction:
           BEGIN;
           DELETE FROM core.supplier_records
            WHERE source_file_id IN (SELECT file_id FROM stage.batch_deletes WHERE batch_id = 8812);
           INSERT INTO core.supplier_records (...)
           SELECT ..., CURRENT_TIMESTAMP FROM stage.supplier_rows WHERE batch_id = 8812;
           COMMIT;
      5. Update ingest_file in Postgres: chosen files -> SUCCESS, replaced prior files -> SUPERSEDED.
    

    Why this survives crashes at every line: If the process crashes after step 4 (COMMIT in Snowflake/BigQuery) but before step 5 (updating Postgres), the files remain STAGED in Postgres. On the next 15-minute run, step 3 truncates and reloads stage.supplier_rows (clearing Snowflake's default 64-day COPY INTO file-skip history so the Parquet files are not silently skipped), and step 4 deletes source_file_id = 904's rows and re-inserts the exact same rows.

    (Note for incremental feeds: if a specific supplier sends row-level change logs rather than full daily snapshots, configure that feed as load_mode: merge to deduplicate the micro-batch by (supplier_id, product_code, delivery_date) keeping the newest received_at, and run one MERGE per batch instead of replacing the whole day's file.)

  7. Deep dive 2: Schema standardization and schema evolution

    1. Map headers by normalized name, never by column position. Suppliers routinely reorder columns or add invisible characters like a UTF-8 BOM (Byte Order Mark) (\ufeff) at byte 0. We normalize header text and separate known canonical columns from unknown extra columns:

    from datetime import datetime
    from decimal import Decimal, InvalidOperation
    
    
    class FileRejected(Exception):
        """Raised when a whole file must fail validation rather than quarantining individual rows."""
    
        def __init__(self, error_code: str, detail: str):
            super().__init__(f"{error_code}: {detail}")
            self.error_code = error_code
            self.detail = detail
    
    
    def normalize_header(raw_name: str) -> str:
        # Strip UTF-8 BOM and surrounding spaces, lowercase, and unify punctuation into single spaces
        cleaned = raw_name.replace("\ufeff", "").strip().lower()
        for separator in "_-./":
            cleaned = cleaned.replace(separator, " ")
        return " ".join(cleaned.split())
    
    
    def map_headers(headers: list[str], mapping: dict) -> tuple[dict[str, int], dict[str, int]]:
        """Return (known_positions, unknown_positions) mapping column names to 0-based CSV indices."""
        alias_to_canonical: dict[str, str] = {}
        for canonical_name, aliases in mapping["columns"].items():
            for alias in aliases:
                alias_to_canonical[normalize_header(alias)] = canonical_name
    
        # known_positions: {"product_code": 0, "unit_price": 3, ...}
        known_positions: dict[str, int] = {}
        # unknown_positions: {"origin_region": 5, ...} preserved into the warehouse `extra` JSON column
        unknown_positions: dict[str, int] = {}
    
        for col_index, raw_header in enumerate(headers):
            normalized = normalize_header(raw_header)
            canonical_name = alias_to_canonical.get(normalized)
            if canonical_name is None:
                unknown_positions[normalized or f"col_{col_index}"] = col_index
            elif canonical_name in known_positions:
                raise FileRejected("DUPLICATE_COLUMN", canonical_name)
            else:
                known_positions[canonical_name] = col_index
    
        for required_col in mapping["required"]:
            if required_col not in known_positions:
                raise FileRejected("MISSING_COLUMN", required_col)
    
        return known_positions, unknown_positions
    

    2. Parse dates and decimals explicitly — never guess per row or strip punctuation blindly. A date like "03/04/2026" means April 3 in %d/%m/%Y and March 4 in %m/%d/%Y; guessing row by row turns half a file into the wrong month. Likewise, naively stripping "." when decimal_separator == "," would silently turn a US-formatted "12.50" into "1250" (inflating prices 100x!). Instead, we validate thousands-separator grouping rules strictly and convert currency into exact Decimal values rather than binary float:

    CANDIDATE_DATE_FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%m/%d/%Y", "%d.%m.%Y", "%Y%m%d"]
    
    
    def parse_date(text: str, date_format: str):
        try:
            return datetime.strptime(text.strip(), date_format).date()
        except ValueError:
            return None
    
    
    def parse_decimal(text: str, decimal_separator: str):
        """Parse localized numbers safely without turning '12.50' under comma-decimal into 1250."""
        cleaned = text.strip().replace(" ", "")
        if not cleaned:
            return None
    
        sign = ""
        if cleaned[0] in "+-":
            sign, cleaned = cleaned[0], cleaned[1:]
    
        thousands_separator = "." if decimal_separator == "," else ","
        parts = cleaned.split(decimal_separator)
        if len(parts) > 2:
            return None
    
        integer_part = parts[0]
        fraction_part = parts[1] if len(parts) == 2 else None
    
        # Thousands separators may never appear in the fractional digits
        if fraction_part is not None and (thousands_separator in fraction_part or not fraction_part.isdigit()):
            return None
    
        # If thousands separators are used (e.g. "1.234,50"), every group after the first must have 3 digits
        if thousands_separator in integer_part:
            groups = integer_part.split(thousands_separator)
            first_group_ok = 1 <= len(groups[0]) <= 3 and groups[0].isdigit()
            later_groups_ok = all(len(group) == 3 and group.isdigit() for group in groups[1:])
            if not (first_group_ok and later_groups_ok):
                return None
            integer_part = "".join(groups)
        elif not integer_part.isdigit():
            return None
    
        normalized_number = f"{sign}{integer_part}" + (f".{fraction_part}" if fraction_part is not None else "")
        try:
            value = Decimal(normalized_number)
        except InvalidOperation:
            return None
        return value if value.is_finite() else None
    

    3. Evolving supplier schemas safely (for example, unannounced extra columns): We store a hash of each file's normalized header list (header_fingerprint) so every change is detected automatically:

    Supplier change                Pipeline behavior
    -----------------------------  ----------------------------------------------------------------------
    Columns reordered              Loads seamlessly because map_headers resolves by normalized name.
    New column added               Loads seamlessly! Extra values go into `extra` JSON (`{"origin_region": "EU"}`)
                                   so zero data is lost, and a low-priority "schema drift" ticket opens.
                                   If analysts later want it as a first-class column, add a nullable column
                                   to core.supplier_records, bump mapping_version, and backfill from `extra`.
    Required column renamed/gone   Fails immediately with MISSING_COLUMN; fix = add the new alias in YAML
                                   (no code deploy) and call POST /ops/files/{file_id}/replay.
    Silent date-order flip         Caught by a plausibility window: delivery_date must fall within +-7 days
    (e.g. DD/MM -> MM/DD)          of business_date. Swapping day and month shifts any non-identical date by
                                   at least 27 days (e.g. Feb 3 <-> Mar 2), pushing it outside +-7 days.
    
  8. Deep dive 3: Malformed rows, quarantine (dead-letter queue), and alerting

    A dead-letter queue (DLQ) (here implemented as our quarantine S3 bucket plus ops.quarantined_rows) is a dedicated holding area where malformed records are stored alongside their raw input and failure reason so engineers can inspect or replay them without halting healthy traffic.

    We split errors into row-level (quarantine the bad row and keep streaming) vs. file-level (abort and mark the file FAILED):

    import csv
    from datetime import date, timedelta
    
    
    def standardize_row(
        fields: list[str],
        known_positions: dict[str, int],
        unknown_positions: dict[str, int],
        expected_col_count: int,
        business_date: date,
        mapping: dict,
    ):
        """Return (clean_record, None) for valid rows, or (None, (error_code, detail)) for bad rows."""
        if len(fields) != expected_col_count:
            return None, ("WRONG_COLUMN_COUNT", f"expected {expected_col_count}, got {len(fields)}")
    
        record = {col: fields[idx].strip() for col, idx in known_positions.items()}
        for required_col in mapping["required"]:
            if record[required_col] == "":
                return None, ("MISSING_VALUE", required_col)
    
        parsed_date = parse_date(record["delivery_date"], mapping["date_format"])
        if parsed_date is None:
            return None, ("BAD_DATE", record["delivery_date"])
        if abs((parsed_date - business_date).days) > mapping.get("max_date_offset_days", 13):
            return None, ("IMPLAUSIBLE_DATE", f"{parsed_date} vs business_date {business_date}")
        record["delivery_date"] = parsed_date
    
        for numeric_col in ("quantity", "unit_price"):
            parsed_num = parse_decimal(record[numeric_col], mapping["decimal_separator"])
            if parsed_num is None:
                return None, ("BAD_NUMBER", f"{numeric_col}={record[numeric_col]!r}")
            record[numeric_col] = parsed_num
    
        if record["unit_price"] <= 0:
            return None, ("OUT_OF_RANGE", f"unit_price={record['unit_price']}")
    
        # Preserve any unmapped columns in `extra` so additive supplier changes never lose data
        record["extra"] = {col: fields[idx].strip() for col, idx in unknown_positions.items()}
        return record, None
    
    
    def process_file(text_lines, business_date: date, mapping: dict, good_sink, bad_sink) -> dict:
        """Stream one CSV file into good_sink (Parquet writer) and bad_sink (quarantine JSONL writer)."""
        reader = csv.reader(text_lines, delimiter=mapping["delimiter"])
        try:
            headers = next(reader)
        except StopIteration:
            raise FileRejected("EMPTY_FILE", "file has zero lines")
    
        known_positions, unknown_positions = map_headers(headers, mapping)
        prev_line_num = reader.line_num
        seen_keys: set[tuple[str, date]] = set()
        good_count = 0
        bad_count = 0
    
        try:
            for fields in reader:
                start_line = prev_line_num + 1
                lines_consumed = reader.line_num - prev_line_num
                prev_line_num = reader.line_num
    
                # Stray-quote guard: an unmatched `"` swallows newlines and merges dozens of rows into one
                if lines_consumed > 1 and not mapping.get("allow_multiline_fields", False):
                    raise FileRejected("STRAY_QUOTE_MULTILINE", f"record starting at line {start_line}")
    
                if not fields or all(cell.strip() == "" for cell in fields):
                    continue
    
                record, error = standardize_row(
                    fields, known_positions, unknown_positions, len(headers), business_date, mapping
                )
                if error is None:
                    business_key = (record["product_code"], record["delivery_date"])
                    if business_key in seen_keys:
                        error = ("DUPLICATE_KEY_IN_FILE", f"{business_key[0]} on {business_key[1]}")
                    else:
                        seen_keys.add(business_key)
    
                if error is None:
                    record["source_row_number"] = start_line
                    good_sink.append(record)
                    good_count += 1
                else:
                    bad_sink.append({
                        "line_number": start_line,
                        "raw_fields": fields,
                        "error_code": error[0],
                        "detail": error[1],
                    })
                    bad_count += 1
        except csv.Error as exc:
            raise FileRejected("MALFORMED_CSV", f"near line {reader.line_num}: {exc}")
    
        total_rows = good_count + bad_count
        if total_rows > 0 and (bad_count / total_rows) > mapping["max_bad_row_rate"]:
            raise FileRejected("TOO_MANY_BAD_ROWS", f"{bad_count}/{total_rows} rows failed validation")
    
        return {
            "rows_total": total_rows,
            "rows_good": good_count,
            "rows_bad": bad_count,
            "unknown_headers": sorted(unknown_positions.keys()),
        }
    

    Why the stray-quote guard matters: In standard CSV parsers, a single unmatched " at the start of a field causes the parser to swallow newlines and merge hundreds of subsequent rows into one giant "field" without raising an error, silently hiding missing rows inside a single quarantined record. Checking lines_consumed > 1 catches an unclosed quote on the exact line it began.

    Alerting without alert fatigue: - Deduplicate by (supplier_id, error_code) per 15-minute run: Send one summary alert ("Supplier V104: 37 files failed MISSING_COLUMN 'quantity' — mapping v3 — [Replay link]") instead of 37 separate alerts. - Page on-call only when the 4-hour SLA or global health is at risk: Project completion time using both remaining files and remaining bytes (now + (pending_files * sec_per_file + pending_bytes / mb_per_sec) / active_workers), because largest-first scheduling leaves thousands of tiny files at the tail where fixed per-file overhead dominates. - Alert on missing files too: Compare received files against each supplier's expected delivery schedule at cut-off time so a silent SFTP outage never goes unnoticed.

  9. Scaling, failure handling, and trade-offs

    Failure modes and recovery

    Failure scenario                        How the system recovers automatically
    --------------------------------------  --------------------------------------------------------------
    Worker pod crashes mid-file             15-minute lease expires; another worker claims the file and
                                            writes to attempt=<n+1>; worker_id fence blocks stale writes.
    Warehouse load crashes after COMMIT     Files are still STAGED in Postgres; next batch re-runs atomic
                                            DELETE + INSERT by source_file_id -> identical final state.
    Poison file (OOM / corrupt binary)      Streaming keeps memory flat; after 3 failed attempts, report
                                            step marks it FAILED (RETRIES_EXHAUSTED) so workers move on.
    Warehouse slow or down                  Workers keep staging Parquet in S3; micro-batch loader retries
                                            with backoff and fires SLA-pace alert before 4h window expires.
    Bad supplier mapping deployed           Roll back YAML in Git to prior mapping_version and hit the
                                            supplier replay endpoint; immutable raw S3 files need no resend.
    

    Scaling to 10x (250,000 files/day, ~500 GB/day): - Increase worker pods from 32 to ~80 (still finishing within 2 hours); Airflow's scheduler load barely changes because tasks map over worker shards, not individual files. - Switch discovery completely to event-driven SQS messages from S3 so workers process files continuously overnight rather than waiting for a batch cut-off. - If a single supplier ever uploads a 20 GB CSV, split byte ranges on newline boundaries (after verifying allow_multiline_fields is false) or route >2 GB files to a high-throughput Rust/Polars worker pool.

    Summary of architectural trade-offs - Immutable raw + staged Parquet layers vs. in-flight streaming directly to the warehouse: Costs ~50 GB/day of cheap S3 storage, in exchange for instant replayability whenever a supplier mapping has a bug. - Long-lived worker shards + Postgres SKIP LOCKED vs. one Airflow task per file: Moves per-file retry UI from Airflow into the ingest_file table, eliminating 25,000 task cold-starts and scheduler bottlenecks. - 15-minute warehouse micro-batches vs. per-file MERGEs: Adds ~15 minutes of warehouse landing latency (well inside the 4-hour SLA) while avoiding warehouse DML lock contention completely. - Configurable bad-row rate threshold (2%) vs. loading whatever parses: Holds back severely broken files temporarily so downstream financial and inventory dashboards never display silently incomplete totals.

Intuition & how it works

Imagine running the receiving dock of a central food distributor where 1,500 independent farms drop off 25,000 paper delivery manifests every night, each using different column labels, date styles, and currencies. Instead of letting delivery drivers scribble directly onto your master inventory ledger, you photocopy every manifest into a locked filing cabinet (immutable raw storage, meaning files are written once and never altered), assign 32 clerks to copy clean lines onto standardized forms (Apache Parquet, a compressed column-oriented file format built for fast analytics) while placing smudged lines into an inspection tray (a dead-letter queue or quarantine, a holding area for rejected records and their error reasons), and wheel completed pallets into the main ledger room every 15 minutes (micro-batching, grouping thousands of small updates into one efficient database transaction).

A naive pipeline that launches one fresh container per file and runs one warehouse MERGE statement per file collapses under per-file overhead: 25,000 container cold starts and 25,000 serialized warehouse locks take over 14 hours even though the actual CSV data is only ~50 GB. Worse, reading CSV columns by position, guessing date formats row by row, or blindly appending rows means a single column reorder or network retry silently corrupts prices or doubles inventory totals.

Walk through how our pipeline handles four files from two vendors during one 15-minute cycle:

Event 1: Vendor V104 uploads catalog_20261202.csv (1,000 rows, 3 negative prices, 1 new "origin_region" column)
  -> Worker computes its SHA-256 checksum (a 64-character cryptographic fingerprint of the exact bytes),
     maps headers by normalized name, puts "origin_region" into the `extra` JSON column, writes 997 clean
     rows to staged Parquet, and sends the 3 negative-price rows to quarantine (0.3% <= 2% limit).
  -> Micro-batch #1 loads the 997 rows into core.supplier_records and marks file_id 101 SUCCESS.

Event 2: V104's script accidentally uploads the exact same file again 4 minutes later
  -> Worker computes the same SHA-256 for (V104, "catalog", 2026-12-02, mapping v3) -> marks file_id 102
     DUPLICATE immediately without touching the warehouse (**idempotency**: running twice never duplicates rows).

Event 3: V104 uploads a corrected catalog_20261202.csv fixing the 3 negative prices (new SHA-256)
  -> Worker stages all 1,000 clean rows under file_id 103.
  -> Micro-batch #2 runs ONE atomic warehouse transaction: DELETE rows where source_file_id = 101,
     INSERT file_id 103's 1,000 rows, mark 103 SUCCESS, and mark 101 SUPERSEDED.

Event 4: Vendor V275 renames required column "price" to "wholesale_rate" across 12 files
  -> All 12 files fail header validation (`MISSING_COLUMN`), stage zero rows, and trigger ONE grouped
     alert ("V275: 12 files MISSING_COLUMN 'unit_price'") with a one-click replay link once YAML is updated.

Key trade-offs

  • Immutable raw + staged Parquet layers vs. transforming in flight. Keeping raw CSVs and staged Parquet files in S3 adds ~50 GB/day of object storage and one extra write step. In exchange, whenever a supplier mapping has a bug, engineers can fix the YAML configuration and replay historical files directly from raw S3 without asking suppliers to resend anything.
  • Orchestrating 32 long-lived worker shards vs. one orchestrator task per file. Scheduling one Airflow task per file gives per-file retry buttons in the Airflow UI, but 25,000 daily task instances overwhelm the scheduler, exceed Airflow's default 1,024 mapped-task cap, and burn hours on container startup. Long-lived shards that pull work from PostgreSQL keep orchestration tiny while storing per-file status and retry history in ingest_file.
  • PostgreSQL FOR UPDATE SKIP LOCKED queue vs. a separate message broker. FOR UPDATE SKIP LOCKED is a SQL locking clause that lets concurrent workers claim distinct rows without waiting on each other, keeping the work queue and file status in a single ACID table that can never drift out of sync. A dedicated broker like Kafka scales to millions of messages per second, which is unnecessary complexity for 25,000 files per day (~150,000 tiny status writes/day).
  • 15-minute micro-batch DELETE + INSERT loads vs. per-file warehouse MERGEs. Grouping thousands of staged files into one warehouse transaction avoids warehouse lock contention and guarantees idempotency by source_file_id. The trade-off is ~15 minutes of landing latency, which easily fits inside a 4-hour SLA.
  • Per-supplier bad-row threshold (default 2%) vs. loading every valid row unconditionally. Rejecting a file when more than 2% of its rows fail validation delays that supplier's update until someone investigates, but prevents a half-corrupted file from displaying plausible-looking yet 40%-too-low revenue totals on executive dashboards.
  • Preserving unknown columns in an extra JSON column vs. failing on any unknown header. Storing unexpected columns in extra keeps the pipeline running when a supplier adds a harmless new column while still capturing the raw values for later backfill; missing or renamed required columns still fail immediately so core metrics are never null or misaligned.

Common mistakes

  • Mapping CSV columns by index (row[0], row[1]), which silently loads quantities into price columns the day a supplier reorders their export.
  • Inferring date formats row by row or stripping number punctuation blindly, turning "03/04/2026" into March on one row and April on another, or turning "12.50" under a comma-decimal config into 1250 (a 100x price error).
  • Using the file name alone as the idempotency key, which both fails to catch identical bytes uploaded under a new name and wrongly ignores a corrected resend uploaded under the original name.
  • Using APPEND-only warehouse loads, so every worker retry, crash recovery, or operator replay duplicates rows in analytics tables.
  • Ignoring the CSV stray-quote trap, where one unclosed " causes the parser to swallow newlines and silently merge hundreds of valid rows into a single quarantined row.
  • Launching one container or running one warehouse MERGE per file, spending 10x more time on cold starts and warehouse lock queues than on actual data processing.
  • Sending one Slack/PagerDuty alert per failed file (flooding channels so engineers mute notifications) while failing to alert when an expected supplier file never arrives at all.

Follow-up questions

  • What safeguards and recovery steps would you use if an upstream schema shift breaks BI dashboards? First, isolate dashboards from raw ingestion tables by having BI tools query curated marts.* views governed by dbt model contracts (automated build checks that enforce exact column names, data types, and nullability before any view change deploys), and allow only additive changes on core.supplier_records. Run a CI check on every mapping or SQL change against recent staged Parquet data to block breaking changes before merge. If bad data or a broken schema still reaches production, immediately repoint the mart view to its prior working version, query source_file_id and mapping_version to delete and replay the affected loads from immutable raw S3, notify downstream owners listed in lineage metadata, and add a regression test for that exact failure mode.
  • When end-to-end ingestion duration spikes unexpectedly, which operational metrics would you inspect first to isolate the bottleneck? Decompose end-to-end time across each pipeline stage and compare against historical p50/p95 baselines: (1) Arrival & queue metrics — PENDING file count, total pending bytes, and per-supplier upload sizes (one vendor suddenly dropping a 20 GB export or 10x file count is the #1 culprit); (2) Worker sub-step timings — S3 download time, CSV parse/validate throughput (MB/s), Parquet write time, and Postgres lease/update latency; (3) Retry & poison-file rates — counts of expired leases or OOM restarts; and (4) Warehouse micro-batch metrics — COPY INTO duration, DELETE/INSERT lock-wait time, and warehouse slot/queue wait time. By Little's law (a queueing rule stating that average queue length equals arrival rate multiplied by average processing time), if arrivals are normal while PENDING backlog grows, per-stage step timings immediately pinpoint whether S3, worker CPU, Postgres locks, or warehouse queuing slowed down.
  • How would your architecture support re-ingesting a full 30-day historical resend from a vendor without starving daily traffic? Land the 30 resent files into the normal raw S3 bucket and tag their ingest_file rows with a backfill_id via the supplier replay endpoint. Any resent file whose bytes match the already-loaded file for that (supplier_id, feed, business_date, mapping_version) hits the SHA-256 check and finishes instantly as DUPLICATE with zero warehouse work, while genuinely changed days stage to Parquet and use the standard atomic DELETE + INSERT micro-batch to swap out old rows and mark superseded files SUPERSEDED. Route backfill_id claims through a lower-priority worker pool (claiming backfill files only when current-day PENDING files are zero) so the daily 4-hour SLA is never starved, then run date-scoped refreshes on downstream incremental marts and emit a day-by-day diff report comparing old vs. new row counts and totals.

Follow-up questions

Similar questions

More Natoora interview questions

All 5 Natoora questions →