Skip to content

Lesson 8 of 9 · 26m

Idempotency, Recovery, and Secrets

Designing operations that can fail halfway: idempotent steps, checkpoints, reconciliation, safe retries, secret handling, and restoring trust after partial execution.

The question that matters is not "what does the script do when it works?" It is "what state exists when it dies at step seven of eleven?" Production automation is crash recovery wearing a costume.

Idempotent means safe to run again

Compare these:

append_line(config_path, 'enabled=true')          # not idempotent
ensure_key_value(config_path, 'enabled', 'true')  # converges on desired state

The second operation inspects current state and changes only what is wrong. For filesystem work, use desired-state checks and atomic replacement. For APIs, use named resources, idempotency keys, or read-before-write reconciliation.

Model work as verified steps

steps = [
    Step('snapshot', snapshot_volume, verify_snapshot),
    Step('stop', stop_service, verify_stopped),
    Step('migrate', migrate_data, verify_schema),
    Step('start', start_service, verify_healthy),
]

Each step needs an action and a verification. If verification fails, stop. Do not continue mutating infrastructure because most steps usually work. Verification should test the user-visible outcome, not merely the command exit code.

Checkpoints beat blind retry

Long jobs need durable checkpoints: a database row, an atomic state file outside the mutated tree, or cloud resource tags. Store detailed state, not a comforting boolean:

{"job_id": "backup-2026-11-29", "completed": ["snapshot", "upload"], "artifact": "db-2026-11-29.dump", "attempts": 2}

Retry only retryable failures

A retry policy needs to know what failed, whether repetition is safe, and how many attempts remain. Use exponential backoff with jitter:

for attempt in range(1, 5):
    try:
        upload()
        break
    except TransientUploadError:
        if attempt == 4:
            raise
        time.sleep(min(2 ** attempt, 30) + random.random())

Authentication failure, validation failure, and missing input are permanent; fail them immediately.

Secrets are inputs, not source code

Never put tokens in scripts, command arguments, or logs. Prefer instance roles, secret managers, or strict-permission local files over environment variables. Once a token reaches a central log system, rotation is your only honest remediation.

Field notes

  • Temporary files, lock files, and partial artifacts are system state; design cleanup for them.
  • "Exactly-once" is rarely available across networks. Aim for safe repetition plus reconciliation.
  • When failing, print what state is confirmed, what is unknown, and what the operator should inspect.

Was this lesson helpful?

Sign in to rate