A pipeline runs every night, again after a crash, and once more by hand "just to be sure". If each run adds the same rows again, the store fills with copies; if a run stops half way, it leaves a table that is half loaded and nobody knows. What must a load do so that running it twice, or failing in the middle, never does harm? On 60 days of SPY, three overlapping batches and one failure show the answer.
Why a pipeline must be able to run twice
Where we are: the last topics made a table correct. This topic is about putting a correct table into a store that other code reads. The difficulty is not one load, it is the second and the hundredth. Real pipelines are restarted by schedulers after failures, batches overlap because a vendor sends the last few days again, and operators re-run a job when they are unsure. Each of these repeats data. By the end of this topic you will be able to write a load that is safe to repeat, one that loads only what is new, and one that either finishes or leaves no trace.
Two failures are common and both are silent. The first is duplication: a load that appends rows adds the same day twice when it runs twice, and every sum, average and count that reads the store is wrong. The second is a partial load: the job stops after 400 of 1,000 rows, and the store holds a table that looks fine but is missing a quarter of its days. Nothing raised an alarm for the readers. The cure for the first is called idempotence and the cure for the second is atomicity.
A load that gives the same store whether it runs once or many times with the same data. Idempotence is what makes it safe to retry.
The easiest way to see the difference is to count. The code below loads the same batch of two rows twice, once by appending to a list and once by writing into a dictionary whose key is the symbol and the date.
store_list = []store_dict = {}batch = [("AAA", "2021-03-01", 10.0), ("AAA", "2021-03-02", 10.2)]for run in (1, 2): store_list += batch1 for symbol, day, close in batch: store_dict[(symbol, day)] = close2 print("run", run, "| append:", len(store_list), "rows | upsert:", len(store_dict), "rows")
run 1 | append: 2 rows | upsert: 2 rows run 2 | append: 4 rows | upsert: 2 rows
- 1Appending adds the batch every time.
- 2Writing by key replaces the row that is already there.
After the second run the list has four rows and the dictionary still has two. The dictionary is idempotent because a row has an address, its key, and writing to an address twice leaves one value. The choice of the key is therefore the first design decision of any store: the symbol and the date identify a daily bar, and nothing else should.
Choosing the key is a modelling decision with consequences. A key that is too coarse (the date alone) merges different instruments and loses data. A key that is too fine (the date and the time the file arrived) makes every re-run look like new data and brings the duplicates back. For daily bars the natural key is the instrument and the trading date. For other data the key is whatever makes two rows "the same fact", and the test is to ask: if this row arrived twice, should the store have one copy or two?
Upsert: insert or update
The operation is called an upsert. It has three outcomes for each row, and a good load reports them, because a run that suddenly updates a thousand rows is telling you something. The row is inserted when its key is new, updated when the key exists with different values, and unchanged when the key exists with the same values. The method has three steps.
- 1Split the rowThe first fields are the key and the rest are the values. Make the values a tuple so that two sets of values can be compared with
==. - 2Decide the outcomeIf the key is not in the store the row is inserted. If it is there, compare the values: different means updated, equal means unchanged.
- 3Write only when something changedStore the values for an insert and for an update, and leave the store alone for an unchanged row. Count each outcome.
Worked example 1. *Problem:* the store holds one row for 1 March. The batch has the same row, a new row for 2 March and a changed row for 1 March. What are the counts and the final store? *Plan:* handle the rows in order with the three steps. The last row of the batch sees the store as the earlier rows left it. *Steps:* loop, branch, count.
store = {("AAA", "2021-03-01"): (10.0, 10.5)}batch = [("AAA", "2021-03-01", 10.0, 10.5), ("AAA", "2021-03-02", 10.2, 11.0), ("AAA", "2021-03-01", 10.1, 10.5)]counts = {"inserted": 0, "updated": 0, "unchanged": 0}for row in batch: key, values = (row[0], row[1]), tuple(row[2:])1 if key not in store: counts["inserted"] += 1 elif store[key] != values:2 counts["updated"] += 1 else: counts["unchanged"] += 1 continue3 store[key] = valuesprint(counts)print(store)
{'inserted': 1, 'updated': 1, 'unchanged': 1}
{('AAA', '2021-03-01'): (10.1, 10.5), ('AAA', '2021-03-02'): (10.2, 11.0)}- 1The key and the values come from the same row.
- 2Different values: this is an update.
- 3Only inserts and updates reach this line.
*Check:* the first row is identical to what is stored, so it is unchanged; the second is new; the third has another close for the same key, so it is an update, and the final store holds the close 10.1 for 1 March. The three counts add up to the three rows. *What to notice:* when the same key appears twice in a batch, the later row wins, because it is handled later. The simple method of counting every existing key as an update would report changes that did not happen.
INSERT without a key check, list.append and file.write in append mode all repeat data when the job repeats. If a load must be safe to retry, write by key, or delete the target range and write it again inside one transaction.
Incremental loads and the watermark
Upserting everything every night works, but it wastes time: a table with twenty years of history is rewritten to add one day. An incremental load handles only the new rows. To know what is new, the pipeline needs a memory of what it has already got. The simplest memory is the watermark of each symbol, the latest date it has in the store. A row is new when its date is later than the watermark of its own symbol.
Worked example 2. *Problem:* the store has AAA on 1 and 2 March and BBB on 26 February. A batch has AAA on 1, 2 and 3 March and CCC on 1 March. Which rows are new? *Plan:* compute the watermark of every symbol in the store, then keep the rows later than the watermark of their symbol; a symbol that has no watermark yet is all new. *Steps:* watermarks, compare.
store = {("AAA", "2021-03-02"): 1, ("AAA", "2021-03-01"): 1, ("BBB", "2021-02-26"): 1}marks = {}for symbol, day in store: marks[symbol] = max(marks.get(symbol, ""), day)1print(marks)rows = [("AAA", "2021-03-01"), ("AAA", "2021-03-02"), ("AAA", "2021-03-03"), ("CCC", "2021-03-01")]print([row for row in rows if row[1] > marks.get(row[0], "")])2
{'AAA': '2021-03-02', 'BBB': '2021-02-26'}
[('AAA', '2021-03-03'), ('CCC', '2021-03-01')]- 1The empty text is smaller than any date, so a new symbol starts from nothing.
- 2Only dates strictly later than the watermark are new.
*Check:* the watermark of AAA is 2021-03-02, the latest date and not the last one that was inserted, and only the 3rd of March and the new symbol survive. The 2nd is equal to the watermark and is not new. *What to notice:* the dates are compared as text. The form YYYY-MM-DD sorts as dates do, which is one more reason to keep dates in that form.
If a vendor fixes the close of a day that is already loaded, the corrected row has a date that is not later than the watermark, so the incremental load skips it. That is the price of speed. Corrections to the past need their own job, which is the subject of the next topic.
Putting the two together
An incremental load is the two ideas in sequence: first decide what is new, then upsert only that, and report how many rows were skipped. The skipped count is the proof of idempotence: when the same batch is loaded again, it must be all skipped. The function below does this on toy rows with one price each. Watch the three numbers it prints for three loads, the second a batch that overlaps the first and the third the same batch again.
Worked example 3. *Problem:* load the rows of days 1 and 2, then the rows of days 2 and 3, then the rows of days 2 and 3 again, and report (loaded, skipped) each time. *Plan:* the function computes the watermarks, keeps the new rows, stores them and returns the two counts. *Steps:* define the function, run it three times.
def load(store, batch): marks = {} for symbol, day in store: marks[symbol] = max(marks.get(symbol, ""), day) fresh = [row for row in batch if row[1] > marks.get(row[0], "")]1 for row in fresh: store[(row[0], row[1])] = row[2] return len(fresh), len(batch) - len(fresh)2store = {}batch = [("AAA", "2021-03-01", 10.0), ("AAA", "2021-03-02", 10.2), ("AAA", "2021-03-03", 10.1)]print(load(store, batch[:2]), load(store, batch[1:]), load(store, batch[1:]))
(2, 0) (1, 1) (0, 2)
- 1The watermarks are read before any row of this batch is loaded.
- 2What was not loaded was skipped.
*Check:* the first load inserts 2 rows, the second inserts 1 (day 3) and skips 1 (day 2, already there), and the third inserts nothing and skips both. *What to notice:* the watermarks are read once, before the batch is loaded. If they moved while the batch was being processed, a batch whose rows are out of order would lose rows.
All or nothing
A load can still fail half way: the network drops, the disk fills, a row has a value that the store refuses. If the store is changed row by row, the failure leaves a part of the batch in it, and a rerun then sees a watermark in the middle of the batch and may skip the rest forever. A load is atomic when it makes all its changes appear at once. The simplest way to get that in memory is to do the work on a copy and to replace the original only when the work is complete.
Worked example 4. *Problem:* three rows are loaded and the load fails before the third. Compare a load that changes the store in place with one that works on a copy. *Plan:* both functions raise an error at the failing row; the second keeps its changes in a copy and writes them back after the loop. *Steps:* define both, run both, print the stores.
def load_in_place(store, batch, fail_at): for index, row in enumerate(batch): if index == fail_at: raise RuntimeError("boom") store[row[0]] = row[1]def load_atomic(store, batch, fail_at): working = dict(store) for index, row in enumerate(batch):1 if index == fail_at: raise RuntimeError("boom") working[row[0]] = row[1] store.update(working)2batch = [("a", 1), ("b", 2), ("c", 3)]for load in (load_in_place, load_atomic): store = {} try: load(store, batch, 2) except RuntimeError: pass print(load.__name__, store)
load_in_place {'a': 1, 'b': 2}
load_atomic {}- 1A copy: the real store is not touched yet.
- 2The one moment the store changes, after every row went well.
*Check:* after the failure the in-place load has left a and b in the store and the atomic load has left nothing. *What to notice:* the half-loaded store is the dangerous one, because it looks like a normal store. Databases give you the same guarantee with a transaction: all the writes, then a commit. The copy and the final update are the same idea in a dictionary.
Atomicity is about what a reader can see. A reader may see the old store or the new one, never a mixture. In files this is done by writing to a temporary file and renaming it over the old one, in databases by a transaction, and here by store.update(working) after the last row.
The two properties work best together. A load that is idempotent can be retried, and a load that is atomic leaves nothing behind when it fails, so the scheduler's answer to any failure can be the simplest one: run it again. Without those properties, every failure needs a person to look at the store first. This is the reason that experienced teams treat them as requirements of a pipeline and not as optimisations.
Putting the loads to work
The lab tells one story on real SPY. Batch A covers the first 30 days. Batch B starts 10 days before A ends, so it overlaps, as a vendor's "last two weeks" file does. Batch B is then sent again, as a scheduler would after a restart. Batch C is loaded atomically and fails on its thirteenth row, after two new rows have already been applied to the working copy, and then succeeds. A correct implementation inserts each day once, skips the overlap, ignores the repeat, leaves the store unchanged after the failure and ends with 60 rows.
- FunctionQuestion it answers
- upsert(store, rows)Insert, update or leave each row?the key is symbol and date
- watermark(store, symbol)What is already loaded for this symbol?None for a new symbol
- new_rows(rows, store)Which rows are newer than that?read before loading
- incremental_load(store, rows)Load only the new rows, and count the skipped.never updates old dates
- atomic_load(store, rows, fail_at)All the rows, or none of them?commit at the end
- study(bars)Does the story end with 60 rows?three batches and a failure
What you will build
The lab follows the lecture. Task 1 writes the upsert with its three counts and task 2 finds the watermark of a symbol. Task 3 picks the new rows and task 4 loads only those. Task 5 writes the load that is all or nothing, and task 6 tells the story of the three batches, the repeat and the failure on real SPY.
Next topic: you can now load safely. The next topic, Backfills and late data, is about what the incremental load cannot do: filling a gap in the past, and handling a row that arrives after its day, or a correction to a day you already loaded.
Lab · what's graded
6 tasks · 100 pts- Insert or update15 pts
- The watermark10 pts
- The new rows15 pts
- Load the new rows15 pts
- All or nothing20 pts
- The study on the SPY table25 pts