Python ETL Engineering for Production
Consider a hypothetical nightly job that loads a partner’s order file into a database. At 02:10 its log says loaded 3 rows. At 02:11 the node running it is drained and the process is stopped. At 07:00 an operator reads the log and has to decide whether to run the batch again. The log line was written by the process, so it shows what the process believed at 02:10, not what the database holds. Running the job again might double the batch. Not running it might leave a hole.
The transformation and the SQL do not settle this. The code around them does: how a unit of work is named, where the record of its completion lives, what the process reports when it ends, and what it does when it is interrupted. The job in this article is one command that takes one delivery file and applies it in one transaction, and its events let an operator answer the 07:00 question with a query. The destination is SQLite and everything else is standard-library Python 3.12, so the whole job runs on a laptop. A warehouse has a different engine and different error messages; the questions the design answers are the same.
The example input is a three-row CSV written for this article; order IDs, customer IDs, and amounts are synthetic. Packaging, typed parsing, and tests for a Python data job are the subject of Python for Data Engineers, and configuration layering and dependency injection of Designing Maintainable Data Workflows; both are assumed here. Building Incremental and Idempotent Pipelines describes the ledger idea in prose. The job below implements it and exercises the failure windows around it.
Three identifiers: batch, run, attempt
The job takes a batch ID, and a batch ID names a logical unit of data that must take effect once. For a file delivery it comes from the delivery. For a scheduled interval it comes from the data interval. It never comes from the clock at the moment the process starts. A run ID names one execution of the process; the orchestrator can pass its own identifier or the process can generate one. An attempt number counts tries inside one run. The three answer different questions.
| Identifier | Assigned by | Stays the same across | Question it answers |
|---|---|---|---|
batch_id | The delivery or the schedule, passed to the command | Every retry of the same data, in any process | Which unit of data is this, and has it already taken effect? |
run_id | The orchestrator, or the process at startup | One process | Which execution wrote this log line or this ledger row? |
attempt | The retry loop inside the process | One run | Which try within this execution? |
Each identifier fails in a specific way if it is merged with another. If the batch ID were generated per process, a retry after a crash would look like new work, and nothing in the destination could tell that the data is already there. If the run ID served as the batch ID, a log query could not group the executions that belong to one delivery. The attempt number is separate because a process that retries a lost connection inside its own run is a different operational event from an orchestrator starting a new process.
A batch ID alone does not say which bytes it covers. A partner can resend a corrected file under the same name. The job therefore records a SHA-256 fingerprint of the input next to the batch ID. The same batch ID with the same fingerprint is a retry. The same batch ID with a different fingerprint is a different request that happens to share a name, and the job refuses it. A corrected delivery is new intent, not a retry, as Building Incremental and Idempotent Pipelines argues.
The command line is the whole interface of the job. The first run of a delivery looks like this:
python3 etl_job.py --batch-id delivery-42 --input data/orders_42.csv --db wh.db --run-id run-17
The options are the job’s whole input, and a usage error exits with status 2 before any work starts:
usage: etl_job.py [-h] --batch-id BATCH_ID --input INPUT --db DB
[--run-id RUN_ID] [--max-rejects MAX_REJECTS]
[--max-attempts MAX_ATTEMPTS] [--busy-timeout BUSY_TIMEOUT]
Load one delivery file as one batch.
options:
-h, --help show this help message and exit
--batch-id BATCH_ID
--input INPUT
--db DB
--run-id RUN_ID
--max-rejects MAX_REJECTS
--max-attempts MAX_ATTEMPTS
--busy-timeout BUSY_TIMEOUT
The run prints one JSON object per line on standard output and exits with status 0:
{"ts":"2026-10-04T22:52:46.968+00:00","level":"INFO","event":"batch_start","schema_version":1,"run_id":"run-17","batch_id":"delivery-42"}
{"ts":"2026-10-04T22:52:46.968+00:00","level":"INFO","event":"batch_validated","schema_version":1,"run_id":"run-17","batch_id":"delivery-42","rows_read":3,"rows_rejected":0,"rows_candidate":3,"input_sha256":"75353b4a82cd81a997b3f05fc7d2fb4be0b4dddd761a751d09aa065887471a0c"}
{"ts":"2026-10-04T22:52:46.970+00:00","level":"INFO","event":"batch_end","schema_version":1,"run_id":"run-17","batch_id":"delivery-42","status":"committed","attempt":1,"exit_code":0,"rows_written":3,"elapsed_s":0.002}
The three events are the start, the result of validating the file (three data lines read, none rejected, three candidates for commit, plus the file fingerprint), and the end: status committed on attempt 1 with 3 rows written. Later listings drop ts, level, schema_version, and input_sha256 to fit the page; the job still emits them.
Commit the data and its record in one transaction
The ledger in this job is a table in the same database as the data. The three tables are created if missing whenever the store opens:
DDL = """
CREATE TABLE IF NOT EXISTS orders(order_id TEXT PRIMARY KEY, customer_id TEXT NOT NULL,
amount_cents INTEGER NOT NULL, batch_id TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS rejects(batch_id TEXT NOT NULL, line_no INTEGER NOT NULL, reason TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batch_ledger(batch_id TEXT PRIMARY KEY, input_sha256 TEXT NOT NULL,
rows_written INTEGER NOT NULL, rows_rejected INTEGER NOT NULL,
run_id TEXT NOT NULL, committed_at TEXT NOT NULL);
"""
orders carries a batch_id on every row, so any row can be traced to the batch that wrote it. rejects holds rows that failed validation but fell inside the allowed number of rejects. batch_ledger has one row per committed batch, and its primary key is the database’s guarantee that a batch is recorded at most once. Each ledger row stores the fingerprint, the number of rows written and rejected, and the run that committed it.
Applying a batch is one method of the store, shown here with its result type:
@dataclass(frozen=True)
class Applied:
status: str # "committed" | "already_committed"
rows_written: int # rows this call inserted
committed_by_run_id: str
def apply(self, batch: Batch, run_id: str) -> Applied:
with closing(self._connect()) as conn:
conn.execute("BEGIN IMMEDIATE") # take the write lock before reading the ledger
try:
seen = conn.execute("SELECT input_sha256, run_id FROM batch_ledger WHERE batch_id = ?",
(batch.batch_id,)).fetchone()
if seen is not None:
conn.execute("ROLLBACK")
if seen[0] != batch.sha256:
raise BatchConflict(f"{batch.batch_id} was committed with different input")
return Applied("already_committed", 0, seen[1])
conn.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)",
[(*r, batch.batch_id) for r in batch.rows])
conn.executemany("INSERT INTO rejects VALUES (?, ?, ?)",
[(batch.batch_id, n, why) for n, why in batch.rejects])
conn.execute("INSERT INTO batch_ledger VALUES (?, ?, ?, ?, ?, ?)",
(batch.batch_id, batch.sha256, len(batch.rows), len(batch.rejects), run_id,
datetime.now(timezone.utc).isoformat(timespec="seconds")))
self.before_commit()
conn.execute("COMMIT")
except BaseException:
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
self.after_commit()
return Applied("committed", len(batch.rows), run_id)
The order of operations is the design.
BEGIN IMMEDIATEtakes SQLite’s write lock before anything is read. A deferred transaction would take it at the first write, after the ledger lookup. With the lock held first, two workers applying the same batch are serialized, and the second one reads the ledger only after the first has committed. In an engine with row-level concurrency, such as PostgreSQL, the same guarantee rests on the primary key instead: both workers can see no ledger row, but only one insert into the ledger can commit, and the loser gets a uniqueness error that the job has to translate into the already-committed outcome. Check-then-insert without that constraint is a race in any engine.- The ledger lookup decides the outcome before any data is touched. A row with the same fingerprint means the batch has taken effect: the method rolls back the empty transaction and reports
already_committed, along with the run that committed it. A row with a different fingerprint raisesBatchConflict. - The data rows, the reject rows, and the ledger row are inserted inside the same transaction, and one
COMMITmakes all of them visible together. Nothing outside the transaction records that the batch happened, so there is no state in which the rows exist and the ledger does not, or the reverse. before_commitandafter_commitare empty methods. They give tests a place to pause or fail at the two moments that matter, immediately before the commit and immediately after it, without patching the code under test.
Concurrent workers are the next question. Two threads, each with its own connection and a five-second busy timeout, start the same batch at the same moment:
def worker(name):
store = Store(db, busy_timeout_s=5.0) # wait up to 5 s for the write lock instead of failing
barrier.wait() # both workers start the same batch at the same moment
results[name] = store.apply(batch, run_id=name)
run-60 committed rows_written= 3 committed_by= run-60
run-61 already_committed rows_written= 0 committed_by= run-60
orders: 3 ledger rows: 1
One worker committed three rows and the other found the ledger row and wrote nothing. Which worker wins depends on which acquires the lock first; the outcome does not. There is one ledger row and three data rows.
What a kill does when the ledger is outside the transaction
The alternative that most first versions use writes the data, commits, and then records completion. The following store does that. It is an anti-pattern kept here to show what the window costs; the child process attaches a pause between its two commits, so the kill lands in the window:
class NaiveStore(Store):
"""Anti-pattern: rows and ledger are committed separately."""
def apply(self, batch, run_id):
with closing(self._connect()) as conn:
if conn.execute("SELECT 1 FROM batch_ledger WHERE batch_id = ?", (batch.batch_id,)).fetchone():
return Applied("already_committed", 0, "unknown")
conn.execute("BEGIN")
conn.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", [(*r, batch.batch_id) for r in batch.rows])
conn.execute("COMMIT")
self.before_commit() # the window between the two commits
conn.execute("BEGIN")
conn.execute("INSERT INTO batch_ledger VALUES (?, ?, ?, ?, ?, ?)",
(batch.batch_id, batch.sha256, len(batch.rows), 0, run_id,
datetime.now(timezone.utc).isoformat(timespec="seconds")))
conn.execute("COMMIT")
return Applied("committed", len(batch.rows), run_id)
A parent process starts the real command with this store (and, separately, with the correct store paused just before its commit), waits until the child reports that it has reached the window, and sends SIGKILL. That signal cannot be caught, so the child gets no chance to clean up:
class PauseBeforeCommit(Store):
def before_commit(self):
print("READY", flush=True) # data rows and ledger row written, COMMIT not yet issued
time.sleep(30)
def spawn(kind, db, batch, path, run, sig):
p = subprocess.Popen([sys.executable, "fault_child.py", kind, "--db", db, "--batch-id", batch,
"--input", path, "--run-id", run], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
seen = []
for line in p.stdout: # read until the child says it is inside the window
if line.strip() == "READY":
break
seen.append(line)
p.send_signal(sig)
out, err = p.communicate()
return p.returncode, [json.loads(l) for l in seen + out.splitlines(keepends=True) if l.startswith("{")]
[naive] killed with SIGKILL, returncode=-9, state after kill={'orders': 3, 'ledger': 0}, events=['batch_start', 'batch_validated']
[naive] rerun -> (1, 'failed', 'IntegrityError', None, ['sqlite3.IntegrityError: UNIQUE constraint failed: orders.order_id'])
[naive] state after rerun={'orders': 3, 'ledger': 0}
[atomic] killed with SIGKILL, returncode=-9, state after kill={'orders': 0, 'ledger': 0}, events=['batch_start', 'batch_validated']
[atomic] rerun -> (0, 'committed', None, 3, [])
[atomic] state after rerun={'orders': 3, 'ledger': 1}
After the naive store is killed, the three data rows are in the table and the ledger is empty. The rerun does not repeat the work, because the table’s primary key rejects the rows, and it does not finish either: the job fails with IntegrityError on every attempt until someone deletes the rows by hand (the batch_id column on orders is what makes that repair a one-line statement). Without the primary key the rerun would succeed and double the data. Which of the two happens depends on the destination’s constraints. Neither is the retry logic being right.
After the correct store is killed in the middle of its transaction, neither table has any rows, and the rerun commits three. SQLite’s rollback journal is the mechanism: before changing the database file it saves the original pages, and removing that journal is the commit point. A process that dies earlier leaves a journal that the next connection finds and plays back, which restores the old state (see SQLite’s description of atomic commit). The guarantee assumes the storage honors flush requests; it is a property of the engine’s transaction, not of anything the job’s Python code does. Because SIGKILL runs no handlers, this is the only kind of safety that survives it.
A killed run also leaves a recognizable trace in the log. The events the child wrote before it was killed are batch_start and batch_validated, and no batch_end. A run that has a start and no end is the signature of a process that was killed or lost, and a query can find it.
Same batch ID, different bytes
The fingerprint check turns a naming collision into an explicit outcome. After delivery-42 has committed, a file with one amount corrected (19.99 changed to 21.99) is submitted under the same batch ID as run-20. The input is parsed and validated as usual, and then the ledger lookup finds a different fingerprint:
{"event":"batch_start","run_id":"run-20","batch_id":"delivery-42"}
{"event":"batch_validated","run_id":"run-20","batch_id":"delivery-42","rows_read":3,"rows_rejected":0,"rows_candidate":3}
{"event":"batch_end","run_id":"run-20","batch_id":"delivery-42","status":"conflict","attempt":1,"exit_code":4,"rows_written":0,"error_type":"BatchConflict","elapsed_s":0.001}
exit=4
The job writes nothing and exits with status 4. It does not overwrite, because it cannot know whether the new file supersedes the old one, whether downstream consumers have already read the old rows, or whether the new file is a mistake. Replacing committed data is a restatement, which needs its own protocol and ordering rule, described in the glossary entry on delivery revisions and restatements. The conflict status makes the situation visible instead of picking a side.
Events an operator can query
The 07:00 question has a precise form: for batch delivery-42, which runs touched it, what did each conclude, and did any of them commit? A line such as loaded 3 rows can answer only through a regular expression that breaks when someone rewords the message. Structured logging replaces the sentence with named fields that have defined meanings. The job emits one JSON object per line, one event per state change, from a closed set of event names: batch_start, batch_validated, retry_scheduled, and batch_end. A run that ends normally emits exactly one batch_end, which carries the status and the exit code.
| Field | Type | Present on | Meaning |
|---|---|---|---|
run_id, batch_id | string | Every event | The identifiers from the first section, bound once for the whole run |
status | string | batch_end | committed, already_committed, rejected, conflict, failed, terminated |
rows_read, rows_rejected, rows_candidate | integer | batch_validated | Data lines in the file, lines that failed validation, and lines that passed and are eligible to be committed |
rows_written | integer or null | batch_end | Rows inserted by the destination call that ended this run |
committed_by_run_id | string | batch_end when already_committed | The run whose transaction wrote the ledger row |
attempt, delay_s | integer, float | retry_scheduled, batch_end | Which try failed, and how long the job waits before the next |
error_type, exit_code, elapsed_s | string, integer, float | batch_end (error_type on failures; also on retry_scheduled) | The exception class name, the status the process returns, and the run’s duration |
input_sha256 | string | batch_validated | The fingerprint of the bytes that were parsed |
The schema lives in code. FIELD_TYPES is the list of permitted fields and types, JsonFormatter turns a record into one line, and EventLogger refuses anything that is not in the schema before the record reaches the logging module:
FIELD_TYPES = { # the log schema: name -> accepted types
"run_id": (str,), "batch_id": (str,), "attempt": (int,), "status": (str,),
"rows_read": (int,), "rows_rejected": (int,), "rows_candidate": (int,),
"rows_written": (int, type(None)), # None = the job cannot prove what was written
"input_sha256": (str,), "committed_by_run_id": (str,), "delay_s": (float,),
"error_type": (str,), "exit_code": (int,), "elapsed_s": (float,),
}
class JsonFormatter(logging.Formatter):
def format(self, record):
doc = {"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
"level": record.levelname, "event": record.getMessage(), "schema_version": SCHEMA_VERSION}
doc.update(record.fields)
return json.dumps(doc, separators=(",", ":"), allow_nan=False)
class EventLogger(logging.LoggerAdapter):
"""Binds run_id and batch_id once and refuses fields that are not in FIELD_TYPES."""
def event(self, name, level=logging.INFO, **fields):
merged = {**self.extra, **fields}
for key, value in merged.items():
if key not in FIELD_TYPES:
raise KeyError(f"unknown log field: {key}")
if type(value) not in FIELD_TYPES[key]:
raise TypeError(f"{key}: {type(value).__name__} is not an allowed type")
if isinstance(value, float) and not math.isfinite(value):
raise ValueError(f"{key}: JSON cannot carry {value}")
self.logger.log(level, name, extra={"fields": merged})
def make_logger(stream, run_id, batch_id) -> EventLogger:
logger = logging.getLogger(f"etl.{run_id}")
logger.handlers.clear()
handler = logging.StreamHandler(stream)
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
return EventLogger(logger, {"run_id": run_id, "batch_id": batch_id})
Python’s logging separates the logger, which creates records, from the handler, which delivers them, and the formatter, which renders them. The adapter binds run_id and batch_id once so that no call site can forget them. The formatter sits where rendering belongs, and the allow-list sits in event for a reason that is easy to miss: when a formatter raises, the logging module prints the traceback to standard error and carries on. A NaN in a float field, which JSON cannot represent and json.dumps(allow_nan=False) refuses, loses the event and the program does not notice. Validating types and finiteness before the call moves the failure to the caller, where a test sees it.
Null, absent, and zero
A count has three ways to be missing from an answer, and a query has to treat them differently. The job follows one rule for rows_written and the other optional fields:
| Representation | Meaning | Example from this job | What a query should do |
|---|---|---|---|
| Field absent | The field has no meaning for this event | rows_written on batch_validated; committed_by_run_id on a run that committed itself | Do not count the event |
| Zero | The job knows that nothing was written | already_committed, rejected, conflict | Sum it; it is a fact |
| Null | The field applies, but the job cannot establish its value | rows_written when the failure happened inside the destination call | Do not sum it as zero; resolve it from the ledger |
The null case is not hypothetical. If the process loses the connection after sending COMMIT, it cannot tell from the inside whether the transaction took effect. Reporting 0 would be a guess, and reporting 3 would be a different guess. The ledger can answer, and the next attempt will. already_committed exists so that the answer comes from the destination’s state instead of the process’s memory.
Candidate counts and written counts are separate fields for the same reason. A candidate is a row that passed validation in some run. A written row is one that a committed transaction inserted. The following query groups the events from the six runs above by batch ID, which is the grouping the identifiers were designed for:
import json, sys
from collections import defaultdict
events = [json.loads(line) for line in open(sys.argv[1])]
by_batch = defaultdict(list)
for e in events:
by_batch[e["batch_id"]].append(e)
for batch_id, evs in by_batch.items():
ends = [e for e in evs if e["event"] == "batch_end"]
candidates = sum(e["rows_candidate"] for e in evs if e["event"] == "batch_validated")
written = sum(e["rows_written"] or 0 for e in ends)
print(f"{batch_id}: runs={[e['run_id'] for e in ends]} "
f"statuses={[e['status'] for e in ends]} candidates_summed={candidates} rows_written_summed={written}")
delivery-42: runs=['run-17', 'run-18', 'run-20'] statuses=['committed', 'already_committed', 'conflict'] candidates_summed=9 rows_written_summed=3
delivery-43: runs=['run-19'] statuses=['committed'] candidates_summed=2 rows_written_summed=2
delivery-44: runs=['run-21', 'run-22'] statuses=['rejected', 'committed'] candidates_summed=4 rows_written_summed=2
Grouping by batch_id puts the three executions that touched delivery-42 together: the commit, the retry that found it already committed, and the conflicting resubmission. Summing rows_candidate over those runs gives 9 for a batch that holds 3 rows, because each run validated the file again. Summing rows_written gives 3, which matches the table. A dashboard that adds candidate counts across runs reports rows that were never loaded. delivery-44 shows a rejected run followed by a committed one under the same batch ID: that is allowed here because the rejection happened before anything was recorded, and a second submission with a larger reject allowance is a decision the operator made.
One more case needs a rule. When the retry that finds a batch already committed is in the same run, as happens when an acknowledgement is lost (shown below), committed_by_run_id equals the run’s own run_id, and rows_written is 0 for the final call even though an earlier attempt of this run wrote the rows. To count what a run wrote, count the ledger rows whose run_id is the run’s ID, not the events’ rows_written.
What the events leave out, and what happens to them
Logging a structured event as JSON does not make it safe to emit or sure to arrive. The allow-list keeps order IDs, customer IDs, and amounts out of the events, because no field exists to hold them; a developer who adds customer_email=... gets a KeyError in the first test that reaches that line. Exception messages are not logged either. The event carries only the exception’s class name, and the traceback goes to standard error as plain text. A traceback includes the exception message, and the messages of some database drivers include the offending key values, so standard error needs the same access control and retention as the data. The glossary entry on log redaction covers masking when fields cannot simply be omitted.
Delivery is a separate concern. The job writes events to standard output and does not know where they go. The Twelve-Factor App’s logging guidance describes this division: the application emits an unbuffered event stream, and the execution environment routes it. Log and Telemetry Collection describes the collectors that do the routing. A collector can drop lines, a buffer can be lost with its node, and the process that wrote a batch_end line may have been killed one instruction later. The log is therefore evidence about what a process observed. The ledger is the record that the batch took effect. When the two disagree, the ledger wins.
Every event carries schema_version. Adding an optional field leaves the version alone. Renaming a field, changing a type (for example rows_written from an integer to a string), or changing what a count means requires a new version, because a query written against version 1 would otherwise return different numbers without an error. FIELD_TYPES is the schema, so a change to it is the point at which a reviewer asks whether the version should move.
Failure classes decide what happens next
A retry is correct for some failures and harmful for others, so the first step on any error is to classify it. The job separates failures that a later attempt can fix from those that it cannot, and gives each a status, an exit code, and an operator action:
| Failure | Example in this job | Retry in process? | Status and exit code | Operator action |
|---|---|---|---|---|
| Input violates the contract beyond the allowance | More rejected rows than --max-rejects | No | rejected, 3 | Get a corrected delivery; it is new intent, so it gets a new batch ID |
| Same batch ID, different input | A resent file under delivery-42 | No | conflict, 4 | Decide whether it supersedes the original |
| Transient destination failure | Database locked; connection lost | Yes, within a budget | failed, 75 when the budget is spent | Rerun later; the ledger makes the rerun safe |
| Unexpected exception | A constraint violation, or a bug | No | failed, 1 | Read the traceback on standard error |
| Stop request | SIGTERM from the runtime | No | terminated, 143 | Rerun |
| Usage error | A missing --batch-id | No | None (argparse exits with 2 before the job starts) | Fix the command |
The classification is code, in two places. Exceptions that the job raises on purpose carry their own status and exit code. For everything else the job has to decide from the exception type, and it errs toward not retrying:
class EtlError(Exception):
status, exit_code = "failed", EXIT_FAILED
class TooManyRejects(EtlError):
status, exit_code = "rejected", EXIT_REJECTED
class BatchConflict(EtlError):
status, exit_code = "conflict", EXIT_CONFLICT
class TransientExhausted(EtlError):
status, exit_code = "failed", EXIT_TEMPFAIL
class Terminated(BaseException): # not an Exception: `except Exception` must not swallow it
pass
def is_transient(exc: BaseException) -> bool:
if isinstance(exc, (ConnectionError, TimeoutError)):
return True
if isinstance(exc, sqlite3.OperationalError):
text = str(exc).lower()
return "locked" in text or "busy" in text
return False
Only connection and timeout errors and SQLite’s lock errors count as transient. An IntegrityError is not, and neither is any exception the job does not recognize: retrying a bug repeats the bug, and retrying a constraint violation repeats the violation. Misclassifying in the other direction is the more expensive mistake. A permanent error retried four times with backoff delays the page that tells someone to look, and it multiplies the load on a destination that may be failing for a reason the retry cannot fix.
The exit status is the second interface of the job, after the events. A scheduler or container runtime that starts the command sees a number and two output streams. Zero means the batch is in the destination, whether this run put it there or an earlier one did; that is why already_committed exits 0. Whether a scheduler can map distinct non-zero codes to distinct policies (retry on 75, do not retry on 3) depends on the scheduler; where it cannot, the status in batch_end carries the same distinction. The value 75 is borrowed from EX_TEMPFAIL in sysexits.h, whose documentation describes it as a temporary failure to be reattempted later. That interface is documented as deprecated, so the numbers here are a convention this job defines and documents, not a standard that tools interpret. The value 143 is the shell’s 128 plus the signal number 15.
Retrying inside the process
Retrying inside the process handles short disturbances without waking anyone or starting a new container. It is safe only because the ledger makes the whole batch application repeatable; without that, a retry after a lost acknowledgement is exactly the double write from the opening scenario. The unit of retry is the destination call, not the parse: the file is read and validated once, and only store.apply repeats.
The delay between attempts uses exponential backoff with full jitter, as described by Marc Brooker in the AWS Architecture Blog. Attempt n waits a random time between 0 and min(cap, base * 2**(n-1)):
def backoff_delay(attempt: int, base: float, cap: float, rng: random.Random) -> float:
"""Full jitter: uniform between 0 and min(cap, base * 2**(attempt-1))."""
return rng.uniform(0, min(cap, base * 2 ** (attempt - 1)))
With a base of 0.2 seconds and a cap of 5 seconds, the upper bound of the delay is 0.2, 0.4, 0.8, 1.6, 3.2, and then 5 seconds. Four attempts therefore sleep at most 0.2 + 0.4 + 0.8 = 1.4 seconds in total, plus the time of the four calls. The randomization matters when many clients fail together. The following toy simulation sends 50 clients, each failing at time 0 and retrying four times, and counts how many retries land in the busiest 50-millisecond window. It ignores service time and queuing, so it shows only the spreading effect:
jitter=False retries=200 busiest 50 ms bucket= 50 buckets used=4
jitter=True retries=200 busiest 50 ms bucket= 22 buckets used=41
schedule caps (s): [0.2, 0.4, 0.8, 1.6, 3.2, 5.0, 5.0]
worst-case total sleep, 4 attempts: 1.4
Without jitter, all 50 clients retry at the same instants, 0.2, 0.6, 1.4, and 3.0 seconds, so 200 retries arrive in 4 windows and the busiest holds 50. With full jitter the same 200 retries spread over 41 windows and the busiest holds 22. Randomness does not make any single client faster. It keeps the retries of one failure from arriving together again. Brooker’s article reports the effect on completion time and total work with contending clients; the toy above reproduces only the shape of the arrival pattern.
The function that ties the pieces together is run_batch. It reads and validates the input, applies the reject allowance, runs the retry loop around the destination call, and ends in exactly one batch_end in every outcome:
def run_batch(cfg: Config, store: Store, log: EventLogger, rng=None, sleep=time.sleep) -> int:
rng = rng or random.Random()
started = time.monotonic()
attempt, in_apply = 0, False
log.event("batch_start")
try:
batch = read_batch(cfg.input, cfg.batch_id)
log.event("batch_validated", rows_read=batch.rows_read, rows_rejected=len(batch.rejects),
rows_candidate=len(batch.rows), input_sha256=batch.sha256)
if len(batch.rejects) > cfg.max_rejects:
raise TooManyRejects(f"{len(batch.rejects)} rejected rows exceed the allowance of {cfg.max_rejects}")
while True:
attempt += 1
try:
in_apply = True
applied = store.apply(batch, cfg.run_id)
in_apply = False
break
except Exception as exc:
if not is_transient(exc):
raise
delay = backoff_delay(attempt, cfg.base_delay_s, cfg.cap_delay_s, rng)
if attempt >= cfg.max_attempts or time.monotonic() - started + delay > cfg.deadline_s:
raise TransientExhausted(f"gave up after {attempt} attempts") from exc
log.event("retry_scheduled", logging.WARNING, attempt=attempt, delay_s=round(delay, 3),
error_type=type(exc).__name__)
sleep(delay)
extra = {"committed_by_run_id": applied.committed_by_run_id} if applied.status == "already_committed" else {}
log.event("batch_end", status=applied.status, attempt=attempt, exit_code=EXIT_OK,
rows_written=applied.rows_written, elapsed_s=round(time.monotonic() - started, 3), **extra)
return EXIT_OK
except Terminated:
log.event("batch_end", logging.WARNING, status="terminated", attempt=attempt, exit_code=EXIT_TERMINATED,
rows_written=None, elapsed_s=round(time.monotonic() - started, 3))
return EXIT_TERMINATED
except EtlError as exc:
# rows_written is provably 0 only when the failure happened before the destination transaction
written = None if in_apply and not isinstance(exc, BatchConflict) else 0
log.event("batch_end", logging.ERROR, status=exc.status, attempt=attempt, exit_code=exc.exit_code,
rows_written=written, error_type=type(exc).__name__,
elapsed_s=round(time.monotonic() - started, 3))
print(f"{type(exc).__name__}: {exc}", file=sys.stderr)
return exc.exit_code
except Exception as exc:
log.event("batch_end", logging.ERROR, status="failed", attempt=attempt, exit_code=EXIT_FAILED,
rows_written=None if in_apply else 0, error_type=type(exc).__name__,
elapsed_s=round(time.monotonic() - started, 3))
traceback.print_exc(file=sys.stderr) # human-readable detail goes to stderr, not into the event
return EXIT_FAILED
Four details carry the behavior.
- The retry loop catches
Exceptionand re-raises whateveris_transientdoes not accept. It gives up when the attempt budget is spent or when the next sleep would push the run pastdeadline_s, and it raisesTransientExhaustedfrom the last exception. in_applyrecords whether the failure happened inside the destination call. By the rule in the previous section,rows_writtenis null for such failures and 0 for failures that happened before the call.BatchConflictis the exception:applyraises it only after its own rollback, so zero is provable.- Unexpected exceptions are logged by class name only, with the traceback printed to standard error.
Terminatedis handled in its own branch. The next section explains it.
Two runs show the retry path. In the first, AckLostOnce is a store whose after_commit raises ConnectionError on its first call, so the transaction has committed but the caller sees a failure. This is the lost-acknowledgement window from Airflow Operations, reproduced at the process level. In the second, a competing connection holds the write lock for 0.7 seconds. The delay values come from a seeded random generator, so they repeat; the wall-clock timing is real:
exit 0
{'event': 'retry_scheduled', 'run_id': 'run-50', 'attempt': 1, 'delay_s': 0.065, 'error_type': 'ConnectionError'}
{'event': 'batch_end', 'run_id': 'run-50', 'status': 'already_committed', 'attempt': 2, 'rows_written': 0, 'committed_by_run_id': 'run-50', 'exit_code': 0}
orders: 3
--- lock held for 0.7 s
exit 0
{'event': 'retry_scheduled', 'run_id': 'run-51', 'attempt': 1, 'delay_s': 0.048, 'error_type': 'OperationalError'}
{'event': 'retry_scheduled', 'run_id': 'run-51', 'attempt': 2, 'delay_s': 0.218, 'error_type': 'OperationalError'}
{'event': 'retry_scheduled', 'run_id': 'run-51', 'attempt': 3, 'delay_s': 0.296, 'error_type': 'OperationalError'}
{'event': 'retry_scheduled', 'run_id': 'run-51', 'attempt': 4, 'delay_s': 0.966, 'error_type': 'OperationalError'}
{'event': 'batch_end', 'run_id': 'run-51', 'status': 'committed', 'attempt': 5, 'rows_written': 3, 'exit_code': 0}
--- lock held throughout, CLI
returncode 75
{'event': 'retry_scheduled', 'run_id': 'run-52', 'attempt': 1, 'delay_s': 0.012, 'error_type': 'OperationalError'}
{'event': 'retry_scheduled', 'run_id': 'run-52', 'attempt': 2, 'delay_s': 0.091, 'error_type': 'OperationalError'}
{'event': 'batch_end', 'run_id': 'run-52', 'status': 'failed', 'attempt': 3, 'error_type': 'TransientExhausted', 'rows_written': None, 'exit_code': 75}
In the first run, attempt 1 committed and then failed, the job scheduled a retry, and attempt 2 found the ledger row: already_committed with committed_by_run_id equal to the run’s own ID, and three rows in the table. Nothing was applied twice and nobody had to know in advance which window the failure fell in.
In the second run, attempts 1 through 4 hit the lock and attempt 5 committed. The sleep after attempt 4 was 0.966 seconds, so the job slept past the moment the lock cleared at 0.7 seconds. That is the price of randomized delays: they trade some idle time for protection against synchronized retries. In the third case the lock never clears within a budget of three attempts. The real command, started in a subprocess while the parent holds the lock, exits with 75, and rows_written is null in its batch_end. The next process, whether an orchestrator retry or an operator, resolves the null by running the same command and reading what the ledger says.
Retries in the job and retries in the orchestrator multiply. A hypothetical orchestrator that retries a failed task three times, around a job that makes four destination attempts each time, can send up to twelve destination attempts for one batch. If the destination is the thing that is down, the budgets should be chosen together, as the arithmetic in the Airflow operations article does for retries and timeouts. Networks and I/O for Data Engineers covers retry cost and timeouts at the network level.
Stopping cleanly, and when nothing gets to stop
Runtimes that stop a process usually send SIGTERM first and SIGKILL after a grace period whose length is a runtime setting. The first signal can be handled, so the job uses it to report what happened. The second cannot be handled, so the job’s correctness cannot depend on the first. Containerizing Data Jobs with Docker follows this command into a container image and its stop behavior.
def _on_sigterm(signum, frame):
raise Terminated()
# in main(), before the job runs:
signal.signal(signal.SIGTERM, _on_sigterm)
The handler raises Terminated, which derives from BaseException rather than Exception. The retry loop’s except Exception and the except EtlError branch therefore do not catch it. Store.apply has an except BaseException that rolls back and re-raises, so the open transaction ends, and run_batch reports it in its own branch. A parent process starts the job paused inside its transaction and sends SIGTERM instead of SIGKILL:
returncode: 143 | state: {'orders': 0, 'ledger': 0}
{'run_id': 'run-40', 'batch_id': 'delivery-42', 'status': 'terminated', 'attempt': 1, 'exit_code': 143, 'rows_written': None}
rerun: (0, 'committed', None, 3, [])
The process returns 143, the last event is batch_end with status terminated and a null rows_written (it was inside the destination call), and the tables are empty. The rerun commits. In contrast to the kill, this run said what it was doing when it stopped.
The Python documentation states that a signal handler runs in the main thread, between bytecode instructions, and that an exception raised from it can surface after any bytecode instruction. The handler is therefore one line and does no work of its own. The safety of an interruption at an arbitrary point comes from the transaction boundary and the context managers around resources, not from the handler getting the order right. A job that writes files has the same obligation: write to a temporary name and rename it into place, as the entry point in Python for Data Engineers does, so that an interrupted write leaves nothing that a reader can mistake for output.
Testing the process boundary
The properties above are statements about a process, not about a function. A test that calls apply twice and checks the row count proves that a second call is harmless; it does not prove that a kill leaves no partial batch, that the exit code is 3 and not 1, or that the batch_end line says what the operator will rely on. The tests for this job assert the outward behavior: exit codes, events, and table contents after specific failures.
class AckLostOnce(Store):
def __init__(self, *a, **k):
super().__init__(*a, **k); self.calls = 0
def after_commit(self):
self.calls += 1
if self.calls == 1:
raise ConnectionError("acknowledgement lost after commit")
def run_job(self, batch_id, name, run_id, store=None, **cfg):
buf = io.StringIO()
config = Config(batch_id, DATA / name, self.db, run_id, **cfg)
code = run_batch(config, store or Store(self.db), make_logger(buf, run_id, batch_id), rng=random.Random(1),
sleep=lambda s: None)
return code, [json.loads(l) for l in buf.getvalue().splitlines()]
def test_lost_acknowledgement_is_resolved_by_the_ledger(self):
code, events = self.run_job("d42", "orders_42.csv", "run-1", store=AckLostOnce(self.db))
self.assertEqual(code, EXIT_OK)
self.assertEqual([e["event"] for e in events if e["event"] == "retry_scheduled"], ["retry_scheduled"])
self.assertEqual(events[-1]["status"], "already_committed")
self.assertEqual(self.count("orders"), 3)
def test_exhausted_transient_failures_exit_with_tempfail(self):
class AlwaysLocked(Store):
def apply(self, batch, run_id):
raise sqlite3.OperationalError("database is locked")
code, events = self.run_job("d42", "orders_42.csv", "run-1", store=AlwaysLocked(self.db), max_attempts=3)
self.assertEqual(code, EXIT_TEMPFAIL)
self.assertIsNone(events[-1]["rows_written"])
self.assertEqual(sum(e["event"] == "retry_scheduled" for e in events), 2)
run_job builds a config, runs run_batch with a seeded random generator and a no-op sleep, and returns the exit code with the parsed events, so tests read the same output an operator would. The hooks make the lost-acknowledgement window reproducible: AckLostOnce raises exactly after the commit. The second test replaces apply with a store that always reports a lock, and asserts the exit code 75, a null rows_written, and exactly two retry events for three attempts. The full suite also checks the reject allowance (nothing written, counts in the event), the conflict (exit 4, zero written), the log schema (an unknown field, a wrong type, and a NaN are each refused), the backoff bounds, the transient classification, and the kill test from earlier, which spawns a process and kills it with SIGKILL.
Ran 9 tests in 0.168s
OK (9 tests: 5 job, 3 unit, 1 process; Python 3.12.14, SQLite via the standard library)
These tests pin the job’s behavior against SQLite. A transaction in a warehouse has its own isolation rules, error codes, and limits, and its lock and uniqueness errors differ from the ones this job classifies. The same properties need checking against the real destination in an integration environment before the classification table is trusted. Python for Data Engineers covers unit tests for transforms and tests of file publication.
Where the design stops
The design depends on one atomic boundary around the data and the ledger. When the destination offers no transaction that covers both, such as files in object storage, several tables, or an external API, the job needs a different commit protocol: write the output to a staging location, validate it, and publish it with one atomic step that also records the batch, as described in the entry on atomic publication and in the publishing section of ETL, ELT, and Data-Pipeline Design Patterns. The batch ID, the fingerprint, and the outcome vocabulary carry over unchanged.
The job reads the whole file into memory and applies it in one transaction. That suits a bounded delivery. A batch too large for either limit needs staging in chunks, each chunk idempotent under its own identity, and a single publish step that moves the staged data into place and writes the ledger row. The ledger then records the publication, not each chunk.
The ledger prevents a batch from being applied twice. It does not prevent the same order from arriving in two different batches. The primary key on orders.order_id turns that into an IntegrityError and a failed run, which is correct for this table and wrong for a feed that legitimately updates orders. Updating them needs an explicit key and ordering policy, covered in the entry on upsert and merge. The ledger also lives with the data: restoring one without the other can make every retry skip work that is not there, and a worker that pauses and wakes after a replacement has taken over needs a fencing mechanism that the destination enforces, as Building Incremental and Idempotent Pipelines explains.
Finally, the guarantees are the destination’s guarantees. The ledger and the data commit together because SQLite’s transaction makes them so. If a job also sends an email or calls another service after the commit, that effect is outside the boundary, and a crash between the commit and the call loses it or, if the order is reversed, repeats it. Such effects need their own idempotency key, or an outbox written inside the same transaction and delivered by a separate process.
References
- Python documentation, Logging Cookbook (LoggerAdapter and structured logging)
- Python documentation, signal: Set handlers for asynchronous events
- SQLite, Atomic Commit In SQLite
- SQLite, BEGIN TRANSACTION (deferred, immediate, and exclusive transactions)
- Marc Brooker, Exponential Backoff And Jitter, AWS Architecture Blog
- The Twelve-Factor App, XI. Logs
- FreeBSD manual, sysexits(3): preferable exit codes for programs
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
