Practical technical guides / Agent-era architecture

Schedule Agent Follow-Ups as Durable Timers, Not Sleeps Inside the Loop

Move multi-day agent waits into a timer table: a testable due-time rule, one claim per timer, cancellation by a racing reply and a follow-up sent once.

By Sandeep Belgavi · Published 2026-11-22

Move multi-day agent waits into a timer table: a testable due-time rule, one claim per timer, cancellation by a racing reply and a follow-up sent once.

A wait that lives in memory

An agent working a help-desk case often reaches a point where it cannot continue: it has asked the customer for an order number or a photo of a damaged book, and the right next step is to follow up if nobody answers. The quickest implementation keeps the agent loop alive and waits: await asyncio.sleep(two_days), or a scheduler call that holds a callback in the same process. It works in a demo. In a service it fails the first time the process restarts, and a service that deploys several times a day restarts much more often than once every two days.

This guide moves that wait out of the loop. The agent decides that a follow-up is needed and when. A small timer table records the decision durably. A poller fires due timers exactly once, a customer reply cancels the timer if it arrives first, and the message that leaves is written so a retried fire cannot send it twice. The worked example uses help-desk cases at the fictional Belgavi's Book Store and runs on SQLite with the Python standard library.

What the agent decides and what stays deterministic

Split the follow-up into a judgment and a mechanism. The judgment belongs to the agent or to the workflow that hosts it: is a follow-up appropriate for this case, and what should it say? The mechanism should not involve a model at all:

  • When the follow-up is due, from a rule you can test: here, two days after the question, at 09:00 UTC, moved forward to Monday if it lands on a weekend.
  • Which worker sends it, decided by an atomic claim, not by whichever process happens to be awake.
  • Whether it is still needed, decided by the state of the timer row when the claim happens.
  • Whether it was already sent, decided by a unique key on the outgoing message.

Keeping the due time as a rule rather than a model output matters more than it seems. A model asked "when should I follow up?" will give a sensible answer most of the time, but it cannot be tested exhaustively, and two runs over the same case can disagree. A rule produces the same due time for every replay, and a reviewer can read it.

The timer table

The table holds one row per pending wait. Its primary key is the case and the kind of timer, so asking the customer a second question replaces the pending timer instead of adding another one.

CREATE TABLE timers (
  case_id    TEXT NOT NULL,
  kind       TEXT NOT NULL,
  due_at     TEXT NOT NULL,
  state      TEXT NOT NULL CHECK (state IN ('pending','claimed','fired','cancelled')),
  claimed_by TEXT,
  PRIMARY KEY (case_id, kind)
);
CREATE TABLE outbox (case_id TEXT NOT NULL, message TEXT NOT NULL, timer_kind TEXT NOT NULL,
  UNIQUE (case_id, timer_kind));

Scheduling is an upsert. Cancellation and claiming are both conditional updates on state = 'pending', and each caller checks the row count to learn whether it won:

def customer_replied(db, case_id):
    cur = db.execute("UPDATE timers SET state='cancelled' "
                     "WHERE case_id=? AND kind='followup' AND state='pending'", (case_id,))
    return cur.rowcount == 1

def claim(db, worker, case_id):
    cur = db.execute("UPDATE timers SET state='claimed', claimed_by=? "
                     "WHERE case_id=? AND kind='followup' AND state='pending'", (worker, case_id))
    return cur.rowcount == 1

Firing writes the message into the outbox and marks the timer fired in one transaction. The outbox row has a unique key on the case and timer kind, so a fire that is retried after a crash finds the row already there and inserts nothing. A separate relay sends outbox rows to the customer channel, which is the transactional outbox pattern applied to a timer.

The worked run

The companion example asks three questions on Friday 20 November 2026, at 15:30, 16:30 and 17:30 UTC, on CASE-4101, CASE-4102 and CASE-4103. Two days later is a Sunday, so the rule moves all three to Monday 23 November at 09:00 UTC.

The in-memory version is modelled as a wait that a restart erases. A deploy 20 hours after the questions restarts the process, and the in-memory version sends nothing. None of the three customers hears from the store again unless a person notices.

The durable version records three pending rows. Jenya replies on CASE-4102 on Saturday; her reply cancels that timer, and customer_replied returns true. On Monday at 09:00:05 two workers poll at the same moment. Worker A claims CASE-4101 and CASE-4103; worker B finds both rows already claimed and gets nothing. Geetha's reply on CASE-4103 arrives after worker A's claim, so her cancellation finds no pending row and returns false. Worker A fires both timers, then the example fires CASE-4101 a second time, as a retry after a crash would. The outbox ends with exactly two messages, and the final states are fired, cancelled and fired.

The late reply on CASE-4103 is the one result in this run that is not what anyone wants: the store sends a follow-up to a customer who has just answered. The table makes the race visible and bounded, but it does not remove it. The relay that sends outbox messages should re-read the case and drop a follow-up when an inbound message is newer than the question, and the agent's next turn should be able to say "thanks, I see you replied" without confusion.

Migrating an existing agent loop

Most teams start with the sleeping version, so the migration matters more than the end state. A sequence that keeps the system working at each step:

  1. Inventory every place the agent waits: sleeps, scheduled callbacks, polling loops and "check back later" tool calls. Each one is a timer kind.
  2. Add the table and write timers from the existing code path, while the old wait still runs. Log both.
  3. Add the poller in shadow mode: it claims due timers and records what it would send, without sending.
  4. Compare the shadow log with what the old loop actually did for a week, including restarts. The durable path should cover every case the old one covered, plus the ones lost to restarts.
  5. Switch sending to the poller and outbox, delete the in-process waits, and keep the comparison as an alert.

The agent's tool interface changes only slightly. Instead of a tool that waits, it gets a tool that schedules: schedule_followup(case_id, kind). The tool computes the due time from the rule and returns it, so the agent can tell the customer when to expect the follow-up.

Failure modes worth testing

  • A worker claims a timer and crashes before firing. With the simple claim above, the row stays claimed forever. Add a claim deadline: a claimed row whose deadline has passed returns to pending, and the outbox key makes the second fire safe.
  • Two timers for the same case. The primary key prevents duplicates of one kind, but a "remind" timer and an "auto-close" timer can both fire. Decide whether firing one cancels the other, and test it.
  • Clock skew between workers. Compare due_at with the database's clock in the claim query rather than each worker's clock.
  • Time zones and calendars. The example uses UTC and skips weekends only. A store with public holidays needs a calendar table, and a rule keyed on the customer's local time needs a time zone database; both deserve their own tests.
  • A poller that falls behind. If the poller stops for a day, every timer becomes due at once. Rate-limit sending and order by due time so the oldest go first.

When you do not need this

If waits are short (seconds to a few minutes) and losing one on restart is harmless, an in-process timer is fine. If you already run a durable workflow engine, use its timers rather than a second table: AWS Step Functions, for example, provides a Wait state with relative seconds or an absolute timestamp, and its documentation gives a maximum wait of one year for Standard workflows and five minutes for Express workflows. The table in this guide is for systems that have a database and an agent loop but no workflow engine, which describes a large share of agent deployments.

You also do not need an agent to decide most follow-ups. "No reply in two days, send the standard reminder" is a rule, and the agent adds value only when the follow-up needs to say something specific to the case.

Verification

The companion example's six tests check the due-time rule on a Friday question, that the in-memory model loses all three waits on restart, that the reply before the due time wins and the late reply loses, that two workers claim each timer once, that a retried fire leaves one message, and that re-asking replaces a pending timer with a new due time. In your own system, add the crash test: kill the worker between claim and fire, wait past the claim deadline, and assert that the follow-up is sent exactly once.

Run the example yourself

The timer and outbox tables in SQLite, the due-time rule, claim and cancellation, and six tests for every result quoted here. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.

Primary references and authorship

Sources read 22 November 2026. Original explanation, measurements and synthetic examples by Sandeep Belgavi. Views are my own and do not represent any employer, past or present.

Related on this site: