← posts / agents

An always-on agent skeleton in 150 lines: durable inbox, timers and outbox

A runnable SQLite sketch of the pieces Anthropic's always-on agent guide names: a deduplicating inbox, one active worker, timers and an outbox, with tests for a crashed run and a duplicate webhook.

if.codesNov 17, 2026 · 8 min read#agents#python#sqlite#architectureAI-assisted

Anthropic published a guide to building always-on agents on 13 November. Its core idea is that an always-on agent spends most of its time asleep and wakes for short runs: each run receives an event, works inside a session, and saves state before sleeping again. The guide names five primitives for this cycle: an event inbox, timers, memory, permissions and an outbox.

This post builds the three that are plain plumbing (inbox, timers, outbox) in about 150 lines of Python and SQLite, plus a single-worker lease. The model call is a stub you replace. The point is to see where each piece breaks and to have tests that prove it recovers. Everything below runs with the standard library only; the full file, assembled in order, is the sum of the blocks shown.

The shape: the inbox is the source of truth

The guide's inbox has three parts: a durable list of events (usually a database table), a handler that writes events (usually an HTTP endpoint), and a background worker that reads them. Two rules matter most. Events are deduplicated using the unique ID from the source, and the inbox, not the worker, is the source of truth, so a replacement worker can re-read pending events and retry a crashed run.

A conceptual view of an inbox acting as the single source of truth for agent events.
A conceptual view of an inbox acting as the single source of truth for agent events.

Here is the schema. The three tables map to the inbox, timers and outbox; the lease table is how we get one active worker.

import sqlite3
import time

db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE inbox (
  id INTEGER PRIMARY KEY,
  source_id TEXT UNIQUE NOT NULL,
  session TEXT NOT NULL,
  body TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  created REAL NOT NULL
);
CREATE TABLE timers (
  id INTEGER PRIMARY KEY,
  session TEXT NOT NULL,
  due REAL NOT NULL,
  every REAL,
  payload TEXT NOT NULL,
  done INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE outbox (
  id INTEGER PRIMARY KEY,
  session TEXT NOT NULL,
  body TEXT NOT NULL,
  sent INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE lease (name TEXT PRIMARY KEY, owner TEXT, until REAL);
""")

The UNIQUE constraint on source_id is the deduplication. The webhook handler only stores and acknowledges; the guide says to acknowledge events quickly and defer deeper checks, such as prompt-injection screening, to the run.

def ingest(source_id, session, body):
    """Webhook handler: store and acknowledge. True if new, False if a duplicate."""
    cur = db.execute(
        "INSERT OR IGNORE INTO inbox(source_id, session, body, created) VALUES (?,?,?,?)",
        (source_id, session, body, time.time()),
    )
    return cur.rowcount == 1

Use the provider's own delivery or message ID as source_id. If a provider retries a slow webhook, the retry lands on the constraint and nothing is duplicated.

Timers live outside the inbox

The guide distinguishes two kinds of timer. Follow-ups are deadlines the agent sets for itself. Schedules are recurring tasks that also track their recurrence. It keeps timers in their own durable store, separate from the inbox, which holds only ready work. A scheduler polls at a fixed interval, finds due timers, marks follow-ups done, advances schedules to their next occurrence and adds an event to the inbox.

Timers allow an agent to schedule future wake-up calls independently of the main event stream.
Timers allow an agent to schedule future wake-up calls independently of the main event stream.

The detail worth copying is the deterministic source ID. If the scheduler crashes between inserting the event and updating the timer, the next tick inserts the same timer:<id>:<due> ID, which the inbox ignores.

def add_timer(session, due, payload, every=None):
    db.execute(
        "INSERT INTO timers(session, due, every, payload) VALUES (?,?,?,?)",
        (session, due, every, payload),
    )


def tick_timers(now=None):
    """Move due timers into the inbox. Safe to run twice: the source id is deterministic."""
    now = time.time() if now is None else now
    due_rows = db.execute(
        "SELECT id, session, due, every, payload FROM timers WHERE done=0 AND due<=?",
        (now,),
    ).fetchall()
    for tid, session, due, every, payload in due_rows:
        db.execute("BEGIN")
        db.execute(
            "INSERT OR IGNORE INTO inbox(source_id, session, body, created) VALUES (?,?,?,?)",
            (f"timer:{tid}:{due}", session, payload, now),
        )
        if every:  # schedule: jump to the next future occurrence
            nxt = due + every * (int((now - due) // every) + 1)
            db.execute("UPDATE timers SET due=? WHERE id=?", (nxt, tid))
        else:  # follow-up: fire once
            db.execute("UPDATE timers SET done=1 WHERE id=?", (tid,))
        db.execute("COMMIT")

Note the nxt arithmetic: if the machine was off for three days, a daily schedule fires once and jumps to the next future slot instead of firing three times to catch up. Whether you want catch-up is a product decision; make it explicitly.

One active worker, one run at a time

The guide recommends one worker per inbox to prevent duplicated or overwritten work, and batching: several pending events, such as consecutive user messages, merge into one run. For mid-run events it lists three options: queue for the next run, fold into the current run, or interrupt and restart. This sketch takes the first and simplest: new events wait for the next run.

The lease mechanism ensures that only one worker process is active at any given time.
The lease mechanism ensures that only one worker process is active at any given time.

The lease is a row that a worker may take if it is free, expired or already its own. The upsert only updates when that condition holds, so rowcount tells you whether you won.

def acquire_lease(owner, ttl=60.0):
    """One active worker: take the lease if it is free, expired, or already ours."""
    now = time.time()
    cur = db.execute(
        """INSERT INTO lease(name, owner, until) VALUES ('worker', ?, ?)
           ON CONFLICT(name) DO UPDATE SET owner=excluded.owner, until=excluded.until
           WHERE lease.until < ? OR lease.owner = excluded.owner""",
        (owner, now + ttl, now),
    )
    return cur.rowcount == 1


def release_lease(owner):
    db.execute("UPDATE lease SET until=0 WHERE name='worker' AND owner=?", (owner,))


def run_once(handle, owner="worker-1"):
    """One run: batch the pending events of one session, call the agent, commit."""
    if not acquire_lease(owner):
        return False
    try:
        first = db.execute(
            "SELECT session FROM inbox WHERE status='pending' ORDER BY id LIMIT 1"
        ).fetchone()
        if not first:
            return False
        session = first[0]
        events = db.execute(
            "SELECT id, body FROM inbox WHERE status='pending' AND session=? ORDER BY id",
            (session,),
        ).fetchall()
        reply = handle(session, [body for _, body in events])  # may raise: nothing is lost
        db.execute("BEGIN")
        db.executemany("UPDATE inbox SET status='done' WHERE id=?", [(i,) for i, _ in events])
        if reply:
            db.execute("INSERT INTO outbox(session, body) VALUES (?,?)", (session, reply))
        db.execute("COMMIT")
        return True
    finally:
        release_lease(owner)

The key ordering: events are marked done and the reply is written to the outbox in one transaction, after the agent returns. If handle raises, nothing changed, the lease is released, and the same events are still pending for the next attempt. The TTL covers the harder case where the whole process dies and never reaches finally: after 60 seconds another worker can take over. Choose a TTL longer than your longest run, or renew the lease during the run.

Want an agent pipeline you can actually inspect?I build multi-step agents with human approval steps. The estimate is free.

The outbox

The guide says a run ends by sending a message, sending nothing, or deferring a tool call for user input. A simple send tool is enough for most agents; a formal outbox is for pacing messages or recovering from delivery errors. The outbox is a table of outgoing messages drained by a dispatcher, analogous to the worker.

def drain_outbox(send):
    """At-least-once delivery: send first, mark sent after."""
    for oid, session, body in db.execute(
        "SELECT id, session, body FROM outbox WHERE sent=0 ORDER BY id"
    ).fetchall():
        send(session, body)
        db.execute("UPDATE outbox SET sent=1 WHERE id=?", (oid,))

Sending first and marking after means a crash between the two re-sends the message on restart: at-least-once, not exactly-once. If your channel supports an idempotency key, pass the outbox id as that key.

Prove each failure mode

These checks cover the three failures the guide's summary names: a slow webhook that the provider retries, a crashed run, and duplicated work. Append them to the file and run it.

if __name__ == "__main__":
    # 1. A duplicate webhook is stored once.
    assert ingest("msg-1", "alice", "hello") is True
    assert ingest("msg-1", "alice", "hello") is False

    # 2. A crashed run leaves the event pending; the retry succeeds and replies once.
    calls = []

    def flaky(session, bodies):
        calls.append(bodies)
        if len(calls) == 1:
            raise RuntimeError("model call failed")
        return f"got {len(bodies)} message(s)"

    try:
        run_once(flaky)
    except RuntimeError:
        pass
    assert db.execute("SELECT COUNT(*) FROM inbox WHERE status='pending'").fetchone()[0] == 1
    assert run_once(flaky) is True
    assert db.execute("SELECT COUNT(*) FROM outbox").fetchone()[0] == 1

    # 3. Running the timer tick twice fires a follow-up once.
    add_timer("alice", due=100.0, payload="follow up on the quote")
    tick_timers(now=200.0)
    tick_timers(now=200.0)
    assert db.execute("SELECT COUNT(*) FROM inbox WHERE source_id LIKE 'timer:%'").fetchone()[0] == 1

    # 4. A second worker cannot run while the first holds the lease.
    assert acquire_lease("worker-1") is True
    assert acquire_lease("worker-2") is False
    release_lease("worker-1")

    sent = []
    drain_outbox(lambda s, b: sent.append((s, b)))
    print("all checks passed;", sent)

Expected output:

all checks passed; [('alice', 'got 1 message(s)')]

I ran this exact file with Python 3 and it prints that line. Check 2 is the one to keep in your own suite after you swap in a real model call: make handle fail at different points and assert that the inbox row is still pending afterwards.

What this skeleton leaves out

  • Memory. The guide says to store only what the agent cannot look up again, keep user instructions in their own file loaded every run, and keep a per-task file of done and remaining work. Add a durable store keyed by session and load it inside handle.
  • Permissions. The guide suggests a proxy outside the agent's environment that injects credentials into outgoing requests, so the agent never handles them, and a hook that can defer a tool call: the run ends with the session saved mid-call, and the user's answer returns as an inbox event that resumes the session. In this sketch that answer would simply be another ingest call.
  • Context growth. Long sessions need compaction or a fresh session. The guide warns both lose detail, so persist important facts to memory during the run.
  • A real database. SQLite in memory shows the logic. For several machines, use a database with row locks or a durable execution engine, which the guide also names as an alternative to a hand-built scheduler.

Start with one inbox per user, as the guide suggests, and split only when you need more parallelism.

Sources

if.codesI build RAG, AI integrations and agent pipelines on Go and Python backends — and write about it here.
// keep reading

More posts on AI and backends.

// free quote

Read something you need? I’ll quote it for free.

RAG, AI integrations, agents or the backend underneath — tell me what you have and what should change. I read every request myself.

Free · no commitment

Tell me what you have. I’ll tell you what it takes.

1Describe the projectA few sentences is enough — about two minutes.
2I review itI read it myself and may ask a follow-up question.
3You get a free quoteScope, approach and estimate — yours to keep, no strings.
What kind of project is it?
Free and without obligation. Your details are used only to reply — see the privacy policy.