A user who cancels a run expects it to stop, but stopping cleanly is work: the run may be halfway through a write, halfway through a list, or holding state nobody has saved. Handle the cancel as a graceful stop: finish the current step if it is safe, save what is done so far, and mark the run cancelled with the reason. LangGraph’s checkpointing makes the save possible, since the graph state is persisted and the run can resume later if the user changes their mind. Never leave a half-written record behind: either the write completed and is recorded, or it did not run and is marked as not done.
What you need
- A run the user can cancel, with its steps and writes known
- A cancel handler that saves partial work and marks the run cancelled
- A test run to cancel halfway through, with a write in progress
Step 1: Stop at the next safe point, not mid-write
When the cancel arrives, let the current step finish if it is a read, or finish the write if it is nearly done, then stop. Never cut a write in half; a half-written record is worse than a late stop.
Step 2: Save the partial work and mark the run cancelled
Write down what is done, what is not done, and the run id, and mark the run cancelled with the user’s reason. A cancelled run with no record looks like a run that never happened.
Step 3: Test by cancelling a run with a write in progress
Start a test run, cancel it while a write is running, and confirm the run stops, the partial work is saved, and no half-written record is left behind. If a half-written record appears, the cancel cut the write.
Worked example: synthetic cancel check
The table below is a synthetic example. It shows the expected result of handling a cancel; no run was cancelled.
| Check | Expected | Result |
|---|---|---|
| Run stops after the cancel | Yes | Pass |
| Partial work is saved | Yes | Pass |
| No half-written record left | Yes | Pass |
| Run marked cancelled with reason | Yes | Pass |
Expected result (UNTESTED). the run stops cleanly, the partial work is saved, no half-written record is left, and the run is marked cancelled. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- A cancel cannot undo a write that already landed; it can only stop the next one.
- A step that hangs will delay the stop, so pair the cancel with a timeout.
- Partial work must be marked as partial, or the next run will trust it as complete.
- A cancelled run that can resume needs its state saved; a kill gives that up.
