Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

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

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.

Terminal 1
mkdir retl-lab && cd retl-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "duckdb==1.5.6" "requests==2.34.2"
Folder layout at the end of the lab
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 too

02. 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.

Python · build_mart.py
"""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"))
Terminal 1
python build_mart.py
Expected output
┌───────────┬────────────┐
│ 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.

Python · mock_crm.py
"""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()
Terminal 2, then terminal 1
cd retl-lab && source .venv/bin/activate && python mock_crm.py

curl -s http://127.0.0.1:8766/contacts/count; echo
Expected output
{"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_state after 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_batch waits 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 the Retry-After value 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_rejections with 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.

Python · sync.py
"""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.

Terminal 1
CRASH_AFTER_BATCHES=2 python sync.py; echo "exit code: $?"
curl -s http://127.0.0.1:8766/contacts/count; echo
Expected output
segment: 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.

Terminal 1
python sync.py
curl -s http://127.0.0.1:8766/contacts/count; echo
Expected output
segment: 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.

Terminal 1
python -c 'import duckdb; db = duckdb.connect("mart.duckdb")
print(db.sql("select external_id, error from sync_rejections"))'
Expected output
┌─────────────┬───────────────┐
│ 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.

Terminal 1
python sync.py
Expected output
segment: 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.

Python · change_source.py
"""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")
Terminal 1
python change_source.py
python sync.py
Expected output
changed 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.

Terminal 1
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; echo
Expected output
segment: 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

Practice check · 3 questions

Batches, state and segments

Each question changes one detail of the lab. Pick the best answer.

Q1. You set `BATCH_SIZE` to 25, delete `mart.duckdb`, run `build_mart.py` and restart the CRM. What happens on the first request?
Q2. Tomorrow customer 12's lifetime value falls to 1,500, so it leaves the segment. What does this sync do about its CRM contact?
Q3. Why does `sync.py` also store the fingerprint of a record that the CRM rejected?
Practice only: not graded, not saved, not evidence.

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_state that are no longer in the segment get one update that clears their segment, and are then removed from the state.
  • Accept a Retry-After value 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check