Weather-Driven Power Forecasting Pipeline for Energy Trading

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect an end-to-end forecasting system for a North American power and natural gas trading desk. This is an architecture-focused design discussion centered on system diagrams, data flows, and concise pseudocode for tricky coordination logic rather than full production code.

Each morning at roughly 06:00 (the exact arrival clock drifts from day to day), an external meteorology vendor posts one CSV file at a public HTTP endpoint. Each daily payload includes:

  • 10 distinct weather ensemble scenarios;
  • a 15-day lookahead at hourly granularity (~360 hourly timestamps per scenario);
  • surface and atmospheric series including temperature, wind speed, soil moisture, cloud cover, and precipitation.

Quantitative researchers supply five containerized/black-box forecasting models. Four fundamental models consume the weather inputs directly, and their scenario outputs feed a fifth model that predicts power prices:

Hourly Weather Series
  |---> Demand Forecast Model -------+
  |---> Wind Generation Model -------+
  |---> Solar Generation Model ------+---> Electricity Price Model
  +---> Hydro Generation Model ------+

Your architecture must span the complete lifecycle—detecting and fetching the morning CSV, validating payload quality, archiving historical inputs and outputs, executing all five models across every scenario, precomputing summary views, and publishing fresh projections to a trader web dashboard as rapidly as possible once new weather data appears.

Key parameters such as CSV byte size, station count, model packaging and runtime, trader headcount, retention horizon, and whether the vendor may upload same-day revisions are intentionally open—state explicit assumptions up front.

Scope & Expectations

  • Resilient ingestion, validation, and storage: How your poller handles variable ~6 AM publication times idempotently without ingesting stale or truncated files, gates model execution behind concrete data-quality checks, and balances raw archival storage against curated analytical formats.
  • DAG structure and scenario execution: Where you draw workflow boundaries for live runs versus reruns/backfills, how you wire task dependencies across the five black-box models and 10 scenarios to minimize critical-path latency, and how you pin model versions.
  • Fault handling and atomic trader delivery: How failures are isolated, retried, or escalated at every stage, what statistical and market-block rollups are precomputed, which dashboard stack serves traders, and how updates go live atomically without exposing half-updated forecasts.
  • Scaling to large ensembles: Which architectural components bottleneck first if ensemble cardinality grows from 10 scenarios to hundreds or thousands, and how compute scheduling, storage layout, and visualization adapt.

Step-by-step walkthrough

  1. Clarify requirements and state assumptions

    Power and gas traders buy and sell electricity for future hours based heavily on weather: a summer heatwave spikes air-conditioning load (Electricity Demand), calm or cloudy skies cut Wind and Solar supply, rainfall feeds Hydro reservoirs, and together those four fundamentals drive Electricity Price. Every morning around 06:00, a vendor publishes a CSV file containing 10 possible 15-day hourly weather futures ("scenarios"), and our job is to turn that CSV into trustworthy, fast price forecasts on traders' screens.

    Because the prompt intentionally leaves scale parameters open, state clear assumptions up front so every later calculation is grounded:

    Open Question Design Assumption
    How to distinguish today's file from yesterday's The public URL serves only the latest CSV; rows include an issue_time column (when the forecast was generated). HTTP ETag / Last-Modified headers exist as a fast hint, but we always verify file contents.
    Arrival window & same-day corrections Usually lands between 05:50 and 06:30 (worst case ~2 hours late). Occasionally the vendor uploads a corrected CSV later the same morning.
    Geographic & variable shape Long format: 1 row per (scenario, location, valid_time) across ~100 US weather stations and 6 weather variables (temperature, wind_speed, soil_moisture, cloud_cover, rainfall, solar_irradiance).
    Black-box model packaging & runtime Research owns 5 containerized Python models. Scenarios are completely independent: upstream models (demand, wind, solar, hydro) take 2–5 min each on 2 vCPUs; price takes ~5 min consuming the 4 upstream outputs of the same scenario.
    Model output shape Each run outputs 360 hourly values across 7 major US power markets (PJM, ERCOT, CAISO, MISO, SPP, NYISO, ISO-NE).
    Users, target latency & existing stack ~30 traders behind company SSO; target < 20 minutes from CSV publication to live dashboard; keep all history; run on existing Airflow on Kubernetes, S3-compatible object storage, and PostgreSQL.

    Core non-functional goals

    1. Correctness over blind speed: Never run models on a half-uploaded or corrupt CSV, never show traders a half-updated mix of yesterday's and today's forecasts, and always display the exact age of every number.
    2. Full reproducibility: Every chart number traces back to one immutable raw CSV hash and exact container versions of all 5 models.
    3. Pragmatic simplicity: Size tools to the actual data volume so a small engineering team can operate it effortlessly.
  2. Back-of-the-envelope numbers

    Multiplying out rows and model runs before choosing databases immediately tells us what is easy and what is hard:

    Daily input CSV     10 scenarios x 360 hours x 100 locations = 360,000 rows/day
                        360,000 x ~80 bytes/row                  -> ~29 MB/day (~10.5 GB/year raw)
    
    Daily model runs    4 upstream models x 10 scenarios         = 40 upstream runs
                        1 price model     x 10 scenarios         = 10 price runs
                        Total runs per forecast                  = 50 container runs
    
    Model output rows   1 run = 360 hours x 7 US power regions   = 2,520 values
                        50 runs x 2,520                          = 126,000 values/day (~46M/year)
    
    Precomputed summary 5 models x 7 regions x 360 hours         = 12,600 summary rows/forecast
                        (holding mean, median, min, max, std)
    
    Peak morning CPU    40 upstream pods x 2 vCPU = 80 vCPU for ~5 min,
                        followed by 10 price pods x 2 vCPU = 20 vCPU for ~5 min
    
    End-to-end latency  Poll detection (<= 2 min) + download & validate (~1 min)
                        + pod startup (~2 min) + slowest upstream (5 min)
                        + price model (5 min) + aggregate & publish (~1 min) = ~16 minutes!
    

    What these numbers reveal:

    • Data volume at 10 scenarios is tiny. 29 MB/day of raw CSV and 12,600 summary rows/day fit comfortably inside object storage and a single PostgreSQL instance for decades — no distributed big-data cluster is needed yet.
    • Timing, validation, and atomic publishing are the real engineering challenges: catching a variable-time file without ingesting yesterday's data, wiring per-scenario dependencies without unnecessary global waits, and flipping the live dashboard cleanly.
    • Run count scales linearly with scenarios: 50 runs at 10 scenarios becomes 5,000 runs at 1,000 scenarios, showing exactly what will break first in the future.
  3. Interfaces and data model

    We need two clean boundaries: a strict CLI/container contract with the quant research team's black-box models, and a versioned Read API for the trader dashboard.

    First, define three storage and deployment terms we use here:

    • Parquet is a compressed, strongly typed columnar file format that reads and writes much faster and smaller than plain CSV.
    • A container image digest (@sha256:...) is an immutable cryptographic hash of a container build, guaranteeing the exact same Python code and library weights run every time (unlike a mutable :latest tag).
    • A forecast vintage (issue_time) is when a prediction was made, as opposed to valid_time (which future hour is being predicted).

    Black-box model container contract:

    Image:   registry.internal/models/wind@sha256:7c3d...
    Command: run --weather s3://forecasts/curated/issue=2026-08-12T06/rev=1/scenario=04.parquet
                 --out     s3://forecasts/outputs/run_set=rs_0904/model=wind/scenario=04.parquet
             (Price model additionally receives --demand, --wind, --solar, --hydro paths for scenario 04)
    Output:  Parquet file with schema (region TEXT, valid_time TIMESTAMPTZ, value DOUBLE, unit TEXT)
    Rules:   Pure deterministic function of inputs; exit code 0 on success; writes ONLY to --out.
    

    Read API (used by the web dashboard, Excel add-ins, and quant notebooks):

    GET /v1/forecasts/current
        -> {run_set_id: "rs_0904", issue_time: "2026-08-12T06:00Z", revision: 1,
            published_at: "2026-08-12T06:17Z", model_versions: {...}}
    
    GET /v1/forecasts/{run_set_id}/summary?model=price&region=ERCOT&agg=hourly|daily|on_peak
    GET /v1/forecasts/{run_set_id}/scenarios?model=price&region=ERCOT
    GET /v1/compare?model=price&region=ERCOT&valid_from=...&valid_to=...&issued=2026-08-12,2026-08-05
    GET /v1/forecasts/{run_set_id}/export.csv
    

    Notice that only /v1/forecasts/current looks up the active pointer; every panel query passes an explicit run_set_id so a dashboard page never mixes charts from two different runs!

    Storage layout (store BOTH immutable raw CSV and curated Parquet):

    Keeping the untouched raw CSV (~10.5 GB/year) proves exactly what the vendor sent and lets us re-parse history if our parser changes, while curated per-scenario Parquet files normalize units (°C, m/s, mm) so models read fast, validated inputs:

    Object Storage (S3)
      raw/issue=2026-08-12T06/sha256=4b8e....csv                      -- immutable vendor bytes
      curated/issue=2026-08-12T06/rev=1/scenario=01..10.parquet       -- cleaned, split per scenario
      outputs/run_set=rs_0904/model=demand..price/scenario=01..10.parquet
    
    PostgreSQL (append-only metadata + precomputed summaries + atomic live pointer)
      forecast_files   (file_id PK, issue_time, revision, sha256, status,
                        UNIQUE (issue_time, sha256), UNIQUE (issue_time, revision))
      validation_checks(file_id, check_name, severity: block|warn, passed, detail)
      run_sets         (run_set_id PK, file_id, model_versions JSONB, purpose: live|backfill|shadow,
                        status, created_at, finished_at)
      model_runs       (run_set_id, model, scenario, status, output_uri, PK (run_set_id, model, scenario))
      forecast_summary (run_set_id, model, region, valid_time, mean, median, min, max, std,
                        PK (run_set_id, model, region, valid_time))
      published        (view_name PK, run_set_id, published_at)       -- 'live' -> 'rs_0904'
      publish_log      (id PK, view_name, run_set_id, published_at)   -- full audit trail of what traders saw
    
  4. High-level architecture

    We orchestrate tasks using DAGs (Directed Acyclic Graphs) — workflows of tasks connected by one-way dependency arrows with no loops — running in Airflow on Kubernetes:

     Vendor Public URL (CSV published ~06:00, variable time)
            |
            |  Conditional HTTP GET every 2 min starting at 05:30
            v
     +------------------------------- Airflow on Kubernetes -------------------------------+
     |                                                                                     |
     |  DAG 1: weather_ingest                   DAG 2: forecast_models (event-triggered)   |
     |  poll_url -> validate_csv                create_run_set                             |
     |           -> write raw S3 + curated S3         |                                    |
     |           -> emit forecast_ready    =====>     +-- Scen 01: [D,W,S,H] -> Price_01 --+
     |                                                +-- Scen 02: [D,W,S,H] -> Price_02 --+
     |                                                |        ... (10 parallel chains)    |
     |                                                +-- Scen 10: [D,W,S,H] -> Price_10 --+
     |                                                                                     |
     |                                                aggregate_summaries -> flip_pointer <+
     +-------------------------------------------------------------------------------------+
            |                        |                           |                    |
            v                        v                           v                    v
     S3 Object Storage          PostgreSQL               K8s Model Pods       External Dead Man's
     (raw / curated /       (vintages, summaries,        (pinned by sha256     Switch + Pager/Slack
      scenario outputs)      atomic 'live' pointer)       container digest)
                                     |
                                     v
                         Read API (FastAPI, 2 replicas)
                            |                     |
                            v                     v
                 Dash Trader Web App      Excel / CSV / Quant Notebooks
                  (behind corp SSO)
    
  5. Deep dive 1: Ingestion, variable-time polling, and validation

    Running a naive cron job at 06:00 is a classic trap because an HTTP request at 06:00 can return four very different things:

    1. 404 or 304 Not Modified (nothing new yet),
    2. 200 OK serving yesterday's stale CSV (HTTP 200 does not mean today's forecast!),
    3. 200 OK serving a half-uploaded CSV if the vendor overwrites the file in place without atomic rename, or
    4. 200 OK serving today's complete CSV (or a same-day correction hours later).

    Polling strategy: Schedule weather_ingest at 05:30 using an Airflow deferrable sensor — a lightweight async task that releases its worker slot while sleeping between polls. It sends conditional HTTP GETs using ETag (an HTTP header fingerprint that lets the server reply 304 Not Modified with zero body bytes when unchanged) every 2 minutes until 08:30 (paging on-call if nothing arrives by 08:30), then switches to a slow 15-minute poll until 14:00 to catch same-day vendor corrections.

    def poll_forecast_once(target_date, last_etag):
        # Send If-None-Match so unchanged files return a tiny 304 response.
        resp = http_get(FORECAST_URL, if_none_match=last_etag)
        if resp.status in (304, 404):
            return "WAIT"
    
        body = resp.body
        # Guard 1: Reject truncated downloads where byte count disagrees with Content-Length.
        if resp.content_length is not None and len(body) != resp.content_length:
            return "WAIT"
    
        # Guard 2: Verify structural completeness (all 10 scenarios x 360 hours parse cleanly)
        # BEFORE accepting, in case the vendor writes the file in place on their server.
        parsed = try_parse_and_check_row_grid(body, expected_scenarios=10, expected_hours=360)
        if not parsed.is_complete:
            return "WAIT"
    
        digest = sha256_hex(body)
        issue_time = parsed.issue_time
    
        # Guard 3: Database deduplication on (issue_time, sha256) makes repeated polls idempotent.
        if db.file_hash_exists(issue_time, digest):
            return "WAIT"
    
        # Persist immutable raw CSV first, then register the new file/revision in Postgres.
        s3.put_if_absent(f"raw/issue={issue_time}/sha256={digest}.csv", body)
        file_id, inserted = db.insert_forecast_file_idempotent(issue_time, digest)
        if inserted:
            validate_and_curate(file_id, parsed)
    
        # Guard 4: Only satisfy today's morning wait once issue_time is actually for target_date!
        # (A late vendor revision to yesterday's file is safely stored above without stopping today's poll.)
        if issue_time.date() < target_date:
            return "WAIT"
        return "TODAY_READY"
    

    Two-tier data validation (gate models before any pod runs):

    • Blocking checks (halt pipeline, keep yesterday live, page data on-call):
      • Exact schema, parseable numeric/timestamp types, and zero NaN/null values in model features.
      • Exactly 10 scenarios, each with 360 consecutive hourly valid_time steps starting from issue_time, and zero duplicate (scenario, location, valid_time) keys.
      • Physical sanity bounds: temperature in [-60, +60] °C, wind speed in [0, 75] m/s, cloud cover in [0, 100]%, rainfall >= 0, soil moisture in [0, 1].
      • Silent unit-flip check: If >80% of locations shift by > 15 °C in the same direction vs. yesterday's overlapping 14 days (for example, vendor accidentally switched °C to °F, where 10 °C becomes 50 °F), block immediately!
    • Warning checks (continue pipeline, attach yellow warning badge on dashboard):
      • Single-region overnight temperature jump > 8 °C (could be a real cold front), file byte size outside ±30% of the 30-day median, or two scenarios having identical series.

    Only when all blocking checks pass does validate_and_curate write the 10 per-scenario Parquet files and emit weather_forecast_ready.

  6. Deep dive 2: DAG boundaries and per-scenario model execution

    Why split into separate DAGs instead of one big DAG?

    • weather_ingest (owned by data engineering): Talks to an flaky outside URL; retrying means polling again.
    • forecast_models (triggered by weather_forecast_ready with {file_id, model_versions, purpose}): Purely internal compute over already-stored S3 files. Separating it lets us re-run models on a vendor correction, test a new wind model on 30 past days (purpose="backfill"), or shadow-test (purpose="shadow") without touching or faking the download step!

    Wire task dependencies strictly within each scenario (avoid a global barrier!):

    Look at what price for Scenario 4 actually needs: only demand_4, wind_4, solar_4, and hydro_4 — nothing from Scenario 8! Putting a global stage barrier ("wait for all 40 upstream runs, then start all 10 price runs") forces every scenario to wait for the single slowest pod across the entire cluster. Instead, run 10 independent parallel chains that synchronize only once at aggregate_summaries:

    create_run_set (pins exact sha256 image digests in Postgres)
       |
       +-- Scenario 01: [demand_01, wind_01, solar_01, hydro_01] --> price_01 --+
       +-- Scenario 02: [demand_02, wind_02, solar_02, hydro_02] --> price_02 --+
       |       ... (dynamic task group mapped over scenarios 01..10) ...        |
       +-- Scenario 10: [demand_10, wind_10, solar_10, hydro_10] --> price_10 --+
                                                                                |
                                                                                v
                                          aggregate_summaries --> sanity_check --> publish_pointer
    
    def run_single_model_task(run_set, model_name, scenario_id, input_uris):
        # Deterministic S3 output URI makes task retries naturally idempotent.
        out_uri = f"s3://forecasts/outputs/run_set={run_set.id}/model={model_name}/scenario={scenario_id}.parquet"
        if s3.exists_and_valid_parquet(out_uri):
            return out_uri  # Already succeeded on an earlier attempt; skip recomputing!
    
        image_digest = run_set.model_versions[model_name]
        run_kubernetes_pod(
            image=image_digest,
            args=build_cli_args(input_uris, out_uri),
            cpu_request="2",
            timeout_minutes=15,
            pool=("live_morning_pool" if run_set.purpose == "live" else "backfill_low_prio_pool"),
        )
        db.upsert_model_run(run_set.id, model_name, scenario_id, status="SUCCEEDED", output_uri=out_uri)
        return out_uri
    

    Isolating live_morning_pool from backfill_low_prio_pool guarantees a researcher's 30-day historical backtest never delays the 6 AM trading run.

  7. Deep dive 3: Summary aggregation, trader dashboard, and atomic publish

    Summary metrics across the 10 ensemble members:

    Ten hourly trajectories represent an uncertainty spread across possible weather futures:

    • Hourly distribution stats (forecast_summary): Precompute mean, median, min, max, and std per (model, region, valid_time), plus expose all 10 raw scenario curves (10 lines are crisp enough to plot directly, and with only N = 10 points, min/max plus individual lines are much less arbitrary than interpolated "P10/P90" percentiles).
    • Power-market trading blocks: Power is traded in standardized strips — precompute On-Peak (e.g., weekday hours ending 07–22), Off-Peak, daily averages, and Net Load (Demand - Wind - Solar, the #1 driver of thermal power prices).
    • Overnight forecast delta ("What changed since yesterday?"): Precompute today_mean - yesterday_mean across the 14 overlapping days so traders immediately spot whether next week got hotter, windier, or pricier overnight.

    Dashboard stack & atomic live switch:

    For ~30 quantitative traders, a Plotly Dash web app (2 stateless replicas on Kubernetes behind corporate SSO) backed by our FastAPI Read API hits the sweet spot: Python-friendly for quants to add custom fan charts and forecast-diff heatmaps in hours (much more flexible than rigid BI tools like Grafana, without weeks of custom React work), paired with one-click CSV/Excel export.

    To guarantee traders never see a half-updated mix of yesterday's and today's forecasts, aggregate_summaries writes all 12,600 rows under the new run_set_id while published still points at yesterday. Then publish_pointer flips the pointer in a single microsecond SQL transaction — guarded so a slow retry of an older revision can never overwrite a newer one:

    BEGIN;
    -- Monotonic guard: only advance 'live' if the new run_set's (issue_time, revision)
    -- is strictly newer than what is currently published!
    UPDATE published p
    SET run_set_id = 'rs_0904', published_at = now()
    FROM run_sets new_rs JOIN forecast_files new_f ON new_f.file_id = new_rs.file_id,
         run_sets cur_rs JOIN forecast_files cur_f ON cur_f.file_id = cur_rs.file_id
    WHERE p.view_name = 'live'
      AND new_rs.run_set_id = 'rs_0904'
      AND cur_rs.run_set_id = p.run_set_id
      AND (new_f.issue_time, new_f.revision) > (cur_f.issue_time, cur_f.revision);
    
    INSERT INTO publish_log (view_name, run_set_id, published_at)
    VALUES ('live', 'rs_0904', now());
    COMMIT;
    
  8. Failure handling across every stage

    Tracing failure modes end to end from the external HTTP endpoint to the trading UI ensures every outage has a deterministic recovery and an honest display state:

    Stage Failure Mode Automated Recovery Who Gets Paged? What Traders See on Screen
    Vendor URL Late file (404 / yesterday's CSV) or mid-upload truncation Keep polling every 2 min until 08:30 Data on-call at 08:30 Prominent banner: "Today's forecast not yet published by vendor — showing yesterday 06:02 (Rev 1)"
    Validation Blocking check fails (missing hours, NaNs, °C/°F unit flip) Abort curate step; zero models run; yesterday stays live Data on-call immediately Red banner: "Today's 06:04 file failed validation — showing yesterday's forecast"
    Model Pods K8s spot preemption, node crash, OOM, transient timeout Retry pod up to 2x with backoff; finished sibling pods skipped via S3 check Only if all retries fail Yesterday stays live until retries finish (~5 min delay)
    Model Pods Deterministic crash inside black-box model code Fail fast after 1 retry; notify research owner Quant model on-call Keep yesterday live (or publish labeled 9/10 scenarios only if pre-approved by the trading desk)
    Airflow / Scheduler Airflow scheduler or DB hangs silently at 05:00 HA scheduler + external dead man's switch (an independent monitor outside Airflow that checks published.published_at by 07:00) Platform on-call Dashboard auto-highlights age (now - published_at) in amber/red
    Bad Forecast Post-Publish Subtle vendor error noticed at 07:15 Run 1-line rollback command pointing published back to yesterday's run_set_id Desk + Data team Banner: "06:02 forecast retracted at 07:15; reverted to prior run"
  9. Scaling to thousands of scenarios and trade-off summary

    If research expands from 10 weather scenarios to 1,000 ensemble members, re-multiplying shows 36M input rows (~2.9 GB CSV/day), 5,000 model runs/day (~19,000 container-minutes -> ~1,900 vCPUs to finish in 20 minutes), and 4.6 billion output values/year. Here is what breaks first and how we evolve each layer without changing our core architecture:

    1. 5,000 individual Airflow tasks & pod cold starts break first: Scheduling 5,000 separate pods wastes minutes on scheduler overhead and container image pulls. Fix: Group scenarios into chunks of 50 (20 chunks x 5 models = 100 tasks) using Kubernetes Indexed Jobs / AWS Batch array jobs, and ask research for a vectorized/looped batch entrypoint so each pod loads Python libraries once and evaluates 50 scenarios.
    2. Morning burst compute (~1,900 vCPU for 20 minutes): Fix: Autoscale a dedicated Spot / Preemptible Kubernetes node pool pre-warmed at 05:45 with cached container images; because every scenario chunk writes to an idempotent S3 path, spot evictions retry cheaply.
    3. 4.6B scenario-level rows/year in PostgreSQL: Fix: Keep raw scenario curves solely as partitioned Parquet in S3 (queried on demand via DuckDB or Trino), while keeping PostgreSQL strictly for forecast_summary (12,600 rows/day stays constant regardless of scenario count!).
    4. 2.9 GB CSV parsing in pandas RAM: Fix: Stream-validate and partition the CSV using Polars or DuckDB in seconds with flat memory usage.
    5. 1,000 overlapping lines on the dashboard: Fix: Replace 1,000 spaghetti lines with shaded quantile fan bands (P5, P25, P50, P75, P95 — statistically meaningful at N = 1,000!) plus on-demand drill-down into extreme or clustered scenarios.

    Summary of key trade-offs:

    Decision Benefit Cost Accepted
    Deferrable 2-min polling + content hash/grid check Catches early arrivals within 2 min; immune to stale 200s and half-written CSVs ~90 cheap conditional HTTP requests each morning
    Store both raw CSV and curated Parquet Full vendor audit trail + fast, unit-clean model reads and historical backtests ~15 GB/year of cheap S3 storage
    Separate weather_ingest and forecast_models DAGs Clean backfills, shadow runs, and vendor-correction reruns without fake downloads Wiring an event trigger + run_sets metadata table
    Per-scenario task chains (no global upstream barrier) Minimizes critical-path latency to slowest_upstream + price (~10 min compute) Final summary waits for all scenarios unless progressive publishing is enabled
    Immutable run_sets + single-row published pointer Zero torn dashboard reads, instant rollback, and effortless vintage-vs-vintage queries Keeping historical summary rows (trivial in Postgres)

Intuition & how it works

Think of a morning financial newsroom printing 10 "what-if" market editions from a weather wire dispatch that arrives sometime around 6:00 AM. First, an intake desk verifies the entire wire transmission from top to bottom so a garbled or yesterday-dated file never reaches the writers. Next, 10 independent desk teams each carry one weather scenario straight through demand, wind, solar, hydro, and electricity price without waiting on slower writers at neighboring desks. Finally, an editor compiles summary tables onto a fresh display board in the back room and flips the trading-floor sign from yesterday's board to today's board in one instant.

A naive script runs a fixed 06:00 cron job, overwrites a latest_forecast SQL table in place, runs all 40 upstream models followed by all 10 price models behind one global barrier, and points charts straight at that mutable table. Whenever the vendor publishes at 06:06, the 06:00 cron silently re-runs yesterday's forecast as today's; one slow hydro run holds up every other scenario's price run; and overwriting rows in place shows traders a dangerous mix of yesterday's demand with today's prices while erasing the history needed to compare forecasts across days.

Here is a concrete morning trace on Wednesday 2026-08-12:

05:30  Deferrable poller wakes up, sends conditional GET -> server returns yesterday's 2026-08-11 CSV.
       Poller sees (2026-08-11T06, sha256=AAA) already in forecast_files and issue_date < 2026-08-12 -> sleeps 2m.
06:04  Vendor uploads 2026-08-12 CSV. At 06:05 poller verifies Content-Length, all 10x360 rows, and
       blocking bounds -> saves raw CSV + 10 curated Parquet files -> emits weather_forecast_ready.
06:06  forecast_models creates run_set rs_0904 (pinning exact sha256 container digests) and launches
       10 parallel chains. Scenario 1's 4 upstream pods finish in 3 min and immediately start price_01!
06:16  Slowest chain finishes -> aggregate writes 12,600 rows for rs_0904 -> 1 SQL UPDATE flips
       published('live') from rs_0903 to rs_0904. Traders see "Issued 06:00, Rev 1, Published 06:17".

Key trade-offs

  • Early 2-minute polling vs. fixed cron vs. vendor push. A fixed cron either fires before the vendor uploads (grabbing yesterday's file) or pads the schedule late (wasting precious pre-market minutes). Polling every 2 minutes from 05:30 with an Airflow deferrable sensor (an async task that frees its worker slot while waiting) bounds detection lag to 2 minutes for ~90 tiny HTTP checks; if the vendor later adds webhooks, use push as the fast path and keep polling as the fallback.
  • Content verification vs. trusting HTTP headers. Conditional headers like ETag (an HTTP file fingerprint) cheaply skip unchanged downloads (304 Not Modified), but only parsing issue_time, hashing the bytes, and verifying all 10 x 360 rows proves a 29 MB file is genuinely today's complete forecast rather than a stale or mid-upload file.
  • Keeping both raw CSV and curated Parquet vs. storing only one. Keeping only raw CSV forces every model and notebook to re-parse text and unit conversions; keeping only transformed Parquet (a fast, compressed columnar format) loses vendor auditability and prevents re-parsing if a parser bug is found. Storing both costs ~15 GB per year on S3.
  • Separate weather_ingest and forecast_models DAGs vs. one monolithic DAG. Splitting ingestion from model orchestration requires an event trigger and a run_sets metadata table, but lets engineers rerun models on vendor corrections, run 30-day historical backfills, or shadow-test new models without faking downloads.
  • One pod per run (at 10 scenarios) vs. chunked array jobs (at 1,000 scenarios). Fifty Kubernetes pods per morning gives crisp per-scenario retry logs in Airflow with minimal overhead. At 1,000 scenarios (5,000 runs), pod startup overhead dominates, making 50-scenario batch array chunks the right trade-off despite coarser chunk-level retries.
  • Precomputed summary tables vs. on-the-fly dashboard aggregation. Writing 12,600 summary rows (mean, median, min, max, std, plus power on-peak/off-peak blocks) once per run keeps trader page loads sub-100 ms and guarantees every trader sees identical numbers, while S3 Parquet outputs remain available for ad-hoc quant queries.

Common mistakes

  • Running a single cron job at 06:00 and assuming HTTP 200 means today's complete file. Public "latest" URLs routinely return yesterday's CSV when late or a truncated file during an in-place upload.
  • Stopping today's morning sensor on a late correction to yesterday's file. Always check both that (issue_time, sha256) is new and that issue_time matches today's expected forecast date before ending today's primary sensor.
  • Putting a global barrier between all 40 upstream runs and all 10 price runs. Scenario s's price model depends only on Scenario s's four upstream outputs; a global barrier needlessly delays 9 scenarios whenever 1 scenario hits a slow node.
  • Overwriting forecast_summary rows in place. In-place updates cause torn dashboard reads (mixing yesterday's wind with today's price), prevent instant rollback, and destroy historical forecast vintages (past forecasts identified by when they were issued).
  • Deploying black-box models with mutable :latest tags. Pinning immutable container image digests (@sha256:...) inside run_sets.model_versions is essential so silent code pushes never masquerade as overnight weather shifts.
  • Relying solely on Airflow alerts to tell you Airflow failed. If the Airflow scheduler or its database hangs at 05:00, no DAG runs and no Airflow alert fires; always run an external dead man's switch (an independent monitor outside the orchestrator) that pages on-call if published.published_at is still yesterday at 07:00.
  • Drawing 1,000 overlapping line series when scenario counts scale. Ten lines are readable; 1,000 lines turn into solid ink and freeze browsers — switch to quantile fan bands (P5/P25/P50/P75/P95) and keep raw scenario series in Parquet rather than PostgreSQL rows.

Follow-up questions

  • Suppose the weather vendor uploads a revised CSV later that morning after the initial forecast run is already live. How should your pipeline process the update and transition the trader dashboard? Our slow post-arrival poller (every 15 minutes until 14:00) detects a new sha256 for today's issue_time, validates it, saves the raw and curated files as revision = 2 without touching revision = 1, and triggers a fresh forecast_models run set. Traders continue seeing revision = 1 undisturbed while revision = 2 computes; once all 50 runs and summary checks pass, our monotonic UPDATE published transaction atomically flips live to revision = 2 (and rejects any slower revision = 1 retry if both overlapped). The dashboard displays a "Revised forecast available (Rev 2) — reload" banner, notifies the trading Slack channel with a Rev 2 vs Rev 1 delta view, and records the exact switch timestamp in publish_log.
  • Quant researchers release an updated wind generation model. How do you deploy it safely to production and backtest it across the prior month's archived weather inputs against the incumbent version? First push the new wind container and record its immutable @sha256 digest without changing the live config pin. Trigger model_backfill over the last 30 stored forecast_files in the low-priority Kubernetes pool with purpose = "backfill" and {wind: new_digest} — crucially rerunning both wind and downstream price (reusing existing demand, solar, and hydro S3 outputs!) so researchers can evaluate wind MAE/bias against actual grid generation and inspect the downstream price impact. Next, run the new digest in purpose = "shadow" alongside the morning run for a week to verify runtime stability before updating model_versions.yaml in Git (making rollback a one-line Git revert).
  • A trader asks to overlay today's hourly price projection for next Wednesday against the projection generated seven days earlier for those exact target hours. How must your schema store historical runs to answer that query? You must never overwrite predictions for a future hour; instead, store every forecast vintage append-only keyed by both issue_time (when the forecast was made, via run_set_id -> file_id) and valid_time (the target hour being predicted), alongside publish_log (which records which run_set_id was actually live on traders' screens each day). Because each daily forecast spans 15 days (360 hours), both today's forecast (e.g., Wednesday 2026-08-12) and the forecast issued 7 days earlier (2026-08-05) contain rows for valid_time on next Wednesday (2026-08-19). Our /v1/compare endpoint simply filters forecast_summary for valid_time inside 2026-08-19 across the final live run_set_id of each requested issue date.
  • What if one upstream model runs five times slower than the remaining three? How do you adapt task scheduling and the trader user experience? Because every scenario's price run depends on all four upstream outputs of that scenario, the slowest model (say hydro taking 25 minutes instead of 5) dictates the entire critical path — adding extra CPUs to wind or solar saves zero wall-clock time. First, optimize the bottleneck with research: allocate larger CPU/GPU pods, prioritize its tasks in the worker pool, or split regions in parallel (note you cannot split hours in parallel if hydro carries reservoir state forward hour-by-hour). On the product side, publish per-model pointers progressively so traders see fresh demand, wind, and solar curves within 6 minutes while price displays "Computing (waiting on hydro)" — or, if the desk agrees hydro moves slowly day-to-day, publish a clearly badged "Preliminary Price (using yesterday's hydro for overlapping 14 days)" first and swap in the final 15-day price once hydro finishes.

Follow-up questions

Similar questions

More Engelhart interview questions

All 8 Engelhart questions →