Why I rebuilt this
My first Formula 1 project was a set of Python scripts and Jupyter notebooks using FastF1 to plot one-off telemetry comparisons. That worked fine for answering a single question on a single race weekend, but it had an obvious ceiling: every time I wanted to compare drivers across a season, track stint degradation, or hand the data to a BI tool, I had to re-run notebooks and stitch DataFrames together manually.
I rebuilt the project as a proper ETL pipeline (f1-pipeline) backed by a relational database on my homelab SQL Server instance (Formula1), then connected Power BI directly to that schema to build a three-page Scuderia Ferrari analytics suite (Ferrari.pbix). Instead of regenerating plots after every race, the pipeline keeps nine seasons of schedules, results, lap timing, and trackside weather synced automatically so Power BI always reads from a single, consistent source of truth.
Architecture and stack
The pipeline runs as a packaged Python 3.11+ CLI (f1-pipeline v1.0.0) using fastf1, pandas, and pyodbc over Microsoft ODBC Driver 18 for SQL Server:
FastF1 (F1 Live Timing + Jolpica/Ergast)
│ └─ persistent disk cache: cache/fastf1/
▼
extractor.py ──► transform.py ──► database.py (pyodbc + #Stage temp tables)
│
▼
SQL Server (Formula1) ──► Power BI (Ferrari.pbix)
One deliberate architectural decision happens at extraction. FastF1 can download full 10+ Hz car and GPS telemetry (car_data and position_data), which quickly balloons into gigabytes of nested data across multiple seasons. Because the relational warehouse and Power BI layer focus on race strategy, tyre stints, sector splits, speed traps, and weather rather than throttle/brake traces, extractor.py loads sessions selectively:
session.load(
laps=True,
telemetry=False,
weather=self.include_weather,
messages=False,
)
That single choice keeps multi-season backfills fast and disk usage modest while preserving every timing metric needed for race engineering analysis. On the SQL Server side, the pipeline connects through a dedicated least-privilege f1_loader login rather than sa.
Relational schema and dataset scale
The warehouse uses six relational tables in dbo (defined in sql/schema.sql and provisioned idempotently via f1-pipeline setup):
Events— Primary key(Season, RoundNumber). Stores Grand Prix weekend metadata (Country,Location,OfficialEventName,EventName,EventDate,EventFormat,F1ApiSupport). Pre-season testing (RoundNumber <= 0orEventFormat = 'testing') is excluded by default.Sessions— Primary keySessionID(YYYY_RR_TYPE, e.g.,2026_22_R), unique(Season, RoundNumber, SessionType), foreign key toEvents. Tracks UTC start times and loaded row counts per session.Results— Primary key(SessionID, DriverNumber), foreign key toSessions(ON DELETE CASCADE). Captures grid and finish positions,Q1Seconds–Q3Seconds, raceTimeSeconds, classificationStatus,Points(FLOATso historical half-point races fit cleanly), and a driver/team snapshot.Laps— Primary key(SessionID, DriverNumber, LapNumber), foreign key toSessions(ON DELETE CASCADE). Stores lap, sector, and pit in/out durations converted frompandas.TimedeltaintoFLOATseconds, four speed traps (SpeedI1,SpeedI2,SpeedFL,SpeedST), tyre metadata (Stint,Compound,TyreLife,FreshTyre),TrackStatus,Deleted/DeletedReason, andIsAccurate.Weather— Primary key(SessionID, SampleIndex), foreign key toSessions(ON DELETE CASCADE). RecordsAirTemp,TrackTemp,Humidity,Pressure,Rainfall,WindDirection, andWindSpeedindexed byTimeSecondsfrom session start.PipelineRuns— Primary keyRunID(BIGINT IDENTITY). Audit log recording everybackfillandsyncexecution (Command,StartedAtUtc,FinishedAtUtc,Status,SessionsProcessed,SessionsFailed,RowsUpserted,Message).
Before every backfill, sync, check, or status run, the repository queries sys.columns and sys.types to verify column types, byte lengths, and nullability against the expected schema. If the target database drifts, the CLI fails fast before extracting a single session.
Across nine seasons (2018–2026) of Race (R), Qualifying (Q), and Sprint (S) sessions — updated through Round 22 of the 2026 season (Qatar Grand Prix) — the database holds:
- 196 Grand Prix weekends (
Events) - 420 sessions (
Sessions) - 8,497 driver classification records (
Results) - 286,659 individual laps (
Laps) - 48,488 trackside weather observations (
Weather)
Idempotent upserts and the FIA steward problem
Formula 1 data is not cleanly append-only. Hours after the checkered flag, FIA stewards routinely issue time penalties, disqualifications, or track-limits lap deletions that change finishing order, points, and valid lap counts. A naive INSERT-only loader either breaks on primary key collisions or leaves stale, pre-penalty classifications in the database.
Two mechanisms in the pipeline handle this cleanly:
1. Per-session transactional staging upserts (database.py). Each session’s Sessions, Results, Laps, and Weather rows are committed inside a single SQL Server transaction. Rows are first bulk-inserted into tempdb staging tables (#ResultsStage, #LapsStage, #WeatherStage) using cursor.fast_executemany = True, then reconciled in three steps:
-- 1. Remove rows for this SessionID dropped in an updated FIA classification
DELETE target
FROM dbo.Laps AS target
WHERE target.SessionID = ?
AND NOT EXISTS (
SELECT 1 FROM #LapsStage AS source
WHERE source.SessionID = target.SessionID
AND source.DriverNumber = target.DriverNumber
AND source.LapNumber = target.LapNumber
);
-- 2. Update existing keys and 3. Insert newly added keys
If any step fails mid-session, SQL Server rolls back the entire transaction so partial sessions never pollute downstream queries.
2. Incremental sync windowing and rate-limit recovery (cli.py). During scheduled sync runs, completion_buffer_hours (default 3) skips future or in-progress sessions until timing feeds settle, while recheck_days (default 7) automatically bypasses the local FastF1 disk cache (Cache.disabled()) for any session within the past seven days. That means steward revisions propagate into SQL Server automatically on subsequent runs without manual --force flags. For large historical loads, --wait-on-rate-limit catches FastF1’s rolling 500 calls/hour rate limit, sleeps 3,615 seconds for the window to clear, reconnects to SQL Server, and resumes without losing previously committed sessions.
The Power BI layer: Scuderia Ferrari’s 2026 season
Power BI connects directly to the five analytical tables (Events, Sessions, Results, Laps, Weather), scoped at the report level to the 2026 season (through 22 completed rounds) and styled with a custom Scuderia Ferrari theme (#DC0000 and #9B0000) across three pages.
1. Executive Summary (Ferrari | 2026 Grand Prix Performance)
The landing page isolates Sunday Grand Prix performance (SessionType = 'R') for Ferrari (TeamName = 'Ferrari'), with a responsive mobile layout built alongside the 1280×720 desktop canvas. Five KPI cards establish the season baseline across 22 Grands Prix:
- 470 Grand Prix points
- 2 wins (Lewis Hamilton at Round 7 in Barcelona; Charles Leclerc at Round 9 at Silverstone)
- 13 podiums
- 5.8 average finish position
- 91% finish rate (40 classified finishes out of 44 starts)
Below the cards, a Starting Position vs. Finishing Position scatter plot (with Positions Gained tooltips), a Points by Round trend line, and three driver-comparison column charts (Points by Driver, Podiums by Driver, Average Finish by Driver) break out the intra-team battle. Hamilton leads Leclerc 248 to 222 in Sunday points (7 podiums vs. 6, and a 5.3 average finish vs. 6.4). Looking at the round-by-round classifications shows that gap is driven more by reliability than raw speed: Leclerc absorbed three retirements (Monaco, Barcelona, and Monza) compared to one for Hamilton (Spain), while Hamilton also salvaged points from recovery drives like P20 to P9 in São Paulo.
2. Current Standings (F1 2026 | Current Standings)
The second page drops the team and Sunday-only filters to place Ferrari in full championship context across all points-paying sessions (Races and Sprints), using a dynamic [Bar Color] measure across both horizontal bar charts:
- Constructors’ Championship: Mercedes leads on 709 points, while Ferrari holds second on 531 points — a 75-point cushion over McLaren (456) and Red Bull Racing (456) tied for third.
- Drivers’ Championship: Behind Kimi Antonelli (427), Max Verstappen (316), and George Russell (282), Hamilton sits fourth on 275 points — one point clear of Lando Norris (274) — with Leclerc sixth on 256 points.
3. Race Performance Analysis (Ferrari | Race Performance Analysis)
The third page drills into Ferrari’s lap-level execution (Laps.Team = 'Ferrari') with six dropdown slicers (Grand Prix, Clean Laps Only?, Tire Compound, Driver, Stint, and Session Type), Average Lap Time and Fastest Lap KPI cards, Lap Times by Driver and Lap Times by Compound line charts, and a detailed lap table showing sector splits, stint number, position, and tyre life.
In the 2026 Qatar Grand Prix Race view (Clean Laps Only = Yes, defined as full green-flag laps with TrackStatus = '1' and no pit-in or pit-out), Ferrari logged 104 clean laps averaging 88.082 seconds, with Leclerc setting the team’s fastest lap at 86.471 seconds on Hard tyres. Across the opening Medium stint, both drivers were virtually indistinguishable (89.666s clean average for Leclerc vs. 89.674s for Hamilton) before dropping into the mid-87s on the closing Hard stint (87.443s for Leclerc vs. 87.608s for Hamilton).
One important analytical guardrail sits directly on the Lap Times by Compound visual subtitle and page footer:
Observed pace by compound, not adjusted for fuel load or traffic.
Without that caveat, a reader glancing at the chart sees Hard tyres running ~2.1 seconds per lap faster than Mediums and might conclude the Hard compound had dramatically better grip. In reality, fuel burn lightens the car over a Grand Prix distance, making late-race stints naturally faster regardless of compound. Building that domain caveat directly into the visual prevents misreading observational lap averages as controlled tyre-delta numbers.
What’s on GitHub
The full pipeline codebase lives at github.com/jakeb7757/formula1. Modules under src/f1_pipeline/ cleanly separate configuration and .env validation (config.py), FastF1 caching and retry logic (extractor.py), pure type/range transforms (transform.py), schema DDL and sys.columns verification (schema.py), transactional staging upserts (database.py), and CLI orchestration (cli.py). It also includes the reference T-SQL DDL (sql/schema.sql), a homelab operations and least-privilege SQL guide (guide.md), and an offline unit test suite (tests/) using in-memory fake database and FastF1 doubles so pytest runs with no SQL Server instance or network access required.
Reflection
A one-off analysis notebook only has to work once, at the exact moment you run it. A production data pipeline feeding a live BI layer has to survive everything that happens afterward: post-race FIA steward revisions, FastF1’s hourly rate limits, NaT and Timedelta edge cases at the SQL type boundary, and schema drift checks before any write occurs. Pairing that engineering discipline with explicit domain caveats on the Power BI canvas — like flagging unadjusted fuel-load effects on compound pace — is what turns raw timing feeds into reporting an analyst can actually stand behind.