A data migration script runs for 40 minutes over 5,000 items. When it fails at item 3,000, rerunning starts from scratch. How do you make it resumable?
AdvancedScenarioScenarios: writing and hardening scripts
Answer
Situation read → Long batch jobs need checkpoints and idempotent steps, otherwise every failure costs the full runtime and may duplicate work.
What I'd do →
- Make each item idempotent (check before acting, or use upserts).
- Record progress in a state file after each item succeeds, written atomically:
state=/var/lib/migrate/done.txt touch "$state" while IFS= read -r id; do grep -qxF -- "$id" "$state" && continue migrate_item "$id" printf '%s\n' "$id" >> "$state" done < items.txt - For large sets, use a sorted done-list and
comm -23 <(sort items.txt) <(sort "$state")to compute the remaining work once, instead of grepping per item. - Take a lock so two resumptions cannot run at once, and add a
--resetflag to clear state deliberately. - Log a progress line every N items with an ETA.
Why → Checkpointing turns a 40-minute retry into a 1-minute one, and idempotency makes reruns safe.
Interview tip → Say you append to the state file only after the item succeeds, so a crash mid-item retries that item.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateA script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?BeginnerYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.Beginner