Ingestion with code
Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Wednesday, 11:20. Tess points at one row: the Hand Cream costs $8.75 in the store and $9 in the warehouse. Nobody typed 9. A script from last quarter guessed that prices were whole numbers from the first file it saw, and has been rounding ever since. The same week the mobile team starts sending app events as nested JSON, and marketing and support have sources waiting. Nora says: "No more one-off scripts. Write the loader once, properly."
You'll learn to
- Name the five jobs every loader does
- Unpack nested JSON into a parent table and a child table
- Page through an API without skipping rows, and respect its rate limit
- Say what dlt, Fivetran and Airbyte do for you
Learn
Every loader does the same five jobs
The old script got data in. Everything else it did by guessing. Before you write its replacement, look at what any loader has to do. Tools differ in the details, but the jobs are always the same five:
- Extract records from the source: files, an API, a database.
- Normalise them: turn nested JSON into flat rows.
- Infer a schema: work out column names and types, and notice when they change.
- Load with a write mode: append, replace, or merge on a key.
- Keep state: remember what is already loaded, so the next run takes only what is new.
You will build a small version of each in Python. After that, tools like dlt, Fivetran and Airbyte stop being magic.
The five jobs of a loader
Five steps in a row: extract records, normalise nested JSON into flat rows, infer a schema, load with a write mode, and keep state; the next run starts from the saved state.
Read it left to right (top to bottom on a phone). The lesson builds each box in turn, starting with a look at the real events.
Look at the events, then infer a schema
import json
with open('data/events.jsonl') as f:
events = [json.loads(line) for line in f]
print(len(events), 'events; one of them:')
print(events[1])
def infer_schema(records):
"""Each top-level key, with the Python types seen for it."""
seen = {}
for rec in records:
for key, value in rec.items():
seen.setdefault(key, set()).add(type(value).__name__)
return {key: sorted(types) for key, types in sorted(seen.items())}
for key, types in infer_schema(events).items():
print(key, types)
There are 192 events. infer_schema reads every record and collects the Python types it sees for each key: that is how loaders "discover" a schema. Look at user_id: both int and NoneType. And items appears only in some events (a page view has none), so a missing key will become a NULL or no child rows.
The trap: the first file decides. Guessing types from the data is convenient, but the guess is made once. A price column that held 5, 12 and 7 on day one becomes a whole-number column. On day two the Hand Cream at 8.75 is quietly rounded to 9, or rejected. That is what happened to Tess's price. Pin the types you care about (dlt takes columns= hints; Airbyte and Fivetran let you review schema changes), and check new data against the schema before loading, as Module 7 shows.
From the types seen to a table design
| Key | Types seen | Becomes |
|---|---|---|
| eventid | str | eventid VARCHAR, the primary key |
| userid | int, NoneType | userid BIGINT, NULL allowed (anonymous visitors) |
| type, page, ts | str | text columns (a smarter loader spots that ts is a timestamp) |
| device | dict | two columns: deviceos, deviceappversion |
| items | list (in some events) | a child table eventsitems |
NoneType next to int is how a loader learns a column may be NULL. A dict turns into more columns. A list turns into more rows, in another table: the next section shows why.
An object becomes columns. A list becomes rows.
Each event has two nested parts, and they need different treatment.
device is an object. It has exactly one value per event, so it fits in the same row. device.os becomes a column called device__os. (dlt uses double underscores; other tools use a dot or one underscore.)
items is a list. It can hold any number of values, so it cannot fit in one row without breaking the grain: one row = one event. It becomes a child table: one row per list element, carrying the parent's key (event_id) and the element's position (idx), so you can join back and keep the order.
It is the same shape as order_items beside orders, and what Module 3 did by hand.
One event, unpacked
One JSON event with plain values, a device object and an items list is unpacked: the plain values and the flattened device object become columns of one row in the events table, and the list element becomes a row in the events__items child table.
One event. A line of JSON with three kinds of thing in it: plain values, an object (
device) and a list (items).Plain values become columns.
event_idandtypego straight into the parent row.The object becomes more columns.
devicehas one value per event, so it is flattened into the same row:device__osanddevice__app_version.The list becomes rows in a child table. Each element of
itemsgets its own row, with the parent'sevent_idand its positionidx. A join onevent_idputs them back together.
Follow the colours from the left box to the two tables. The parent row grows sideways (more columns). The child table grows downwards (more rows).
Unpack into a parent and a child
import json
from normalise import unpack # open normalise.py below: two short functions
with open('data/events.jsonl') as f:
events = [json.loads(line) for line in f]
parents, children = unpack(events, key='event_id', list_field='items')
print(len(parents), 'parent rows;', len(children), 'child rows')
print(parents[1])
print(children[0])
flatten walks into dicts and prefixes their keys. unpack gives every list element its own row with the parent key and its position. 192 events become 192 parent rows and 111 child rows: only product views, add-to-carts and purchases carry items.
Merge on a key, and remember where you stopped
Now load the rows. You have the same choice as in Lesson 6.3: append, replace, or merge on a key. For events the key is event_id, so reading a file twice, or a file that overlaps the last one, cannot double anything. Child rows merge on (event_id, idx).
The last job is state: Lesson 6.2's watermark, kept by the loader. For files, the state is the list of files already loaded. Each run lists the folder, skips the files in the state, loads the rest, and saves the state after each file. Databricks Auto Loader's checkpoint does exactly this.
The two work as a pair. State saves work. The merge keeps the result right when the state is lost.
A small loader: schema from the data, merge on a key, state in a file
import duckdb, glob, json, os
from normalise import unpack
SQL_TYPES = {'int': 'BIGINT', 'float': 'DOUBLE', 'bool': 'BOOLEAN', 'str': 'VARCHAR'}
STATE = 'loader_state.json'
def merge_rows(con, table, rows, key):
"""Create the table from the rows' own types (once), then upsert on the key."""
cols = {}
for row in rows:
for col, value in row.items():
if cols.get(col) is None: # first non-null value decides
cols[col] = SQL_TYPES[type(value).__name__] if value is not None else None
names = list(cols)
defs = ', '.join(f'{c} {cols[c] or "VARCHAR"}' for c in names)
con.sql(f"CREATE TABLE IF NOT EXISTS {table} ({defs}, PRIMARY KEY ({', '.join(key)}))")
marks = ', '.join('?' for _ in names)
con.executemany(f"INSERT OR REPLACE INTO {table} ({', '.join(names)}) VALUES ({marks})",
[[row.get(c) for c in names] for row in rows])
def run(con, pattern):
state = {'files_done': []}
if os.path.exists(STATE):
with open(STATE) as f:
state = json.load(f)
new_files = [p for p in sorted(glob.glob(pattern)) if p not in state['files_done']]
for path in new_files:
with open(path) as f:
records = [json.loads(line) for line in f]
parents, children = unpack(records, 'event_id', 'items')
merge_rows(con, 'events', parents, ['event_id'])
merge_rows(con, 'events__items', children, ['event_id', 'idx'])
state['files_done'].append(path)
with open(STATE, 'w') as f: # after each file
json.dump(state, f)
return new_files
con = duckdb.connect()
count = lambda t: con.sql(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
print('run 1 loaded', run(con, 'landing/events/*.jsonl'))
print('run 2 loaded', run(con, 'landing/events/*.jsonl'))
os.remove(STATE) # lose the state on purpose
print('run 3 loaded', len(run(con, 'landing/events/*.jsonl')), 'files again')
print(count('events'), 'events,', count('events__items'), 'items')
Run 2 loads nothing: the state remembers. Before run 3 the state file is deleted on purpose, so every file is read again, and the merge still leaves 193 events (the 192, plus the late one in the 3 June file). Look at merge_rows: the first non-null value decides a column's type. That is the guess the warning earlier was about.
Page 2 moved while you read page 1
Files are the easy source. The store's orders come from an API, and an API hands out data in pages.
This one pages by offset: page 1 is rows 1 to 20 of the result sorted by updated_at, page 2 is rows 21 to 40, and so on. That would be fine if the data stood still. It does not. The store keeps changing orders while you read.
Suppose an order on page 1 is updated just after you read page 1. Its updated_at is now the newest, so it moves to the end of the sort.
How an offset page skips a row
Six orders on two pages of three: after page 1 is read, order 1002 is updated and moves to the end, order 1004 slides onto page 1 and is never read, and order 1002 is read a second time on page 2.
Before you start. Six orders, sorted by
updated_at, three to a page. (A small version of the real API, which has 80 orders in pages of 20.)You read page 1. Orders 1001, 1002 and 1003 are in your hands.
Order 1002 changes. Its new
updated_atsends it to the end of the sort. Every row behind it moves up one place, so 1004 slides onto page 1, which you have already read.You read page 2. You get 1005, 1006, and 1002 for the second time. Order 1004 was never read, and nothing told you.
Watch order 1004. It never changes, yet it is the one that goes missing: a change somewhere else pushed it onto a page you had finished.
Ask for what comes after the last row
The cure is to stop asking for a position. Ask for the rows after the last one you saw:
WHERE (updated_at, id) > (:last_ts, :last_id) ORDER BY updated_at, id LIMIT n
This is keyset pagination, also called cursor pagination. APIs expose it as a cursor parameter such as starting_after or next_cursor. Rows can shift as much as they like: "after this key" still means the same thing.
Use both columns. A cursor on updated_at alone skips rows that share the boundary timestamp if you compare with >, and repeats them with >=.
Offsets fail on deletes and inserts too: a delete skips a row the same way, and an insert near the front repeats one.
Offset pages skip a row; a cursor does not
import csv
import swiftkart_api as api
def change(order_id, status, ts):
"""The shop updates one order while we are paging."""
with open('data/orders.csv', newline='') as f:
rows = list(csv.DictReader(f))
for r in rows:
if int(r['order_id']) == order_id:
r['status'], r['updated_at'] = status, ts
with open('data/orders.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
# Offset paging: read page 1, the shop changes order 1006, read the rest
first = api.get_orders(page=1, page_size=20)
seen = [r['order_id'] for r in first['data']]
change(1006, 'delivered', '2025-06-16 08:00:00')
page = first['next_page']
while page:
resp = api.get_orders(page=page, page_size=20)
seen += [r['order_id'] for r in resp['data']]
page = resp['next_page']
print('offset: read', len(seen), 'rows,', len(set(seen)), 'orders; never read:', sorted(set(range(1001, 1081)) - set(seen)))
# Keyset paging: always "page 1 of what changed after the last row I saw"
change(1007, 'delivered', '2025-06-16 09:00:00')
cursor, keyset = '1900-01-01 00:00:00', []
while True:
rows = api.get_orders(page=1, page_size=20, updated_since=cursor)['data']
if not rows:
break
keyset += [r['order_id'] for r in rows]
cursor = rows[-1]['updated_at']
if len(keyset) == 20:
change(1008, 'delivered', '2025-06-16 10:00:00') # a change mid-read again
print('keyset: read', len(keyset), 'rows,', len(set(keyset)), 'orders; never read:', sorted(set(range(1001, 1081)) - set(keyset)))
With offsets, order 1014 is never read and 1006 is read twice. The cursor version can read a changed row twice (it comes back with its new updated_at, which a merge absorbs), but it never skips one. This API filters on updated_at only. That is safe here because no two orders share an updated_at; a real cursor should include the id.
The API says slow down
APIs also limit how fast you may ask. Go over the limit and you get the status 429 Too Many Requests. It usually carries a Retry-After header: wait that long, then ask again.
With no Retry-After, wait longer after each failure: 1 second, then 2, then 4, up to a cap. That is exponential backoff: min(cap, base x 2^attempt). Add jitter, a random part, so a hundred workers do not all retry at the same instant.
Retry only what can succeed later: a 429, a 503, a timeout. Never a 400, 401 or 404. And cap the number of attempts.
A rate limit also decides how long a load must take. Do the sums before you promise a deadline: the bars below work one example.
One page, a rate limit, and a saved cursor
The loader asks the API for the next page, gets a 429 with Retry-After, waits, retries and gets the rows, merges them into the destination, and only then saves the new cursor.
Read it top to bottom. The red arrow is the 429: the loader waits, then sends the same request again. Look at the last two arrows: the rows are merged first, and only then is the cursor saved.
Minutes to pull 2 million records at 100 requests a minute
Bars show the minimum extract time for two million records under a limit of one hundred requests per minute, at page sizes of 100, 500 and 1,000 records.
Work the top bar out, one step at a time. 2,000,000 records / 100 per page = 20,000 requests. 20,000 requests / 100 a minute = 200 minutes, however many threads you run. At 1,000 per page it is 2,000 requests, so 20 minutes. Parallel workers share the same limit, so they cannot beat these bars: they only collect more 429s. An incremental cursor makes most nights a few requests.
Save your place after the data
The cursor is only safe if it never runs ahead of the data. Save it after each page is safely written. A crash in between means reading that page again, and the merge on the key makes that harmless.
Write a state file in one move: write state.json.tmp, then os.replace() it over the old file, so a crash never leaves half a file.
Best of all, keep the state in the destination, in the same transaction as the data. dlt stores it there, in a table called _dlt_pipeline_state, so data and cursor cannot disagree.
Remember: a cursor that is lost is a full reload. A cursor that is wrong is silent data loss. Save it last, and test it like code.
What dlt, Fivetran and Airbyte do for you
You have now written all five jobs by hand. The tools do the same five.
- dlt (data load tool) is an open-source Python library. You write a function that yields records. dlt infers the schema, unpacks nested JSON into child tables, loads with append, replace or merge, and keeps the state. It runs wherever your Python runs, such as an Airflow task.
- Fivetran is a paid, fully managed service with hundreds of ready connectors (Salesforce, Stripe, Postgres with log-based CDC). You set it up in a web page. It handles schema changes and retries, and charges by the rows that change each month.
- Airbyte is open source (or Airbyte Cloud), also built on connectors, with sync modes such as full refresh, incremental append, and incremental append + deduped.
The same load with dlt
Runs on your laptop:
import json
import dlt
@dlt.resource(name="events", primary_key="event_id", write_disposition="merge")
def events(cursor=dlt.sources.incremental("ts", initial_value="2025-06-01T00:00:00Z")):
with open("data/events.jsonl") as f:
for line in f:
yield json.loads(line)
pipeline = dlt.pipeline(
pipeline_name="swiftkart_events",
destination="duckdb",
dataset_name="raw",
)
load_info = pipeline.run(events())
print(load_info)
Pipeline swiftkart_events load step completed in 0.62 seconds
1 load package(s) were loaded to destination duckdb and into dataset raw
The duckdb destination used duckdb:////home/alex/swiftkart/swiftkart_events.duckdb location to store data
Load package 1749456000.123456 is LOADED and contains no failed jobs
Compare it with your loader: primary_key with write_disposition="merge" is job 4, and the incremental cursor on ts is job 5. dlt creates raw.events (with device__os and device__app_version) and a child table raw.events__items, linked by _dlt_parent_id and _dlt_list_idx. The next run keeps only events newer than the last ts it loaded (your function still reads the file; dlt drops the old records). To try it on a laptop: pip install "dlt[duckdb]".
Numbers to remember
| Name | Value | What it is |
|---|---|---|
| HTTP 429 Too Many Requests | RFC 6585 | Usually carries Retry-After, in seconds or as an HTTP date (RFC 9110) |
| Backoff | min(cap, base x 2^attempt) | AWS's "full jitter" sleeps a random time between 0 and that value |
| Worth retrying | 429, 503, timeouts | Never a 400, 401 or 404. Cap the attempts |
| Keyset cursor | (updatedat, id) | APIs call it startingafter or nextcursor |
| dlt destinations | DuckDB, Postgres, Snowflake, BigQuery, Databricks and more | The same pipeline code loads into any of them |
| dlt child tables | dltparentid, dltlistidx | Link a child row to its parent and keep its place in the list |
| dlt state | dltpipelinestate | A table in the destination, so data and cursor are stored together |
| dlt type hints | columns= | Pin the types you care about instead of trusting the first file |
| Build or buy? | managed connectors against code | Fivetran or Airbyte Cloud save weeks on standard SaaS sources, but cost money per row and give less control. Code (dlt, plain Python) fits in-house APIs and odd files, but you own retries, schema changes and state |
| A team of SwiftKart's size | Fivetran, dlt, Auto Loader | Fivetran for Stripe and the help desk, dlt inside an Airflow task for the store's own API, Databricks Auto Loader for event files in cloud storage. All three write raw tables; dbt (Module 8) takes it from there |
The first four rows are the API rules of this lesson in one place. The rest are names you will see in the tools.
What changed at SwiftKart
The one-off script is gone. The new loader pins price as a decimal, so the Hand Cream is $8.75 again. App events land as two tables, events and events__items, merged on their keys, with the loaded files remembered in a state file. The orders API is read with a cursor, backs off on a 429, and saves its place after every page.
Nora's plan for the sources still waiting: Fivetran for the standard ones, your own code for the store's API.
One promise from Lesson 6.5 is still open. Log-based CDC reads "the database's own log" through "a replication slot". Lesson 6.7 opens Postgres and shows you both.
In one line
A loader extracts, flattens objects into columns and lists into child tables, infers then pins a schema, merges on a key and saves its state last; dlt, Fivetran and Airbyte do the same at scale.
Interview corner
How do you load nested JSON into a warehouse?
Flatten nested objects into columns (device.os becomes device__os) and turn lists into child tables with the parent key and the element position, so the grain stays one row per parent. Load both with a merge on their keys. Some warehouses can also store the raw JSON in a VARIANT or JSONB column, which I keep in raw for replay.
Build or buy: when would you use Fivetran or Airbyte instead of writing code?
For standard SaaS sources (Salesforce, Stripe, a Postgres database) a managed connector is usually cheaper than my time: it handles pagination, retries, schema changes and state. For in-house APIs, odd file formats or tight cost control I write code, often with a library like dlt, and then I own retries, schema changes and monitoring.
Design an extractor for a REST API with 50 million records, a limit of 600 requests a minute and records that change during the extract.
Do the arithmetic first: at 1,000 records a page that is 50,000 requests, about 83 minutes at best, and parallel workers share the same limit. I would page with a cursor on a stable unique key, (updated_at, id), never offsets, because rows that change mid-read shift offset pages and get skipped. Each request retries only 429, 503 and timeouts, honouring Retry-After, otherwise exponential backoff with jitter and a capped number of attempts. After each page I merge the rows on the key and then save the cursor, ideally in the destination in the same transaction, so a crash rereads at most one page.
What state does an ingestion job need to keep, and where?
Whatever tells the next run where to start: a cursor value such as the highest updated_at, an API page token, or the list of files already loaded. It must live outside the job (a state table, the destination, the orchestrator) and be saved only after the data it describes is safely loaded.