Sub topic 4
Making Steps Safe to Repeat
This chapter assumes you can read Python, understand JSON files, and know that an agent runs tools in a loop. It also assumes you have seen why long tasks get interrupted and how work is split into steps. Here we focus on one property of each step: running it twice should be as safe as running it once.
Why repeats happen
A long-running task will run some steps more than once. Nobody plans this. It follows from how interruptions work.
Suppose a step uploads a file and then the process is killed. The checkpoint was not yet saved, so on restart the step looks unfinished. The agent runs it again. The upload happened once already, so now it happens twice.
The same thing happens when:
- A network call times out, but the server actually processed the request.
- A tool call is retried automatically after an error.
- A new agent picks up the task and cannot tell whether the last step finished.
- A person re-runs the whole job "to be safe."
The gap between "the side effect happened" and "the checkpoint says it happened" cannot be closed completely. Two things can never be made one atomic action: the effect on the outside world, and the write to your own state file. So the design goal shifts. Instead of trying to prevent repeats, make repeats harmless.
What idempotent means
A step is idempotent if running it once and running it many times leave the system in the same final state. The word comes from mathematics. In practice it means: "doing this again changes nothing new."
Some operations are naturally idempotent:
- Setting a value:
status = "done". - Writing a file to a fixed path, replacing what was there.
- Deleting a file that may already be gone, if you treat "not found" as success.
Others are not:
- Appending a line to a log.
- Incrementing a counter.
- Sending an email.
- Creating a record with a generated ID.
- Uploading a file under a new unique name each time.
The second group is where long tasks go wrong. A repeated append gives duplicate lines. A repeated email reaches the customer twice. A repeated payment charges twice.
Techniques for making a step idempotent
There are four common techniques. They can be combined.
Replace instead of append
Where you can, write the whole result to a fixed location rather than adding to something that exists. A step that regenerates out/report-2023-08.csv from source data can run any number of times. A step that appends rows to report.csv cannot.
Check before acting
Before doing the effect, test whether it is already done. If the output file exists and is valid, skip the work. If the record exists in the database, do not insert it again.
This works, but it has a window. Between the check and the action, another process can act. For a single writer, the window is harmless. With concurrent writers you need locking, which a later chapter covers.
Use a deterministic key
Derive the identity of the result from the input, not from the clock or a random generator. Compare these two names for the same upload:
report-8f3a91c2.csv, where the suffix is random. Each retry creates a new object.report-2023-08.csv, where the name comes from the month being exported. Each retry targets the same object.
The same idea applies to idempotency keys for APIs. Many services accept a client-chosen key and return the original result if they see the same key again. Choose the key from the work item, such as export:2023-08, never from a fresh random value.
Record the effect before or with the action
Keep a durable record of which effects have been applied. Then a retry can look it up. This is the pattern you will use most in agent tasks, so the next section works through it.
A worked example
The following code exports monthly data. Each month produces one file. The first version is not safe to repeat.
import os
def export_month_unsafe(month, rows, out_dir="out"):
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, "export.csv")
with open(path, "a") as f:
for row in rows:
f.write(f"{month},{row}\n")If this step runs twice for the same month, every row appears twice. The file also mixes months, so you cannot tell which ones are complete.
Here is a version that is safe to repeat. It uses a deterministic file name per month and writes through a temporary file, so a crash never leaves a partial result under the final name.
import os
import tempfile
def export_month(month, rows, out_dir="out"):
os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f"export-{month}.csv")
fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
for row in rows:
f.write(f"{month},{row}\n")
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, final_path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
return final_path
if __name__ == "__main__":
export_month("2023-08", ["a", "b", "c"])
export_month("2023-08", ["a", "b", "c"])
with open("out/export-2023-08.csv") as f:
print(f.read())Running this prints three lines, not six. The second call replaces the first file with identical content. The temporary file plus os.replace follows the same approach as the atomic checkpoint writer from the previous chapter.
Steps with side effects you cannot replace
Some effects are not files you control. You cannot "replace" an email. For these, record the effect in a ledger and consult it before acting.
import json
import os
def load_ledger(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {"sent": []}
def save_ledger(path, ledger):
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(ledger, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def send_once(ledger_path, key, send_fn):
ledger = load_ledger(ledger_path)
if key in ledger["sent"]:
return "skipped"
send_fn()
ledger["sent"].append(key)
save_ledger(ledger_path, ledger)
return "sent"This is better, but look closely at the order. send_fn() runs before the ledger is saved. A crash between those two lines sends the message but loses the record, so a retry sends it again. The ledger narrows the window. It does not remove it.
You have two honest options:
- At-least-once. Act first, then record. A crash may cause a duplicate, but never a lost action. Use this when a duplicate is cheap or the receiving system deduplicates by key.
- At-most-once. Record first, then act. A crash may cause a lost action, but never a duplicate. Use this when a duplicate is harmful and you can detect and repair a missing action.
Pick deliberately. Sending a reminder email is fine as at-least-once. Charging a card should pass an idempotency key to the payment service so that the service itself provides the guarantee.
Where repeats enter an agent loop
The diagram shows the usual path from an interruption to a repeated step, and the two places where you can stop the damage.
Designing steps for repeatability
When you decompose a task, apply these checks to each step.
- Name the effect. Write down what the step changes outside the process: files, rows, messages, remote resources.
- Name the identity. Decide what uniquely identifies the work item, such as a month, a page ID, or a file path. Use it in names and keys.
- Decide the order. Choose at-least-once or at-most-once, and state why.
- Make partial results invisible. Write to a temporary location and publish with a single rename or a single commit.
- Test by running twice. Run the step two times in a row and compare the state after each run.
The last check is the cheapest and catches most mistakes. A step that fails the double-run test will fail in production the first time a restart lands at the wrong moment.
Edge cases
- Non-deterministic output. If a step calls an LLM or reads the current time, a repeat may produce different content. The step can still be idempotent in effect if it writes to a fixed location and the content is replaced. It is not idempotent if downstream steps already consumed the first output. Save the first result and reuse it instead of regenerating.
- Partial completion inside a step. A step that processes 1000 items may stop at item 600. If each item is idempotent, rerunning the whole step is fine. If not, make the item the unit of work, with its own record, or split the step.
- Deleting. Deleting something that is already gone should count as success. Treat "not found" as a normal result, not an error.
- Changed inputs. A repeat after a long pause may see different source data. Replace-style steps will produce the new result, which may be what you want or may silently change an earlier result. Decide which, and record the version of the input if it matters.
- Counters and totals. Compute totals from the underlying data each time rather than adding to a stored number.
Summary table
| Operation | Safe to repeat? | How to fix |
|---|---|---|
| Write file to fixed path | Yes | Use a temp file and `os.replace` |
| Append to a file | No | Write one file per work item |
| Insert row with generated ID | No | Use a key from the work item and upsert |
| Send email | No | Ledger plus a deliberate ordering |
| Charge a payment | No | Use the provider's idempotency key |
| Delete a resource | Yes, if "not found" is success | Handle the not-found result |
| Increment a counter | No | Recompute from source data |
Exercise
A step uploads report.csv to a storage bucket under the name report-<random-uuid>.csv, then saves a checkpoint. The process is killed after the upload but before the checkpoint. What goes wrong on restart, and what is the smallest change that fixes it?
Show answer
On restart the step looks unfinished and runs again, so a second object with a different random name is uploaded, leaving a duplicate. The smallest fix is to derive the object name from the work item, for example report-2023-08.csv, so the second upload targets the same object and replaces it. Optionally also check whether the object already exists and skip the upload.
Exercise
In send_once, the message is sent before the ledger is saved. Which guarantee does this give, and what failure does it allow? How would you change the order to get the opposite guarantee, and what failure would that allow?
Show answer
Sending first gives at-least-once delivery. A crash between the send and the ledger save lets the message be sent again on retry, so a duplicate is possible but a lost message is not. Saving the ledger entry first gives at-most-once delivery. A crash after the save but before the send means the retry sees the key and skips, so the message is lost, but it is never duplicated.
Exercise
You wrote a step that processes 1000 invoices and appends each result to results.json. Describe how you would test it for repeat safety, and name one change that makes it safe.
Show answer
Run the step twice on the same input and compare results.json after each run. If the file grows or contains duplicate entries after the second run, the step is not safe. One fix is to write one result file per invoice, named from the invoice ID, so each rerun replaces the same file. Another is to key entries by invoice ID and overwrite the existing entry instead of appending.