Lab: Reverse ETL from a Mart to an Operational Tool
Push a high-value customer segment from a DuckDB mart into a mock CRM API: send only new and changed records, in batches that respect a rate limit, record every rejected record, survive a crash half-way through, and prove that a re-run creates no duplicates.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Build the mart and the segment
- Step 2: Start the mock CRM
- Step 3: Write the sync
- Step 4: Run the first sync and crash it
- Step 5: Resume after the crash
- Step 6: Run it again with nothing to do
- Step 7: Sync tomorrow's changes
- Step 8: Lose the state and prove the sync is idempotent
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Serving & BI
- Who Consumes Data and How It Reaches Them Concept · 20 min
- One Definition per Metric: Building a Semantic Layer Worked example · 25 min
- Lab: A Fast Dashboard That Respects Access Rules Lab · 30 min
- Lab: Reverse ETL from a Mart to an Operational Tool Lab · 25 min
- Low-Latency Serving: Caches, Data APIs and Real-Time OLAP Worked example · 20 min
- Check: Choose and Defend a Serving Path Knowledge check · 8 questions
What you will learn
- Implement a reverse ETL sync that pushes a modeled segment or score into an operational tool's API incrementally and idempotently, respecting rate limits and reporting rejected records.
01. Goal and setup
Most pipelines move data from operational systems into the warehouse. Reverse ETL moves modelled results the other way: from the warehouse into the tools that sales, support or marketing use every day, such as a CRM (customer relationship management system). A score or segment that only lives in a dashboard changes nothing; the same segment inside the CRM can drive a call list or an email campaign.
The destination is someone else's API, so the hard parts are not the SQL. The API limits how fast you can call it, rejects some records, and may be called again after your job crashes. In this lab you build a sync that handles all three. It sends only records that are new or have changed since the last run, in batches of 10, at no more than 4 requests a second. It writes every rejected record to a table that an owner can act on, and it uses each customer's warehouse id as the CRM's external id, so sending a record twice updates it instead of creating a copy.
You need Python 3.10 or later and curl. The lab was tested with Python 3.12, DuckDB 1.5.6 and requests 2.34.2. The CRM is a small mock server that you run yourself, so nothing leaves your machine.
mkdir retl-lab && cd retl-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "duckdb==1.5.6" "requests==2.34.2"retl-lab/
├── build_mart.py step 1: the mart and the high-value segment
├── mock_crm.py step 2: a CRM API with a rate limit and strict emails
├── sync.py step 3: the reverse ETL job
├── change_source.py step 7: tomorrow's changes in the mart
└── mart.duckdb created in step 1; the sync keeps its state here too02. Step 1: Build the mart and the segment
The mart holds one row per customer with a lifetime value. The segment is a view over it: customers worth 2,000 or more. Seeded random numbers give everyone the same 60 customers, and three of them have broken email addresses, as real data sometimes does.
"""Build mart.duckdb: lifetime value per customer, the same on every run."""
import random
import duckdb
rng = random.Random(11)
rows = []
for customer_id in range(1, 61):
email = f"customer{customer_id}@example.com"
if customer_id in (7, 23, 41):
email = email.replace("@", " at ") # three broken addresses
rows.append((customer_id, email, round(rng.uniform(50, 4000), 2)))
con = duckdb.connect("mart.duckdb")
con.execute("create or replace table customer_value"
"(customer_id int, email text, lifetime_value decimal(10, 2))")
con.executemany("insert into customer_value values (?, ?, ?)", rows)
con.execute("""
create or replace view high_value_segment as
select customer_id, email, lifetime_value from customer_value
where lifetime_value >= 2000
""")
print(con.sql("select count(*) as customers, count(*) filter "
"(where lifetime_value >= 2000) as high_value from customer_value"))python build_mart.py┌───────────┬────────────┐
│ customers │ high_value │
│ int64 │ int64 │
├───────────┼────────────┤
│ 60 │ 31 │
└───────────┴────────────┘03. Step 2: Start the mock CRM
The mock behaves like many SaaS APIs. A batch endpoint takes at most 10 contacts and upserts them by external_id: it creates a contact the first time and updates it afterwards, reporting created, updated or unchanged for each record. It rejects a record with an invalid email but still processes the rest of the batch. It allows 5 requests in any one second and answers 429 Too Many Requests with a Retry-After header above that. To make the lab repeatable, its third request is always throttled. Start it in a second terminal and leave it running.
"""A pretend CRM: batch upsert by external_id, 5 requests a second, strict emails."""
import json
import re
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
CONTACTS = {} # external_id -> properties
EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[a-z]{2,}$")
recent = [] # times of recent requests, for the rate limit
calls = 0
class Handler(BaseHTTPRequestHandler):
def reply(self, status, body, headers=None):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
for name, value in (headers or {}).items():
self.send_header(name, value)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/contacts/count":
return self.reply(200, {"count": len(CONTACTS)})
self.reply(404, {"error": "not found"})
def do_POST(self):
global calls
calls += 1
now = time.monotonic()
recent[:] = [t for t in recent if now - t < 1.0] + [now]
if len(recent) > 5 or calls == 3: # call 3 is always throttled
return self.reply(429, {"error": "rate limited"}, {"Retry-After": "1"})
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if len(body["contacts"]) > 10:
return self.reply(413, {"error": "at most 10 contacts per batch"})
results = []
for contact in body["contacts"]:
key, props = contact["external_id"], contact["properties"]
if not EMAIL.match(props.get("email", "")):
results.append({"external_id": key, "status": "rejected",
"error": "invalid email"})
continue
status = ("unchanged" if CONTACTS.get(key) == props
else "updated" if key in CONTACTS else "created")
CONTACTS[key] = props
results.append({"external_id": key, "status": status})
self.reply(200, {"results": results})
def log_message(self, *args):
pass
if __name__ == "__main__":
print("mock CRM on http://127.0.0.1:8766", flush=True)
ThreadingHTTPServer(("127.0.0.1", 8766), Handler).serve_forever()cd retl-lab && source .venv/bin/activate && python mock_crm.py
curl -s http://127.0.0.1:8766/contacts/count; echo{"count": 0}04. Step 3: Write the sync
Read sync.py from top to bottom before you run it. Four ideas carry the whole job.
- Diff against what was sent. For each contact the job computes a fingerprint, a SHA-256 hash of the exact payload, and compares it with the fingerprint stored in
sync_stateafter the last successful send. Only contacts whose fingerprint is new or different are sent. On a quiet day that is a handful of records, not the whole segment. - Throttle on your side, and obey the server.
post_batchwaits so that calls are at least a quarter of a second apart, below the CRM's limit. If the CRM still answers 429, or a 5xx error, it waits for theRetry-Aftervalue and tries again, at most five times. Any other 4xx answer means the request itself is wrong, so the job stops. - Keep per-record results. A rejected record is written to
sync_rejectionswith the CRM's reason, and its fingerprint is stored too. An unchanged bad record is therefore not sent and rejected again on every run, but once someone fixes it in the source, its fingerprint changes and it is sent again. - Save progress after every batch. The state is written as soon as a batch is answered, so a crash loses at most the batch in flight.
CRASH_AFTER_BATCHES exists only for this lab: it lets you stop the job half-way on purpose.
"""Reverse ETL: push the high-value segment to the CRM, changes only."""
import hashlib
import json
import os
import sys
import time
from collections import Counter
import duckdb
import requests
CRM = os.environ.get("CRM_URL", "http://127.0.0.1:8766")
BATCH_SIZE, MAX_PER_SECOND, MAX_ATTEMPTS = 10, 4, 5
CRASH_AFTER = int(os.environ.get("CRASH_AFTER_BATCHES", "0")) # lab only
con = duckdb.connect("mart.duckdb")
con.execute("""create table if not exists sync_state (
external_id text primary key, payload_hash text, status text)""")
con.execute("""create table if not exists sync_rejections (
external_id text, error text, rejected_at timestamp default current_timestamp)""")
def to_contact(row):
customer_id, email, lifetime_value = row
return {"external_id": f"cust-{customer_id}",
"properties": {"email": email, "lifetime_value": str(lifetime_value),
"segment": "high_value"}}
def fingerprint(contact):
return hashlib.sha256(json.dumps(contact, sort_keys=True).encode()).hexdigest()
last_call = 0.0
def post_batch(batch):
global last_call
for attempt in range(1, MAX_ATTEMPTS + 1):
time.sleep(max(0.0, last_call + 1 / MAX_PER_SECOND - time.monotonic()))
last_call = time.monotonic()
r = requests.post(f"{CRM}/contacts/batch_upsert",
json={"contacts": batch}, timeout=10)
if r.status_code == 429 or r.status_code >= 500:
delay = float(r.headers.get("Retry-After", 2 ** attempt))
print(f" HTTP {r.status_code}: waiting {delay:g} s, then retrying")
time.sleep(delay)
continue
r.raise_for_status() # 4xx: a bug, stop the run
return r.json()["results"]
raise RuntimeError(f"CRM still failing after {MAX_ATTEMPTS} attempts")
rows = con.sql("select * from high_value_segment order by customer_id").fetchall()
known = dict(con.sql("select external_id, payload_hash from sync_state").fetchall())
contacts = [to_contact(row) for row in rows]
changed = [c for c in contacts if known.get(c["external_id"]) != fingerprint(c)]
print(f"segment: {len(contacts)} contacts, {len(changed)} new or changed")
counts = Counter()
for number, start in enumerate(range(0, len(changed), BATCH_SIZE), start=1):
if CRASH_AFTER and number > CRASH_AFTER:
sys.exit(f"simulated crash before batch {number}")
batch = changed[start:start + BATCH_SIZE]
sent = {c["external_id"]: c for c in batch}
results = post_batch(batch)
statuses = Counter(r["status"] for r in results)
summary = ", ".join(f"{status} {n}" for status, n in sorted(statuses.items()))
print(f" batch {number}: {summary}")
counts.update(statuses)
for result in results:
key, status = result["external_id"], result["status"]
if status == "rejected":
con.execute("insert into sync_rejections (external_id, error) "
"values (?, ?)", [key, result["error"]])
con.execute("insert or replace into sync_state values (?, ?, ?)",
[key, fingerprint(sent[key]), status])
print("results:", dict(sorted(counts.items())))05. Step 4: Run the first sync and crash it
Run the sync with a simulated crash before its third batch, then count the contacts in the CRM.
CRASH_AFTER_BATCHES=2 python sync.py; echo "exit code: $?"
curl -s http://127.0.0.1:8766/contacts/count; echosegment: 31 contacts, 31 new or changed
batch 1: created 10
batch 2: created 9, rejected 1
simulated crash before batch 3
exit code: 1
{"count": 19}Twenty contacts were sent before the crash. Nineteen exist in the CRM, because one had an invalid email. The job exited with a non-zero code, which is what lets an orchestrator notice the failure and retry or alert.
06. Step 5: Resume after the crash
Run the same command without the crash. The job reads sync_state, sees which 20 contacts it already sent, and sends only the other 11. On the way it meets the scripted 429, waits the second that Retry-After asks for, and carries on.
python sync.py
curl -s http://127.0.0.1:8766/contacts/count; echosegment: 31 contacts, 11 new or changed
HTTP 429: waiting 1 s, then retrying
batch 1: created 10
batch 2: created 1
results: {'created': 11}
{"count": 30}Thirty of the 31 contacts are in the CRM. The missing one is in the rejections table, with the reason the CRM gave. In production, this table feeds a report or an alert to the owner of the source data, who can fix the address where it was entered.
python -c 'import duckdb; db = duckdb.connect("mart.duckdb")
print(db.sql("select external_id, error from sync_rejections"))'┌─────────────┬───────────────┐
│ external_id │ error │
│ varchar │ varchar │
├─────────────┼───────────────┤
│ cust-23 │ invalid email │
└─────────────┴───────────────┘07. Step 6: Run it again with nothing to do
A sync that runs every hour must cost almost nothing when nothing has changed. Run it once more.
python sync.pysegment: 31 contacts, 0 new or changed
results: {}08. Step 7: Sync tomorrow's changes
Tomorrow, customer 5's lifetime value changes and someone fixes customer 23's email address. Only those two fingerprints change, so only those two records are sent. Customer 23 is created, because the CRM never accepted it before; customer 5 is updated.
"""Simulate tomorrow's mart: one score changes and one email is fixed."""
import duckdb
con = duckdb.connect("mart.duckdb")
con.execute("update customer_value set lifetime_value = 3999.99 where customer_id = 5")
con.execute("update customer_value set email = '[email protected]' "
"where customer_id = 23")
print("changed customers 5 and 23")python change_source.py
python sync.pychanged customers 5 and 23
segment: 31 contacts, 2 new or changed
batch 1: created 1, updated 1
results: {'created': 1, 'updated': 1}09. Step 8: Lose the state and prove the sync is idempotent
State can be lost: a new environment, a restored backup, a deleted table. Without state the job sends every contact again. Because the CRM upserts by external id, that is safe. A sync is idempotent when running it again with the same input leaves the destination in the same state, and this one is.
python -c 'import duckdb
duckdb.connect("mart.duckdb").execute("drop table sync_state")'
python sync.py
curl -s http://127.0.0.1:8766/contacts/count; echosegment: 31 contacts, 31 new or changed
batch 1: unchanged 10
batch 2: unchanged 10
batch 3: unchanged 10
batch 4: unchanged 1
results: {'unchanged': 31}
{"count": 31}Every record came back unchanged and the count stayed at 31. With an API that only offers "create contact", the same run would have made 31 duplicates. Choose a destination endpoint that upserts on an id you control before you write any sync code, and store that id in the CRM.
Reverse ETL tools describe this choice as a sync mode. An upsert mode creates and updates; an update-only mode never creates; a mirror mode also removes destination records that left the segment. This sync never removes anyone: a customer who drops out of the segment keeps segment = high_value in the CRM until something clears it. Decide which behaviour the business needs, and remember that a segment is personal data: send only the fields the tool needs. Stop the CRM with Ctrl+C when you have finished.
10. Check your understanding
11. Apply it
This is the reverse ETL part of the skill practice. Point the sync at the high-value segment of your own mart and the mock CRM, then extend it:
- Add a mirror step: contacts in
sync_statethat are no longer in the segment get one update that clears their segment, and are then removed from the state. - Accept a
Retry-Aftervalue written as an HTTP date as well as a number of seconds, as RFC 9110 allows. - Write a short run summary (sent, created, updated, unchanged, rejected, retries) to a table, and alert when rejections exceed 1% of the batch.
- Run the job twice in a row in CI against the mock and assert that the second run sends nothing.
12. Review prompt
Without looking back, explain: what reverse ETL is and why it needs a different design from loading a warehouse; how the fingerprint diff keeps each run small; why the job throttles itself and also obeys Retry-After; why per-record rejections are stored instead of failing the batch; and why an upsert on an external id makes a crashed or repeated run safe.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.