You kicked off an agent last night: pull 200 leads, write each one a personalized pitch, deliver the results, done by morning. You wake up and it died at item 141. Your options are "start the whole thing over" or "hand-rebuild 140 lines of results at 6 a.m." If the run bills per API call, starting over also means paying for those 141 twice.
A checkpoint file fixes this. After every finished item, write one small record: what's done, what's paid. On restart, read the file, skip finished work, continue from the break. A crash becomes a pause, not a restart.
Here's the full pattern: why long runs die, how to checkpoint safely, how to make every step safe to repeat, and a short loop you can paste into your next agent.
Why long runs die halfway
Long agent jobs fail in three predictable ways.
Timeouts. A server can answer "408 Request Timeout" when your request arrives too slowly, and servers close idle connections on their own schedule, not yours (HTTP spec, RFC 9110). At hour three of a batch job, one slow response is enough to kill the loop.
Rate limits. Batch work hits API limits constantly. The standard response, HTTP 429 "Too Many Requests", is defined in RFC 6585 (source), and if your loop doesn't handle it, it crashes or hammers the API until something worse happens.
Restarts you didn't plan. Your laptop sleeps. Your VPS reboots for kernel updates. Your shell session times out and takes the process with it. A cron job fires twice. None of these are bugs in your code; they're ordinary conditions at 3 a.m.
The fix is not making the run smarter. It's making any interruption cheap: the run can die at any point, and restarting loses nothing.
Checkpoint after every finished item
Pick the smallest unit your job has: one lead scraped, one summary written, one file uploaded. After each unit finishes, write the state to disk. Not every 50 items, after every single one. A checkpoint every 50 items means a crash at item 49 loses all 49.
Two storage choices cover almost every case:
- JSON file. Fine up to thousands of items. One dictionary, human-readable, easy to inspect while the job runs.
- SQLite. Built into Python (source), better when you have tens of thousands of items or want to query "which leads are done" directly.
The one rule that matters: write the checkpoint atomically. If you write the file in place and the process dies mid-write, your checkpoint is corrupt, and a corrupt checkpoint is worse than none because you can't trust it. The standard trick is to write a temp file in the same folder, then rename it over the real file. POSIX guarantees rename() replaces the old file atomically (source), and Python's os.replace() is the portable way to do it (source). A crash mid-write leaves either the old checkpoint or the new one, never a torn file.
Make every step repeatable (idempotent)
A step is idempotent when running it twice produces the same result as running it once. That's the property that makes "skip done items" safe.
The dangerous step is the one between "did the work" and "recorded that I did the work". Send the email, crash before the checkpoint, restart: the loop can't tell whether that email went out, and a naive retry sends it again.
Two habits prevent this:
- Checkpoint the instant a unit finishes. The gap between action and record should be one line of code, not "I'll write the file at the end of the loop".
- Use request IDs the API can dedupe. Many APIs support idempotency keys: you send the same key twice, the API performs the action once and returns the original result the second time (Stripe's API docs are a well-known example). Generate one key per item and reuse it on every retry.
If an API has no idempotency support, that step is the one to verify manually on restart rather than blind-retry.
Never pay or send twice
Money and messages are the steps where a double run costs real money or real reputation. Order matters here.
Record before the slow work, not after. The sequence is: check the item isn't paid, pay, write "paid" to the checkpoint, then do the work. If the process dies between pay and work, the restart sees "paid" and skips the charge; it only repeats the work. If you record after the work instead, a crash in between means the restart charges again. That still leaves one tiny gap, between the charge and the save, and the idempotency key from the last section closes it: a retried charge with the same key is not charged twice.
When "paid" exists but "done" doesn't, don't guess. Look up whether the work actually happened: query the order status, check the message log, ask the API what it has for that request ID. If you can't verify, leave the item marked and handle it by hand when you're awake. Fixing one item by hand costs you five minutes; a blind retry can cost you a duplicate charge or a duplicate message to a client.
Same for outbound messages: keep a sent-log in the checkpoint, and treat "not sure if sent" as "sent" until you can prove otherwise. One missed message is a smaller loss than a duplicate.
The whole pattern in one short loop
This is the skeleton. Replace charge_card and deliver with your real calls; everything else is the pattern.
import json, os
from pathlib import Path
STATE = Path("run_state.json")
ITEMS = ["lead-001", "lead-002", "lead-003"] # your full work list
def save(state):
tmp = STATE.with_suffix(".tmp")
tmp.write_text(json.dumps(state), encoding="utf-8")
os.replace(tmp, STATE) # atomic swap: old file or new file, never torn
def load():
if STATE.exists():
return json.loads(STATE.read_text(encoding="utf-8"))
return {"paid": [], "done": []}
state = load()
for item_id in ITEMS:
if item_id in state["done"]:
continue # finished before the crash, skip
if item_id not in state["paid"]:
charge_card(item_id) # your payment call goes here
state["paid"].append(item_id)
save(state) # record payment BEFORE the slow work
deliver(item_id) # your real work call goes here
state["done"].append(item_id)
save(state)
print(f"done: {len(state['done'])}/{len(ITEMS)}")
Kill it mid-run and run it again. It picks up where the checkpoint left off and skips every item already marked paid. Pass the item ID as the idempotency key inside charge_card and the last gap is covered too.
Before you leave an agent running overnight
BEFORE YOU LEAVE AN AGENT RUNNING OVERNIGHT
[ ] Checkpoint file updates after EVERY item, not in batches
[ ] Write is atomic: temp file + os.replace, same folder
[ ] Restart skips every item marked done
[ ] Payments recorded before the work that depends on them
[ ] "Paid but not done" triggers a status check, never a blind retry
[ ] Sent messages logged; can't verify means don't resend
[ ] Rate-limit responses handled with a backoff retry
[ ] Dry run: do 3 items, kill the process mid-run, restart, confirm it resumes
[ ] Logs write to a file, not just the terminal you're about to close
[ ] You can answer in one sentence: "if it dies at item N, restart does what?"
That last test, kill-and-restart, is the one people skip. Run it once before every overnight job. It takes two minutes and it's the only way to know the pattern actually works instead of hoping it does.
Related: Idempotency keys: stop your AI agent from paying twice
If this saved you a re-run, a small tip on the post is appreciated.






Latest comments
0