Lesson 3 of 9 · 23m
Idempotency, State, and Retries: Automation You Can Run Twice
Real automation gets interrupted; design actions that can be rerun safely, record state honestly, and stop pretending exactly-once exists.
The question that separates a script from automation is simple: what happens if I run it again? If the answer is duplicate tickets, repeated firewall pushes, deleted evidence, or nobody knows, it is not safe to automate yet.
Exactly-once is a lie; effects need identity
Networks time out after the remote side has processed a request. Workers die after creating a ticket but before recording its ID. The practical defense is idempotency: give every logical operation a stable key and make repeating it harmless.
from hashlib import sha256
def finding_key(finding: dict) -> str:
material = "|".join([
finding["scanner"], finding["host"],
str(finding["port"]), finding["plugin"],
])
return sha256(material.encode()).hexdigest()[:24]That key becomes a ticket custom field, a database primary key, or an object name in storage. When the same finding arrives again, update the existing object instead of creating a twin.
State transitions beat boolean flags
A row with done = true cannot distinguish "queued," "scanner accepted," "scan finished," or "ticket created." Use explicit states and record transitions.
from enum import StrEnum
class ScanState(StrEnum):
DISCOVERED = "discovered"
NORMALIZED = "normalized"
TICKETED = "ticketed"
VERIFIED = "verified"
CLOSED = "closed"
FAILED = "failed"Store state, attempts, last_error, and timestamps. Do not erase the last error when retrying; preserve enough context to know whether failures are changing.
Retry only what is worth retrying
Retries are for transient failure: connection resets, rate limits, temporary 5xx responses. They are not for authentication failures, validation errors, or malformed input. Blind retry converts a bug report into a self-inflicted denial of service.
import random
def backoff(attempt: int) -> float:
return min(60.0, (2 ** attempt) + random.uniform(0, 0.5))Jitter matters when many workers retry together; without it, a rate limit becomes a synchronized drumbeat. Destructive steps need even more care: isolate-host, disable-user, and purge-data actions should carry reason, approval, rollback, and expiration metadata.
Field notes
- Rerun safety is tested by actually rerunning the job, not by reading the code hopefully.
- Idempotency keys must exclude noisy fields such as scan timestamps unless the timestamp is genuinely part of identity.
- Infinite retry is not persistence; use a dead-letter state for input that cannot be processed.
- A database transaction protects local state, not the remote side effect — use outbox records or reconciliation passes.
- Dashboard states and ages, not just counts; ten items stuck in
TICKETEDfor six hours are a problem.
Was this lesson helpful?