Skip to content
LeetQuant
QD07 Databases, Pipelines and Distributed Systems

QD07 · Databases, Pipelines and Distributed Systems · Lesson 2 of 5

Data Ingestion

Build loads that can be rerun safely: natural keys and upserts for idempotency, deduplication, schema validation with quarantine, explicit handling of late and corrected data, and backfills that recompute exactly what changed.

16 min

Objective

An ingestion job pulls data from a vendor, an exchange or an internal system and writes it into tables that research and trading read. Interviewers ask about it because every serious data bug in a quant shop is an ingestion bug: doubled volumes after a retry, a vendor correction that never landed, a backtest that used data before it existed. By the end of this lesson you should be able to design a load that is idempotent, validated and point-in-time correct, and to plan a backfill.

The central property: idempotency

A load is idempotent if running it twice on the same input leaves the same state as running it once. This matters because jobs will run twice: a scheduler retries after a timeout, an operator reruns a failed day, a message is redelivered. A plain append is not idempotent:

import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE raw (symbol TEXT, d TEXT, volume INTEGER)")
rows = [("AAA", "2024-01-02", 1000), ("AAA", "2024-01-03", 1500)]
for attempt in range(2):          # the job is retried after a timeout
    con.executemany("INSERT INTO raw VALUES (?, ?, ?)", rows)
print(con.execute("SELECT SUM(volume) FROM raw").fetchone())   # (5000,)

The true total is 2,500. Idempotency needs two things: a natural key that identifies a record (here (symbol, d); for trades, an exchange trade id; for events, an event id), and a write that replaces rather than adds on that key.

Upserts with a version guard

An upsert inserts a new key or updates an existing one. Adding a version (or a vendor timestamp) and updating only when the incoming version is newer makes the load safe against both retries and out-of-order replays of older files:

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("""
    CREATE TABLE bars (
        symbol TEXT NOT NULL,
        d      TEXT NOT NULL,
        close  REAL NOT NULL CHECK (close > 0),
        volume INTEGER NOT NULL CHECK (volume >= 0),
        version INTEGER NOT NULL,
        PRIMARY KEY (symbol, d)
    )""")

UPSERT = """
    INSERT INTO bars (symbol, d, close, volume, version)
    VALUES (?, ?, ?, ?, ?)
    ON CONFLICT (symbol, d) DO UPDATE SET
        close = excluded.close,
        volume = excluded.volume,
        version = excluded.version
    WHERE excluded.version > bars.version
"""

def load(rows):
    with con:  # one transaction: all rows or none
        con.executemany(UPSERT, rows)

batch = [("AAA", "2024-01-02", 100.0, 1000, 1),
         ("AAA", "2024-01-03", 102.0, 1500, 1)]
load(batch)
load(batch)                                         # retry: no change
load([("AAA", "2024-01-03", 102.5, 1550, 2)])       # vendor correction
load([("AAA", "2024-01-03", 102.0, 1500, 1)])       # stale replay: ignored
print(con.execute("SELECT * FROM bars ORDER BY d").fetchall())
# [('AAA', '2024-01-02', 100.0, 1000, 1), ('AAA', '2024-01-03', 102.5, 1550, 2)]

Three design points:

  • The primary key makes duplicates impossible rather than merely unlikely. Constraints (NOT NULL, CHECK) are a last line of defence that the database enforces even when the code has a bug.
  • The transaction makes a batch atomic. A crash halfway leaves the table as it was, so the retry starts from a clean state.
  • The version guard makes the outcome independent of arrival order. Without it, replaying yesterday's file after today's correction would undo the correction.

For aggregated outputs (one file per day), the equivalent pattern is partition overwrite: delete the day's partition and insert its recomputed contents in one transaction, or write to a new location and swap a pointer. "Overwrite this partition" is idempotent; "append to this table" is not.

Deduplication

When you cannot enforce a key at write time (a raw landing zone that must accept everything, a stream with redelivery), deduplicate on read with the ROW_NUMBER pattern from SQL for Time Series:

SELECT symbol, d, close, received_at FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY symbol, d
                               ORDER BY received_at DESC) AS rn
  FROM landing
) WHERE rn = 1;

On a landing table holding an exact duplicate of AAA 3 January (close 102.0, received 21:00) and a correction (102.5, received 06:00 next day), this returns the single row AAA 2024-01-03 102.5. Decide what "duplicate" means before writing the query: identical bytes (a redelivery), the same natural key (a correction), or the same economic event reported by two venues (needs a matching rule, not a key).

Schema validation and quarantine

Validate every record against an explicit contract before it reaches the clean tables, and route failures to a quarantine table with the reason instead of dropping them or failing the whole batch:

from datetime import date

def validate(row: dict) -> list[str]:
    errors = []
    for field in ("symbol", "d", "close", "volume"):
        if row.get(field) is None:
            errors.append(f"missing {field}")
    if errors:
        return errors
    try:
        date.fromisoformat(row["d"])
    except ValueError:
        errors.append(f"bad date {row['d']!r}")
    if not isinstance(row["close"], (int, float)) or row["close"] <= 0:
        errors.append(f"bad close {row['close']!r}")
    if not isinstance(row["volume"], int) or row["volume"] < 0:
        errors.append(f"bad volume {row['volume']!r}")
    return errors

Run on five sample rows, one passes and four are quarantined with bad close 0.0, bad date '05/01/2024', bad close '52.0' (a string, not a number) and missing close. Beyond per-row checks, add batch-level checks: row count within a band of yesterday's, every expected symbol present, no day with zero volume across the whole universe. A vendor that silently sends half a file passes every row check.

Two policies to state in an interview: whether a batch with some bad rows loads the good ones (usually yes, with an alert above a threshold) and whether a schema change (a new column, a renamed field) fails loudly (it should; silently reading NULL for a renamed column is how a feature becomes constant).

Late, out-of-order and corrected data

Market data is revised: trades are busted, corporate actions adjust history, fundamentals are restated, vendors fix errors days later. A pipeline must answer two different questions:

  • What is the best current value for 3 January? The latest version.
  • What did we know about 3 January at 21:00 on 3 January? The version available then.

A backtest must use the second. Store both the event (valid) time and the knowledge (system) time, for example d and received_at, and never overwrite history in a research table; append versions and select "latest version with received_at <= the simulation time". This is called a bitemporal or point-in-time table. Overwriting in place is how restated fundamentals end up in a backtest dated before the restatement.

Backfills

A backfill reloads or recomputes history: a new vendor, a bug fix in a transform, a new derived column. Do it with the same idempotent, partitioned job you run daily, parameterised by date range, so a backfill is "run the normal job for these partitions" rather than a one-off script. Then recompute every downstream partition whose inputs changed, which is determined by the lookback of each transform.

Worked example

which outputs does a correction invalidate?

A daily job writes a 3-day moving average (by rows) of AAA's close, one partition per trading day. The trading days are 2, 3, 4, 5 and 8 January with closes 100, 102, 99, 101 and 104. On 9 January the vendor corrects the 3 January close from 102 to 102.5. Which output partitions must be recomputed, and what are their new values?

Show solution

Step 1: find the dependents. A 3-row window at day tt reads days t−2t-2, t−1t-1 and tt. The corrected day (3 January) therefore feeds the outputs for 3, 4 and 5 January. The output for 8 January reads 4, 5 and 8 January, and the output for 2 January reads only that day; neither changes.

Step 2: recompute.

OutputWindowOldNew
3 Jan100, 102.5101.0101.25
4 Jan100, 102.5, 99100.3333100.5
5 Jan102.5, 99, 101100.6667100.8333

(Checked by rerunning the window query in SQLite on the corrected data; 8 January stays at 101.3333.)

Step 3: generalise. A correction at day tt to an input of a transform with lookback LL rows invalidates outputs t,…,t+L−1t, \dots, t + L - 1, and each downstream transform extends the range by its own lookback. A 20-day volatility feeding a 60-day z-score can make one corrected bar touch about 80 days of signals. This is why lineage (which partitions read which) is worth recording, and why recomputing a generous range with an idempotent job is safer than computing the minimal set by hand.

Knowledge check

A nightly job appends the day's vendor file to a trades table. The scheduler retries jobs that exceed 30 minutes, and occasionally a slow run completes after its retry has started. What is the most robust fix?

Knowledge check

A fundamentals table is updated in place whenever a company restates earnings. A backtest that joins on report date shows strong returns to an earnings-quality signal. What is the most likely problem?

Knowledge check

An upsert updates on conflict without a version guard. File v2 (a correction) is loaded, then an operator reruns the older file v1 for an unrelated reason. What is the final state?

Key takeaways

  • Assume every job runs more than once. Make writes idempotent with a natural key plus upsert, or a transactional partition overwrite.
  • Guard upserts with a version or vendor timestamp so late replays cannot undo corrections.
  • Deduplicate raw data with ROW_NUMBER over the natural key, after deciding what counts as a duplicate.
  • Validate rows and batches; quarantine failures with reasons; fail loudly on schema changes.
  • Keep event time and knowledge time. Research tables are append-only and queried point-in-time.
  • A backfill is the normal job over a date range, followed by recomputing every downstream partition within each transform's lookback.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).