Lesson 8.3: Long-running and background agents
Learn how to build agents that run for hours or days: durable state, checkpoints, safe resumption, waiting for people and events, triggers and heartbeats.
By the end of this lesson you will be able to explain what changes when an agent runs for hours instead of seconds, store an agent's state so that a crash does not lose its work, add checkpoints and resume safely, handle waiting for people and events without burning money, start agents from schedules and events, and monitor a run that no one is watching. You will work out that an eight-hour run on a machine that fails 0.3 times an hour needs about 33 hours of work in expectation if it must restart from the beginning every time, against about 8.2 hours with a checkpoint every ten minutes, and that polling every five minutes for eight hours costs ₹48 where waiting for a callback costs ₹1. You should have read Lessons 4.3, 5.4 and 7.4. No code is needed. The mathematics is exponentials, multiplication and division.
Everything so far has assumed that an agent runs for a few seconds or minutes while someone waits. Many of the most valuable jobs are not like that. An agent that reconciles a month of transactions, researches a topic over an afternoon, monitors a process overnight, works through a queue of five thousand documents or handles a customer case that needs a person's approval tomorrow, runs for hours or days. We call these long-running or background agents. They share a problem: over a long time, things go wrong. Machines restart. Networks drop. A person takes a day to reply. The world changes while the agent waits. An agent designed as a short script that simply runs longer will fail in all these ways. This lesson is about designing for them.
What changes when a run is long
Five things become true of long runs, and each needs an answer.
Interruption is certain. Over eight hours, a process will probably be restarted, a deployment will replace a server, a network call will hang or a rate limit will stop it. You must assume the run will be cut off at some point.
Context cannot hold the whole story. A run of thousands of steps cannot keep all its history in the model's context. It needs its own memory and summaries, as Lessons 4.3 and 4.4 explained.
The world moves. Between step 10 and step 400, records change, prices move and people reply. What the agent knew at the start may be false later.
Waiting is part of the job. The run may need to wait hours for a human or for an external process. Waiting should cost nothing.
Nobody is watching. A short run has a person waiting for the answer. A long one runs alone, so a fault can go unnoticed for hours. It must report on itself.
Durable state: the agent's memory outside the process
The first rule is that the agent's state must live outside the process that runs it. If the state is only in the variables of a running program or in a model's context, a crash destroys it. The agent must keep a durable record in a database or file store of where it is up to. A good state record holds:
The goal and constraints, exactly as given, with the version of the instructions.
The plan, the list of steps, and which are done, in progress or pending.
Results so far, or references to where they are stored.
Decisions made and facts established, as in the hand-off record of Lesson 5.3.
Pending items, including anything waiting on a person or an outside event, and what would wake it.
Counters and budgets, steps and money spent against the limits.
A log of actions taken in the world, with idempotency keys, so that nothing is done twice.
With such a record, the agent's context becomes a working copy that can be rebuilt at any time. When a run starts or restarts, it reads the state record, builds a context from it and carries on. The model remembers nothing between sessions, and the record is its memory.
Checkpoints and resumption
A checkpoint is a moment at which the state is saved so that the run can restart from there. Save one after every step that matters: after a tool result has been stored, after a decision has been made, after each unit of work in a list. The more often you save, the less work a crash loses, at the price of a little time for each save.
Resuming means starting a new process that reads the latest checkpoint and continues. For this to work safely, three properties are needed.
Every step is safe to repeat. A crash may strike after an action has happened and before the checkpoint recording it. On resumption, the agent may try the action again. If the action is "send an email" or "issue a refund", the second attempt must not happen. This is the job of idempotency keys, from Lesson 5.4: each action has a unique ID derived from the task and step, and the system records IDs it has already performed and refuses a repeat. Reading actions are safe to repeat. Writing actions need keys.
The order of recording is deliberate. A reliable pattern is to record intent before acting ("about to send email 77"), act with the idempotency key, and record completion afterwards. If a crash happens between, the resumed run sees the intent without a completion and checks the outside world, or retries the idempotent action, to settle what happened.
The state is versioned. If you change the agent's code or instructions while runs are in flight, a resumed run might meet instructions it was not started under. Store the version with the state, and decide whether old runs finish under the old version or move to the new.
Why checkpoints matter so much
The value of checkpoints grows with the length of the run. Suppose a machine fails at a steady rate of 0.3 times an hour, so the chance of getting through T hours with no failure is e raised to the power of minus 0.3 × T. For a one-hour job that is e⁻⁰·³ = 74 per cent. For an eight-hour job it is e⁻²·⁴ = 9 per cent. If a failure means starting over, the expected total work to finish an eight-hour job is not eight hours. The standard result is (e^(λT) − 1) ÷ λ, where λ is the failure rate. With λ = 0.3 and T = 8 that is (e²·⁴ − 1) ÷ 0.3 = (11.02 − 1) ÷ 0.3 = 33.4 hours. You must do the equivalent of four eight-hour jobs, on average, to get one done.
With a checkpoint every 10 minutes, a failure loses on average half of one interval, 5 minutes. Over 8 hours you expect 0.3 × 8 = 2.4 failures, so about 12 minutes of lost work, 0.2 hours. The total expected work is about 8.2 hours. The same machine, the same fault rate, and the job costs a quarter as much. For a one-hour job the difference is small, 1.17 hours without checkpoints against about 1.03 with. For an eight-hour job it is enormous.
Predict first: a job takes 8 hours and the machine fails on average 0.3 times an hour. If every failure means starting again from the beginning, would you guess the average total work is about 10 hours, 20 hours or over 30? Think it through before reading on.
The answer is over 30 hours, about 33. People tend to guess around 10, because failures sound occasional, but each failure throws away everything done so far, and long jobs are likely to meet at least one failure before finishing.
Waiting without wasting
Long runs often wait. For a person to approve something, for a payment to clear, for a file to arrive, for a time to come. How the agent waits determines whether it costs anything.
Polling means the agent repeatedly checks: "is it done yet?" If each check is a model call carrying the context, waiting is expensive. Suppose a check costs ₹0.50 and runs every 5 minutes for 8 hours. That is 8 × 60 ÷ 5 = 96 checks, ₹48, for doing nothing. Polling with plain code, which costs almost nothing per check, is far cheaper than polling with a model. Better still, avoid polling.
Event-driven waiting means the agent saves its state and stops. The system records what it is waiting for, and when the event occurs, such as an approval, a webhook or a timer, a new run of the agent starts from the saved state. While it waits, the agent is not running and costs nothing. One call to park it and one to resume is two calls, about ₹1.00 with the same example cost. The saving here is ₹47 for an eight-hour wait, and it grows with the wait.
Use event-driven waiting wherever the tools allow it. Where the outside system offers no callback, poll with cheap code and wake the model only when something has changed.
Waiting for people
Humans are the slowest dependency. An approval may take minutes or days. Design for it.
Save state, notify the person, stop. Do not hold a process open for a reply.
Set a deadline and a fallback. If there is no answer in 24 hours, remind them. After 48, escalate to someone else. Decide the fallback, such as a safe default or cancelling the action, and write it down.
Make the reply easy, with a link or a button that carries the information the agent needs to resume.
Re-check the world on resumption. The approval was given for a situation that may have changed. Before acting, confirm that the facts still hold, as the next section explains.
Expire approvals, as Lesson 6.3 said.
Triggers: how background agents start
A long-running agent does not wait for a user to type. Something starts it. Three kinds of trigger are common.
A schedule. Run every night at 2 a.m., or on the first of each month. Easy to understand. Beware overlap: if the last run has not finished when the next one starts, you may have two doing the same work. Use a lock, or a rule that a new run does not start while one is active, and give a lock a timeout.
An event. A new ticket arrives, a file is uploaded, a payment fails. The event triggers a run, perhaps through a queue. Queues smooth bursts, and let you cap how many runs happen at once, which protects rate limits and budgets. Plan for duplicates, since the same event may be delivered twice, and for events arriving out of order.
A person's request. A user starts a job that will take a while. The agent accepts it at once, returns a job ID, and works in the background. The user can check progress or is notified when it is done.
For every trigger, define how many runs may be active at once, what happens when too many arrive and what happens if the trigger fires while the agent is paused or being updated.
The world moves: re-verify before acting
During a long run, what the agent read earlier may have changed. A customer's balance moved, an invoice was already paid by someone else, the supplier changed bank details. An agent that plans at 9 a.m. and acts at 3 p.m. on its morning knowledge is acting on a stale picture.
The remedy is a rule: re-read before you write. Before any action that changes the world, fetch the current state of the thing about to be changed and check that the conditions for the action still hold. Better still, make the write conditional in the tool: "update this record only if its version is still 7", as Lesson 5.4 described. If the check fails, the agent should replan, or stop and hand back, not push on.
Also set a maximum age for facts the agent holds. A price read six hours ago is too old to quote. A permission check from yesterday is too old to rely on. Store a time with every fact and refresh the old ones.
Keeping the context healthy over a long run
A model's context cannot hold thousands of steps. Three habits keep a long run coherent.
Work in units. Divide the job into units, such as one document or one account, and handle each with a fresh context built from the state record, not a single ever-growing conversation. The record carries what matters forward.
Summarise as you go, as in Lesson 4.3, with the summary stored in the state.
Restate the goal at the start of each unit and at checkpoints, as Lesson 7.4 explained, so that it does not drift.
Seeing a run no one is watching
A long run needs to tell you how it is doing. Four things help.
Progress. A number you can read: 2,340 of 5,000 documents done, 3 failed, 14 waiting on a person.
A heartbeat. The agent records a timestamp every few minutes. A monitor alerts if the heartbeat stops, since a silent agent may be stuck or dead. Without a heartbeat, a crashed run looks identical to a slow one.
Alerts on limits and anomalies. Budget nearly used, error rate rising, a unit taking ten times as long as the others, the same unit failing three times.
A summary when done, or when stopped: what was completed, what was not and why, what needs a person. Send it where the owner will see it.
And as in Lesson 7.4, build a cancel function. A person must be able to stop a run cleanly, and the agent should handle cancellation by finishing or abandoning the current unit safely, recording its state and, where needed, undoing partial work.
Three worked examples
Example 1: a month-end reconciliation
An agent reconciles 12,000 bank transactions against the ledger each month, in units of 100. It takes about 6 hours. State is kept in a database: which units are done, the matches found and the exceptions. A checkpoint is saved after each unit, about every 3 minutes. Midway through one run, the host machine is replaced in a deployment. A new process starts, reads the record, finds unit 47 recorded as started and not finished, and re-runs it. Because every match write carries an idempotency key built from the transaction ID, nothing is entered twice. The run finishes late by minutes, not hours. The team's earlier version, which kept everything in memory, had lost an entire run in the same situation.
Example 2: an approval that took two days
A procurement agent prepares a large order and needs a director's approval. It saves its state, sends the request with the evidence and stops. Two days later, the director approves from a phone. The approval wakes a new run. The agent re-reads the supplier's price and finds it has risen 4 per cent, outside the tolerance set by its instructions. It does not place the order. It reports the change to the director with the new figure and asks again. A design that acted on the old approval would have bought at a price nobody had agreed.
Example 3: a schedule that overlapped
A nightly agent that cleaned up customer records started at 1 a.m. One night the job took longer than usual, and when the next scheduled start came 24 hours later, the earlier run was still going. Both worked on the same records, and some were updated twice with conflicting values. The team added a lock with a six-hour timeout, an ownership rule that gave each record to one run and a heartbeat, so that if a run died the lock would be freed and an alert raised.
A design checklist for long-running agents
1. Move the state out of the process into a durable store: goal, plan, progress, results, decisions, pending items, counters and an action log.
2. Rebuild the context from the state on every start.
3. Checkpoint after each meaningful step, and choose an interval from the failure rate and the cost of lost work.
4. Give every write action an idempotency key. Record intent, act, record completion.
5. Version the instructions and state. Decide how in-flight runs meet changes.
6. Use event-driven waiting instead of polling with a model. Poll with plain code where there is no callback.
7. For people, save state, notify, set a deadline and fallback, and re-check on resumption.
8. Define triggers, concurrency limits, locks and duplicate handling.
9. Re-read before you write. Use conditional writes. Set a maximum age for facts.
10. Work in units with fresh contexts, and summarise and restate the goal.
11. Report progress, heartbeat, alerts and a summary. Provide a clean cancel.
Common mistakes
State in memory only. A restart loses everything.
Restarting from the beginning. Failures multiply the work. Checkpoint.
Actions that cannot be repeated safely. A resumed run sends two emails.
Polling with the model. It spends money to learn nothing.
Acting on a stale approval or old facts. Re-read before you write.
Overlapping scheduled runs. Use locks and ownership.
One endless conversation. Work in units with fresh contexts.
No heartbeat. A dead run looks like a slow one.
Changing the agent mid-run without a plan. Version the state.
No cancel. You cannot stop a run that has gone wrong.
Key takeaways
Long runs differ from short ones: interruption is certain, context cannot hold the story, the world moves, waiting is part of the job and nobody is watching.
Keep state outside the process in a durable record, and rebuild the context from it. The record is the agent's memory.
Checkpoint and resume, with idempotency keys so that repeated steps do no harm. For an eight-hour job at 0.3 failures an hour, expect about 33 hours of work if you restart each time, against about 8.2 with ten-minute checkpoints.
Wait by parking the agent and resuming on an event. Polling with the model for eight hours cost ₹48 in the example, against ₹1 for parking.
Start agents by schedule, event or request, with limits on concurrency, locks and handling of duplicates.
Re-read before you write, use conditional writes and expire old facts. Approvals and plans can go stale.
Report progress, send a heartbeat, alert on anomalies and provide a clean cancel.
Check yourself
1. Why must an agent's state live outside the running process?
A crash or restart destroys anything held only in the process or in the model's context. A durable record lets a new process resume.
2. What does an idempotency key do for a resumed run?
It lets the system recognise an action already done and refuse to do it again, so a retry after a crash does no harm.
3. A job takes 2 hours and the failure rate is 0.5 an hour. With no checkpoints, what is the expected work?
(e¹ − 1) ÷ 0.5 = (2.718 − 1) ÷ 0.5 = 3.44 hours.
4. A wait of 6 hours is polled every 10 minutes with a model call costing ₹0.40. What does it cost?
6 × 60 ÷ 10 = 36 checks, 36 × ₹0.40 = ₹14.40.
5. Why re-read a record before changing it after a long wait?
The world may have changed during the wait. The approval or the plan may no longer fit, so the agent must check the conditions still hold.
6. What is a heartbeat for?
It shows the agent is alive. If the heartbeat stops, a monitor raises an alert, so a crashed run is not mistaken for a slow one.
Try this
Set aside seventy-five minutes.
1. Pick a job that would take an agent over an hour. Divide it into units.
2. Design the state record: list every field it needs to resume after a crash.
3. For every action the agent takes in the world, write the idempotency key and decide what is recorded before and after.
4. Estimate your failure rate and job length. Use the checkpoint simulator to choose a checkpoint interval.
5. List every place the agent waits. For each, decide poll or park, and use the wait simulator to see the cost.
6. Write the trigger, the concurrency limit and the lock rule. Write what happens if two runs overlap.
7. Design the progress report, the heartbeat, the alerts and the cancel behaviour.
A good result is a design for one long-running agent: state record, checkpoint plan, idempotency rules, waiting and trigger design, re-verification rules and monitoring. Lesson 8.4 steps back from one agent to the organisation: how to deploy and govern a whole set of them.
Tags: Agentic AI Long-running agents Durable state Checkpoints Background tasks