Education › Forward Deployed › Stage 1: The role & engineering foundations

Python for fast, reliable delivery

Scripts, CLIs and small services you can hand over: environments, typing, HTTP clients, retries, config and packaging.

Beginner ~40 min read Module 3 of 20

Most FDE code is not a grand system; it is the glue that makes a customer's world work with yours: a script that pulls records nightly, a CLI that validates their data, a small service that exposes an internal system to an AI agent. That code has to be written fast, run reliably on machines you do not control, and be handed to someone else. This lesson covers the Python habits that make that possible: reproducible environments, configuration from the environment, HTTP clients that behave behind proxies, retries and idempotency, logs someone else can read, tests, and packaging that installs cleanly.

After this module you can
  • Create reproducible Python projects with locked dependencies
  • Load configuration and secrets from the environment, never from code
  • Write HTTP clients with timeouts, retries with backoff, and proxy and CA support
  • Produce structured logs and clear errors that a customer team can act on
  • Test and package a tool so it installs and runs the same everywhere

Reproducible environments

"It works on my machine" is fatal at a customer site. Every project gets a pyproject.toml, a lock file and a pinned Python version. Tools such as uv create the virtual environment, resolve and lock dependencies, and run commands inside the environment in one step; pip with a requirements file and hashes works too. What matters is that a colleague or the customer can rebuild exactly what you ran.

A new tool project with locked dependencies
bash
uv init claims-sync && cd claims-sync
uv add httpx
uv add --dev pytest ruff
uv run python -c "import httpx; print(httpx.__version__)"
uv lock   # commit pyproject.toml and uv.lock together
  • Pin the Python version you test on; customers' servers often have older system Pythons, which is one reason to ship a container or a self-contained environment.
  • Keep dependencies few. Every package is something the customer's security team may ask about.
  • Run a formatter and linter (ruff) and type hints from the first commit; code you hand over should look intentional.

Configuration from the environment

The same code must run on your laptop, the customer's staging server and production, against different URLs and credentials. Follow the twelve-factor rule: configuration comes from environment variables (or files mounted by the platform), with validation at start-up so a missing value fails immediately and clearly, not on the first nightly run.

Typed configuration with early, readable failure
python
import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    api_url: str
    api_token: str
    batch_size: int = 500
    timeout_s: float = 30.0


def load_config() -> Config:
    missing = [k for k in ("CLAIMS_API_URL", "CLAIMS_API_TOKEN") if not os.environ.get(k)]
    if missing:
        raise SystemExit(f"missing required environment variables: {', '.join(missing)}")
    return Config(
        api_url=os.environ["CLAIMS_API_URL"].rstrip("/"),
        api_token=os.environ["CLAIMS_API_TOKEN"],
        batch_size=int(os.environ.get("CLAIMS_BATCH_SIZE", "500")),
        timeout_s=float(os.environ.get("CLAIMS_TIMEOUT_S", "30")),
    )
Watch out

Never commit tokens, never print them, and never put them in command-line arguments (they show up in process lists and shell history). Read them from the environment or a secrets file the platform mounts.

HTTP clients that survive enterprise networks

Calls to customer APIs fail in ordinary ways: timeouts, 429 rate limits, 502s from a load balancer during a deploy. Your client must set timeouts, retry the failures that are safe to retry with exponential backoff and jitter, and give up with a clear error. It must also honour the customer's proxy and private certificate authority: httpx reads HTTPS_PROXY, NO_PROXY and SSL_CERT_FILE from the environment by default.

Timeouts, bounded retries with backoff, and only safe retries
python
import random
import time

import httpx

RETRYABLE = {429, 500, 502, 503, 504}


def get_json(client: httpx.Client, path: str, attempts: int = 5) -> dict:
    for attempt in range(1, attempts + 1):
        try:
            r = client.get(path)
            if r.status_code not in RETRYABLE:
                r.raise_for_status()
                return r.json()
            reason = f"HTTP {r.status_code}"
        except (httpx.TimeoutException, httpx.TransportError) as exc:
            reason = type(exc).__name__
        if attempt == attempts:
            raise RuntimeError(f"GET {path} failed after {attempts} attempts: {reason}")
        time.sleep(min(30, 2 ** attempt) * random.uniform(0.5, 1.0))


client = httpx.Client(base_url="https://claims.internal.example",
                      headers={"Authorization": "Bearer TOKEN_FROM_ENV"},
                      timeout=httpx.Timeout(30.0, connect=5.0))

Retrying a GET is safe. Retrying a POST that creates a record can create it twice. Make writes idempotent: send an idempotency key the server deduplicates on, or upsert by a natural key, so a retry after a timeout does no harm. The integration lesson goes deeper.

Logs and errors for someone else

The person reading your logs at 3 a.m. may be the customer's operator who has never seen your code. Log one event per line, with a timestamp, a level, what happened, and identifiers (batch, record count, request ID), and avoid logging personal data or secrets. JSON lines are easy for any log system to parse.

One JSON object per log line
python
import json
import logging
import sys


class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = {"ts": self.formatTime(record), "level": record.levelname,
                   "msg": record.getMessage(), **getattr(record, "ctx", {})}
        return json.dumps(payload)


handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("claims_sync")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("batch synced", extra={"ctx": {"batch": 12, "records": 500, "seconds": 4.2}})
  • Exit with a non-zero status on failure so schedulers and monitoring notice.
  • Write error messages that say what to do: "CLAIMS_API_TOKEN expired or invalid (HTTP 401): rotate it in the vault", not a stack trace alone.
  • Add a --dry-run flag to anything that writes: customers love being able to see what would change first.

Tests and packaging for handover

You do not need exhaustive tests for a pilot, but you need enough that the next person can change the code without fear: unit tests for parsing and transformation logic, and a test that runs the client against a fake server. httpx's MockTransport lets you test retry logic without a network.

Testing retries with a fake transport
python
import httpx

from claims_sync.client import get_json


def test_retries_then_succeeds(monkeypatch):
    monkeypatch.setattr("time.sleep", lambda s: None)
    calls = {"n": 0}

    def handler(request):
        calls["n"] += 1
        if calls["n"] < 3:
            return httpx.Response(503)
        return httpx.Response(200, json={"ok": True})

    client = httpx.Client(base_url="https://x", transport=httpx.MockTransport(handler))
    assert get_json(client, "/health") == {"ok": True}
    assert calls["n"] == 3

Package the tool so it installs one way everywhere: a wheel with a console-script entry point for Python environments, or, more often at customer sites, a container image with the Python version and dependencies baked in. Include a README with prerequisites, configuration variables, how to run, how to test, and how to roll back.

Hands-on practice

Build a handover-ready sync tool

  1. Create a project with uv (or pip and a lock file) named claims-sync with httpx, pytest and ruff.
  2. Implement load_config() from this lesson and make the tool exit with a clear message when a variable is missing.
  3. Point the client at a public test API (or a local FastAPI stub you write) and fetch paginated JSON into a local SQLite table, upserting by ID.
  4. Add the retry function and prove it works with the MockTransport test, including the give-up case.
  5. Emit JSON logs with batch and record counts, and add a --dry-run flag that prints what would be written.
  6. Write a README covering configuration, running, testing and rollback, then build a container image and run the tool from it.
Cheat sheet

Python for fast, reliable delivery — at a glance

Main things to focus on

  • Lock dependencies and pin Python: someone else must rebuild exactly what you ran.
  • Configuration and secrets from the environment, validated at start-up.
  • Timeouts always; retry only safe failures, with backoff and jitter.
  • Make writes idempotent so retries cannot duplicate data.
  • JSON logs with identifiers, no secrets or personal data, non-zero exit on failure.
  • Ship with tests, a README and a container image.

Project setup (uv)

uv init NAMENew project with pyproject.toml
uv add PKG / uv add --dev PKGAdd runtime / development dependency
uv run CMDRun inside the project environment
uv lock / uv syncWrite the lock file / install from it
uv buildBuild a wheel and sdist

httpx

httpx.Client(base_url=, headers=, timeout=)Reusable client with defaults
httpx.Timeout(30.0, connect=5.0)Overall and connect timeouts
HTTPS_PROXY / NO_PROXY / SSL_CERT_FILEProxy and CA from the environment
httpx.MockTransport(handler)Fake server for tests

Reliability patterns

retry on 429, 5xx, timeoutsNot on 400, 401, 403, 404
sleep = min(cap, 2**attempt) x jitterExponential backoff with jitter
Idempotency-Key header / upsert by keySafe retries for writes
--dry-runShow changes without writing

Quality

ruff check . && ruff format .Lint and format
pytest -qRun tests
sys.exit(1) on failureLet schedulers detect errors

Common pitfalls

  • Relying on the customer's system Python and whatever packages it has.
  • Hard-coded URLs and tokens, or tokens passed as command-line arguments.
  • No timeouts, so one hung connection stalls a nightly job forever.
  • Retrying non-idempotent POSTs and creating duplicates.
  • Logs full of stack traces and personal data but no record counts or IDs.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →