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:
10distinct weather ensemble scenarios;- a
15-daylookahead at hourly granularity (~360hourly 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
10scenarios 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
10scenarios to hundreds or thousands, and how compute scheduling, storage layout, and visualization adapt.
Step-by-step walkthrough
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 cutWindandSolarsupply, rainfall feedsHydroreservoirs, and together those four fundamentals driveElectricity Price. Every morning around06:00, a vendor publishes a CSV file containing10possible 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_timecolumn (when the forecast was generated). HTTPETag/Last-Modifiedheaders exist as a fast hint, but we always verify file contents.Arrival window & same-day corrections Usually lands between 05:50and06: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~100US weather stations and6weather 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) take2–5 mineach on 2 vCPUs;pricetakes~5 minconsuming the 4 upstream outputs of the same scenario.Model output shape Each run outputs 360hourly values across7major US power markets (PJM, ERCOT, CAISO, MISO, SPP, NYISO, ISO-NE).Users, target latency & existing stack ~30 traders behind company SSO; target < 20 minutesfrom CSV publication to live dashboard; keep all history; run on existing Airflow on Kubernetes, S3-compatible object storage, and PostgreSQL.Core non-functional goals
- 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.
- Full reproducibility: Every chart number traces back to one immutable raw CSV hash and exact container versions of all 5 models.
- Pragmatic simplicity: Size tools to the actual data volume so a small engineering team can operate it effortlessly.
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/dayof raw CSV and12,600summary 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:
50runs at 10 scenarios becomes5,000runs at 1,000 scenarios, showing exactly what will break first in the future.
- Data volume at 10 scenarios is tiny.
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:latesttag). - A forecast vintage (
issue_time) is when a prediction was made, as opposed tovalid_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®ion=ERCOT&agg=hourly|daily|on_peak GET /v1/forecasts/{run_set_id}/scenarios?model=price®ion=ERCOT GET /v1/compare?model=price®ion=ERCOT&valid_from=...&valid_to=...&issued=2026-08-12,2026-08-05 GET /v1/forecasts/{run_set_id}/export.csvNotice that only
/v1/forecasts/currentlooks up the active pointer; every panel query passes an explicitrun_set_idso 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 sawHigh-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)Deep dive 1: Ingestion, variable-time polling, and validation
Running a naive cron job at
06:00is a classic trap because an HTTP request at06:00can return four very different things:404or304 Not Modified(nothing new yet),200 OKserving yesterday's stale CSV (HTTP 200 does not mean today's forecast!),200 OKserving a half-uploaded CSV if the vendor overwrites the file in place without atomic rename, or200 OKserving today's complete CSV (or a same-day correction hours later).
Polling strategy: Schedule
weather_ingestat05:30using 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 reply304 Not Modifiedwith zero body bytes when unchanged) every2 minutesuntil08:30(paging on-call if nothing arrives by08:30), then switches to a slow15-minutepoll until14:00to 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
10scenarios, each with360consecutive hourlyvalid_timesteps starting fromissue_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 °Cin the same direction vs. yesterday's overlapping 14 days (for example, vendor accidentally switched°Cto°F, where10 °Cbecomes50 °F), block immediately!
- Exact schema, parseable numeric/timestamp types, and zero
- 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.
- Single-region overnight temperature jump
Only when all blocking checks pass does
validate_and_curatewrite the 10 per-scenario Parquet files and emitweather_forecast_ready.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 byweather_forecast_readywith{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
pricefor Scenario 4 actually needs: onlydemand_4,wind_4,solar_4, andhydro_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 ataggregate_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_pointerdef 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_uriIsolating
live_morning_poolfrombackfill_low_prio_poolguarantees a researcher's 30-day historical backtest never delays the 6 AM trading run.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): Precomputemean,median,min,max, andstdper(model, region, valid_time), plus expose all10raw scenario curves (10 lines are crisp enough to plot directly, and with onlyN = 10points,min/maxplus 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_meanacross 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_summarieswrites all12,600rows under the newrun_set_idwhilepublishedstill points at yesterday. Thenpublish_pointerflips 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;- Hourly distribution stats (
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 truncationKeep polling every 2 min until 08:30Data on-call at 08:30Prominent 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 scenariosonly 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_atby07:00)Platform on-call Dashboard auto-highlights age ( now - published_at) in amber/redBad Forecast Post-Publish Subtle vendor error noticed at 07:15Run 1-line rollback command pointing publishedback to yesterday'srun_set_idDesk + Data team Banner: "06:02 forecast retracted at 07:15; reverted to prior run" Scaling to thousands of scenarios and trade-off summary
If research expands from
10weather scenarios to1,000ensemble members, re-multiplying shows36Minput rows (~2.9 GBCSV/day),5,000model runs/day (~19,000container-minutes ->~1,900 vCPUsto finish in 20 minutes), and4.6 billionoutput values/year. Here is what breaks first and how we evolve each layer without changing our core architecture:- 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(20chunks x 5 models =100tasks) 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. - Morning burst compute (
~1,900 vCPUfor 20 minutes): Fix: Autoscale a dedicated Spot / Preemptible Kubernetes node pool pre-warmed at05:45with cached container images; because every scenario chunk writes to an idempotent S3 path, spot evictions retry cheaply. - 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,600rows/day stays constant regardless of scenario count!). - 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.
- 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 atN = 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_ingestandforecast_modelsDAGsClean backfills, shadow runs, and vendor-correction reruns without fake downloads Wiring an event trigger + run_setsmetadata tablePer-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-rowpublishedpointerZero torn dashboard reads, instant rollback, and effortless vintage-vs-vintage queries Keeping historical summary rows (trivial in Postgres) - 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
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:30with 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 parsingissue_time, hashing the bytes, and verifying all10 x 360rows proves a29 MBfile 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_ingestandforecast_modelsDAGs vs. one monolithic DAG. Splitting ingestion from model orchestration requires an event trigger and arun_setsmetadata 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,600summary 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:00and assuming HTTP200means 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 thatissue_timematches 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 Scenarios's four upstream outputs; a global barrier needlessly delays 9 scenarios whenever 1 scenario hits a slow node. - Overwriting
forecast_summaryrows 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
:latesttags. Pinning immutable container image digests (@sha256:...) insiderun_sets.model_versionsis 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 ifpublished.published_atis still yesterday at07: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 newsha256for today'sissue_time, validates it, saves the raw and curated files asrevision = 2without touchingrevision = 1, and triggers a freshforecast_modelsrun set. Traders continue seeingrevision = 1undisturbed whilerevision = 2computes; once all 50 runs and summary checks pass, our monotonicUPDATE publishedtransaction atomically flipslivetorevision = 2(and rejects any slowerrevision = 1retry if both overlapped). The dashboard displays a "Revised forecast available (Rev 2) — reload" banner, notifies the trading Slack channel with aRev 2 vs Rev 1delta view, and records the exact switch timestamp inpublish_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
@sha256digest without changing the live config pin. Triggermodel_backfillover the last 30 storedforecast_filesin the low-priority Kubernetes pool withpurpose = "backfill"and{wind: new_digest}— crucially rerunning bothwindand downstreamprice(reusing existingdemand,solar, andhydroS3 outputs!) so researchers can evaluate wind MAE/bias against actual grid generation and inspect the downstream price impact. Next, run the new digest inpurpose = "shadow"alongside the morning run for a week to verify runtime stability before updatingmodel_versions.yamlin 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, viarun_set_id -> file_id) andvalid_time(the target hour being predicted), alongsidepublish_log(which records whichrun_set_idwas actually live on traders' screens each day). Because each daily forecast spans 15 days (360 hours), both today's forecast (e.g., Wednesday2026-08-12) and the forecast issued 7 days earlier (2026-08-05) contain rows forvalid_timeon next Wednesday (2026-08-19). Our/v1/compareendpoint simply filtersforecast_summaryforvalid_timeinside2026-08-19across the final liverun_set_idof 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
pricerun depends on all four upstream outputs of that scenario, the slowest model (sayhydrotaking 25 minutes instead of 5) dictates the entire critical path — adding extra CPUs towindorsolarsaves 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 ifhydrocarries reservoir state forward hour-by-hour). On the product side, publish per-model pointers progressively so traders see freshdemand,wind, andsolarcurves within 6 minutes whilepricedisplays "Computing (waiting on hydro)" — or, if the desk agreeshydromoves 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 oncehydrofinishes.
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?
- 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?
- 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?
- What if one upstream model runs five times slower than the remaining three? How do you adapt task scheduling and the trader user experience?
Similar questions
- Building and Unit Testing a FastAPI REST Endpoint Around Python Logic
- Abstract Base Classes and Method Binding in Python
- Under the Hood of Python Dicts: Hashing, Collisions, and Valid Keys
- Generator Mechanics, Lazy Evaluation, and Function Decorators in Python
- Python Environment Isolation, Package Managers, and Daily Linux Workflow
- Database Index Trade-Offs and Diagnosing Slow SQL Queries
More Engelhart interview questions
- Building and Unit Testing a FastAPI REST Endpoint Around Python Logic Medium
- Abstract Base Classes and Method Binding in Python Medium
- Under the Hood of Python Dicts: Hashing, Collisions, and Valid Keys Medium Pro
- Generator Mechanics, Lazy Evaluation, and Function Decorators in Python Medium Pro
- Python Environment Isolation, Package Managers, and Daily Linux Workflow Medium Pro
- Database Index Trade-Offs and Diagnosing Slow SQL Queries Medium Pro
- Python Concurrency: Processes, Threads, the GIL, and Asyncio Medium Pro