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 2 of 6 · Lab · 30 min · revision 2

Lab: A Python Extractor That Survives Flaky APIs

Run a local orders API that fails on purpose, watch a naive extractor crash, then build one with timeouts, retries with exponential backoff and jitter, Retry-After handling, a client-side rate limit and cursor pagination that lands the raw data safely.

Contentsand lesson path

What you will learn

  • Extract from REST APIs and databases in Python with pagination, retries with backoff and rate limits, and bulk-load the results (COPY or batched inserts).

Prerequisites: Data Handling, SQL Fundamentals

01. Goal and setup

Real APIs fail in ordinary ways. A deploy returns 503 Service Unavailable for a few seconds, a busy server answers 429 Too Many Requests, and a slow response leaves your program waiting. An extractor, the code that pulls data out of a source, must survive these: if it treats each as fatal, the nightly job fails; if it retries carelessly, it hammers a struggling server.

In this lab you run a small orders API locally. It serves 230 orders in pages of 50 and fails on purpose, always the same way: page 2 fails once with 503, page 3 fails twice with 429, and page 4 is too slow the first time. You will watch a naive extractor crash, then build one that finishes and lands complete data.

You need Python 3.10 or later and curl. The lab was tested with Python 3.12, requests 2.34.2 and DuckDB 1.5.6. Create the project folder, a virtual environment and the three settings that the scripts read from the environment. The token is a secret, so it lives in the environment, not in the code; in production it would come from a secret store.

Terminal 1
mkdir extractor-lab && cd extractor-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "requests==2.34.2" "duckdb==1.5.6"
export API_BASE_URL=http://127.0.0.1:8765 API_TOKEN=lab-token RUN_DATE=2026-11-02
Folder layout at the end of the lab
extractor-lab/
├── mock_api.py      step 2: the flaky orders API
├── naive.py         step 3: an extractor with no error handling
├── extract.py       step 4: the robust extractor
├── check.py         step 6: checks the landed file with DuckDB
└── raw/orders/ingest_date=2026-11-02/orders.jsonl   written in step 5

02. Step 1: Know which failures are worth retrying

Sort failures into two groups. A transient failure is one that may succeed if you simply try again later: a timeout, a dropped connection, 429, or a 5xx status such as 500, 502, 503 and 504. A permanent failure will fail the same way every time: 400 Bad Request, 401 Unauthorized, 403 Forbidden or 404 Not Found. Retrying a permanent failure only wastes time and hides the real problem, such as an expired token.

For transient failures, wait before the next attempt, and wait longer each time. This is exponential backoff: 0.5 s, then 1 s, 2 s, 4 s, up to a cap. Add jitter, a random part of the wait, so that clients that failed together do not all retry together and knock the server over again. With full jitter, each wait is a random value between zero and the current cap. When the server sends a Retry-After header, it is telling you how long to wait, so use that value instead of your own guess. RFC 9110 allows it as a number of seconds or as an HTTP date; the code below handles the seconds form that this API sends, and email.utils.parsedate_to_datetime would read a date. Finally, always set a timeout. Without one, requests can wait for a response indefinitely, and a single stuck connection stalls the whole job.

03. Step 2: Start the flaky API

Save the server below as mock_api.py. Seeded random numbers give everyone the same 230 orders. Pagination uses a cursor: each response carries a next_cursor token that encodes the last order id returned, and the client sends it back to get the next page. With ?offset=100 instead, a row inserted near the start of a list pushes every later row down one place, so the next page repeats a row you already have, and a delete makes you skip one. A cursor points at a position in the data, not at a count, so pages stay stable. The FAILURES dictionary scripts the failures by page and attempt number.

Python · mock_api.py
"""A small orders API with scripted failures, for the extractor lab."""
import base64
import json
import os
import random
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

TOKEN = os.environ.get("API_TOKEN", "lab-token")
rng = random.Random(42)
ORDERS = [
    {"order_id": i, "customer_id": rng.randint(1, 40),
     "amount": round(rng.uniform(5, 300), 2),
     "status": rng.choice(["paid", "refunded"])}
    for i in range(1, 231)
]
# (page number, attempt) -> failure. Each page fails only on the attempts listed.
FAILURES = {(2, 1): 503, (3, 1): 429, (3, 2): 429, (4, 1): "slow"}
attempts = {}


def encode(order_id):
    return base64.urlsafe_b64encode(str(order_id).encode()).decode()


class Handler(BaseHTTPRequestHandler):
    def send_json(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):
        url = urlparse(self.path)
        if url.path != "/orders":
            return self.send_json(404, {"error": "not found"})
        if self.headers.get("Authorization") != f"Bearer {TOKEN}":
            return self.send_json(401, {"error": "invalid token"})
        query = parse_qs(url.query)
        limit = min(int(query.get("limit", ["50"])[0]), 100)
        cursor = query.get("cursor", [None])[0]
        after = int(base64.urlsafe_b64decode(cursor)) if cursor else 0
        page = after // limit + 1
        attempt = attempts[page] = attempts.get(page, 0) + 1
        failure = FAILURES.get((page, attempt))
        print(f"GET page={page} attempt={attempt} -> {failure or 200}", flush=True)
        if failure == 503:
            return self.send_json(503, {"error": "temporarily unavailable"})
        if failure == 429:
            return self.send_json(429, {"error": "slow down"}, {"Retry-After": "1"})
        if failure == "slow":
            time.sleep(3)
        rows = [o for o in ORDERS if o["order_id"] > after][:limit]
        more = rows and rows[-1]["order_id"] < ORDERS[-1]["order_id"]
        next_cursor = encode(rows[-1]["order_id"]) if more else None
        self.send_json(200, {"data": rows, "next_cursor": next_cursor})

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    print("mock API on http://127.0.0.1:8765", flush=True)
    ThreadingHTTPServer(("127.0.0.1", 8765), Handler).serve_forever()

Start it in a second terminal (with the virtual environment active) and leave it running. Then fetch two orders from the first terminal.

Terminal 2, then terminal 1
python mock_api.py

curl -s -H "Authorization: Bearer $API_TOKEN" "$API_BASE_URL/orders?limit=2" \
  | python -m json.tool
Expected output
{
    "data": [
        {
            "order_id": 1,
            "customer_id": 8,
            "amount": 12.38,
            "status": "refunded"
        },
        {
            "order_id": 2,
            "customer_id": 16,
            "amount": 70.85,
            "status": "paid"
        }
    ],
    "next_cursor": "Mg=="
}

04. Step 3: Watch a naive extractor fail

Save this extractor as naive.py. It follows the cursor correctly but has no timeout and no retries: the first non-200 response raises an exception.

Python · naive.py
import os

import requests

BASE = os.environ["API_BASE_URL"]
HEADERS = {"Authorization": f"Bearer {os.environ['API_TOKEN']}"}

rows, cursor, page = [], None, 0
while True:
    params = {"limit": 50, **({"cursor": cursor} if cursor else {})}
    response = requests.get(f"{BASE}/orders", params=params, headers=HEADERS)
    response.raise_for_status()
    body = response.json()
    rows.extend(body["data"])
    page += 1
    print(f"page {page}: total {len(rows)} rows")
    cursor = body["next_cursor"]
    if cursor is None:
        break
Terminal 1
python naive.py 2>&1 | grep -v '^ ' | fold -w 80
Expected output
page 1: total 50 rows
Traceback (most recent call last):
requests.exceptions.HTTPError: 503 Server Error: Service Unavailable for url: ht
tp://127.0.0.1:8765/orders?limit=50&cursor=NTA%3D

(grep hides the indented traceback lines; fold wraps the last one.) One brief 503 on page 2 killed the run, and the 50 rows already fetched were lost because they were only in memory.

05. Step 4: Write the robust extractor

Save the next two blocks together as one file, extract.py. The first part holds the settings and the retry logic. RETRYABLE lists the transient status codes. RateLimiter is a client-side rate limit: it makes sure at least 0.2 s passes between requests, so the extractor never sends more than five requests per second even when the server is fast. timeout=(3, 2) allows 3 s to connect and 2 s between bytes of the response. The random generator for jitter is seeded only so that your log matches the one below; in a real job, leave it unseeded.

Python · extract.py (part 1 of 2)
"""Extract every order from the API into the raw landing area, as received."""
import json
import os
import random
import sys
import time
from pathlib import Path

import requests

BASE = os.environ["API_BASE_URL"]
TOKEN = os.environ["API_TOKEN"]          # a secret: from the environment, never in code
RUN_DATE = os.environ["RUN_DATE"]        # the logical date this run is for
RETRYABLE = {429, 500, 502, 503, 504}
MAX_ATTEMPTS = 5
MIN_INTERVAL = 0.2                       # client-side rate limit: at most 5 requests/s
jitter = random.Random(7)                # seeded only so the lab output is repeatable


def log(event, **fields):
    print(json.dumps({"event": event, **fields}), file=sys.stderr, flush=True)


class RateLimiter:
    def __init__(self, min_interval):
        self.min_interval, self.last = min_interval, 0.0

    def wait(self):
        pause = self.last + self.min_interval - time.monotonic()
        if pause > 0:
            time.sleep(pause)
        self.last = time.monotonic()


def backoff_delay(attempt, response):
    """Seconds to wait before the next attempt."""
    if response is not None and "Retry-After" in response.headers:
        return float(response.headers["Retry-After"])   # seconds form only
    cap = min(8.0, 0.5 * 2 ** (attempt - 1))             # 0.5, 1, 2, 4, 8 ...
    return jitter.uniform(0, cap)                         # "full jitter"


def get_page(session, limiter, params):
    for attempt in range(1, MAX_ATTEMPTS + 1):
        limiter.wait()
        response, reason = None, None
        try:
            response = session.get(f"{BASE}/orders", params=params, timeout=(3, 2))
        except (requests.ConnectionError, requests.Timeout) as exc:
            reason = type(exc).__name__
        else:
            if response.status_code == 200:
                return response.json()
            if response.status_code not in RETRYABLE:
                response.raise_for_status()               # 401, 404 ...: fail fast
            reason = response.status_code
        if attempt == MAX_ATTEMPTS:
            raise RuntimeError(f"giving up after {attempt} attempts: {reason}")
        delay = backoff_delay(attempt, response)
        log("retry", attempt=attempt, reason=reason, wait_ms=round(delay * 1000))
        time.sleep(delay)

The second part follows the cursor until the API returns next_cursor: null. Each record is written exactly as received, one JSON object per line, into a folder named after the logical run date (RUN_DATE), not the date on the clock. That way a re-run of 2 November writes to the 2 November folder even if it runs on 3 November. The rows go to a .tmp file first, which is deleted if the run fails, and the file is renamed only after the last page. A rename within one file system is atomic on Linux and macOS, so downstream jobs see either the old complete file or the new complete file, never half of one. Each log line is a JSON object, easy to search in a log system.

Python · extract.py (part 2 of 2)

def main():
    session = requests.Session()
    session.headers["Authorization"] = f"Bearer {TOKEN}"
    limiter = RateLimiter(MIN_INTERVAL)
    out_dir = Path("raw/orders") / f"ingest_date={RUN_DATE}"
    out_dir.mkdir(parents=True, exist_ok=True)
    tmp = out_dir / "orders.jsonl.tmp"
    pages, rows, cursor = 0, 0, None
    try:
        with tmp.open("w") as out:
            while True:
                params = {"limit": 50, **({"cursor": cursor} if cursor else {})}
                body = get_page(session, limiter, params)
                pages += 1
                rows += len(body["data"])
                for record in body["data"]:
                    out.write(json.dumps(record) + "\n")
                log("page", page=pages, rows=len(body["data"]), total=rows)
                cursor = body["next_cursor"]
                if cursor is None:
                    break
    except BaseException:
        tmp.unlink(missing_ok=True)         # a failed run leaves no partial file
        raise
    tmp.rename(out_dir / "orders.jsonl")    # publish the file only when complete
    log("done", rows=rows, path=str(out_dir / "orders.jsonl"))


if __name__ == "__main__":
    main()

06. Step 5: Run it against the same failures

The API counts attempts per page since it started, so restart it to replay the failures from the beginning: press Ctrl+C in terminal 2 and run python mock_api.py again. Then run the extractor. The logs go to standard error, which the terminal shows as normal.

Terminal 1
python extract.py
Expected output
{"event": "page", "page": 1, "rows": 50, "total": 50}
{"event": "retry", "attempt": 1, "reason": 503, "wait_ms": 162}
{"event": "page", "page": 2, "rows": 50, "total": 100}
{"event": "retry", "attempt": 1, "reason": 429, "wait_ms": 1000}
{"event": "retry", "attempt": 2, "reason": 429, "wait_ms": 1000}
{"event": "page", "page": 3, "rows": 50, "total": 150}
{"event": "retry", "attempt": 1, "reason": "ReadTimeout", "wait_ms": 75}
{"event": "page", "page": 4, "rows": 50, "total": 200}
{"event": "page", "page": 5, "rows": 30, "total": 230}
{"event": "done", "rows": 230, "path": "raw/orders/ingest_date=2026-11-02/orders.jsonl"}
Expected output (terminal 2, after the start-up line)
GET page=1 attempt=1 -> 200
GET page=2 attempt=1 -> 503
GET page=2 attempt=2 -> 200
GET page=3 attempt=1 -> 429
GET page=3 attempt=2 -> 429
GET page=3 attempt=3 -> 200
GET page=4 attempt=1 -> slow
GET page=4 attempt=2 -> 200
GET page=5 attempt=1 -> 200

The 503 on page 2 was retried after a random 162 ms. Both 429 responses carried Retry-After: 1, so the extractor waited exactly 1000 ms each time instead of using its own backoff. On page 4 the server took 3 s, longer than the 2 s read timeout, so requests raised ReadTimeout and the extractor retried. Each retry reused the same cursor, so no page was skipped or read twice.

07. Step 6: Check the landed data and re-run

Exit code 0 does not prove completeness. Save check.py, which uses DuckDB to read the landed file and count rows and distinct ids. The hive_partitioning option turns the ingest_date=2026-11-02 folder name into a column you could filter on.

Python · check.py
import duckdb

print(duckdb.sql("""
    SELECT count(*) AS rows, count(DISTINCT order_id) AS ids,
           min(order_id) AS first_id, max(order_id) AS last_id,
           round(sum(amount), 2) AS total_amount
    FROM read_json('raw/orders/*/orders.jsonl', hive_partitioning = true)
"""))
Terminal 1
python check.py
sha256sum raw/orders/ingest_date=2026-11-02/orders.jsonl | cut -c1-16
ls raw/orders/ingest_date=2026-11-02
Expected output
┌───────┬───────┬──────────┬─────────┬──────────────┐
│ rows  │  ids  │ first_id │ last_id │ total_amount │
│ int64 │ int64 │  int64   │  int64  │    double    │
├───────┼───────┼──────────┼─────────┼──────────────┤
│   230 │   230 │        1 │     230 │      34877.9 │
└───────┴───────┴──────────┴─────────┴──────────────┘

b00cacb86d438c9c
orders.jsonl

All 230 ids arrived exactly once, and no .tmp file is left behind. (On macOS, use shasum -a 256.) Now restart the API again, run python extract.py a second time, and print the checksum. It is identical, because a re-run for the same RUN_DATE replaces the file with the same content instead of appending to it. Getting the same result however often you run it is called idempotency; later lessons build on it.

Expected output (checksum after the second run)
b00cacb86d438c9c

08. Step 7: Fail fast on a permanent error

Run the extractor with a wrong token. The API answers 401, which is not in RETRYABLE, so raise_for_status() stops the run at once, with no retry lines in the log. That is what you want: no amount of waiting fixes a bad credential, and a fast, clear failure pages the right person sooner.

Terminal 1
API_TOKEN=wrong python extract.py 2>&1 | tail -n 1 | fold -w 80
Expected output
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: http://12
7.0.0.1:8765/orders?limit=50

Stop the API with Ctrl+C. Libraries such as tenacity, or the retry support in urllib3, offer the same retry policy as configuration, and connector frameworks such as dlt add pagination helpers on top. You still decide which errors are transient, how long to wait and when to give up.

09. Check your understanding

Practice check · 3 questions

Retries, limits and failures

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

Q1. You change `MAX_ATTEMPTS` to 2, restart the API and run `python extract.py`. What happens when it reaches page 3?
Q2. You change the request to `timeout=(3, 5)` and restart the API. Page 4 still takes 3 s on its first attempt. What does the log show for page 4?
Q3. Which response should make an extractor stop at once instead of retrying?
Practice only: not graded, not saved, not evidence.

10. Apply it

This extractor is the first half of the skill practice. Point it at a public paginated API, or keep the mock and add more failures to FAILURES, including one page that fails six times. Then extend it:

  • Write each run to raw/<source>/ingest_date=<RUN_DATE>/ and record, in a small JSON manifest next to the file, the row count and the time the run finished.
  • Add an updated_since parameter so a run can ask only for recent changes; the lesson on watermarks shows how to choose its value.
  • Make the retry settings (MAX_ATTEMPTS, the backoff cap, the rate limit) environment variables with safe defaults, and log them at start-up.

11. Review prompt

Without looking back, explain to a colleague: which HTTP responses and exceptions you retry and which you do not, and why; how exponential backoff, jitter and Retry-After work together; why the extractor needs a timeout and a client-side rate limit; and why the file is written to .tmp and renamed at the end.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

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