Long-Running AI Agents: Event-Driven Architecture and On-Demand Wake-Ups

    Long-running AI agents do not need continuously active models. This article explains how event-driven wake-ups, persistent state, bounded execution, and reliable message delivery support ongoing tasks without uncontrolled resource use. It covers the core architecture, retry and observability practices, and the trade-offs of keeping agents available while letting them idle between tasks.

    1. The Hidden Costs of Always-On Processes

    A common approach to building a long-running autonomous agent is to put an automation script or coding assistant on a server and leave it running around the clock, continuously listening and executing. This is straightforward, but it creates three problems.

    First, a persistent loop consumes resources even when there is no useful work. The process keeps checking state or waiting for API responses, regardless of whether it produces results.

    Second, retries can spiral out of control. If an external API fails and the script has no backoff policy, it may repeat requests at a high rate. Logs grow rapidly, and compute resources are spent on an unproductive loop.

    Third, state held in process memory is difficult to recover. A restart or crash can erase task progress and make troubleshooting harder.

    “Always available” should therefore describe the system’s ability to receive work—not the model’s execution state. Separating system availability from the lifecycle of an individual inference run is the foundation of a more reliable design.

    2. A Standby Model: Let the Agent Sleep Like a Phone

    A phone appears to be online all day, but its screen is usually off and much of the system operates in a low-power state. A notification, alarm, or user interaction wakes it briefly. Once the work is done, it returns to standby.

    An agent can follow the same pattern. The model does not need to run continuously. It wakes only when one of three signals arrives:

    1. External callbacks, such as webhook notifications from third-party services.
    2. User messages, such as new chat messages or emails.
    3. Scheduled tasks or task-specific follow-up times.

    Each wake-up is a Run: a short, focused unit of execution that releases resources when it finishes. A long-running task consists of multiple Runs, with persistent storage carrying state between them.

    3. Core Components and Data Flow

    A standby architecture typically has five components.

    Event Inbox

    The Event Inbox is a persistent event table where all incoming inputs are queued. Ingestion handles deduplication and records the event source and retry count.

    External systems do not invoke the model directly. This allows events to remain available even when the model is temporarily unavailable.

    Dispatcher

    The Dispatcher is a lightweight background service that claims pending events from the inbox. When no events are available, it waits without invoking the model.

    Claiming an event must be atomic so that multiple workers do not process the same event simultaneously.

    Run

    A Run loads the session’s saved state, invokes the model for a round of reasoning and tool use, saves the updated state, and exits.

    Each Run should have step and token limits to keep a single execution from running out of control.

    Outbox

    Replies, emails, and notifications generated by the model are first written to an Outbox. A separate delivery process sends them.

    If delivery fails, the system can retry delivery without rerunning the model. This separation also helps prevent duplicate sends.

    Follow-Up Timer

    Before a Run ends, the agent can register a future wake-up time and a condition to check. For example: “In three days, if the recipient still has not replied, send a reminder.”

    Unlike a fixed recurring schedule, a follow-up time depends on the progress of the task.

    The following pseudocode illustrates how these components interact. It is not an interface for any particular framework.

    1. def worker_loop():
    2. while True:
    3. event = inbox.claim_next() # Atomically claim a pending event
    4. if event is None:
    5. wait_for_signal() # Wait without invoking the model
    6. continue
    7. try:
    8. run_once(event)
    9. inbox.mark_done(event.id)
    10. except TransientError:
    11. inbox.schedule_retry(event.id, backoff(event.attempts))
    12. except PermanentError:
    13. inbox.dead_letter(event.id) # Move to dead letter for manual review
    14. def run_once(event):
    15. state = load_state(event.session_id)
    16. result = agent.step(state, event, max_steps=8, max_tokens=4000)
    17. save_state(event.session_id, result.state)
    18. for msg in result.messages:
    19. outbox.enqueue(msg)
    20. for timer in result.timers:
    21. scheduler.schedule(timer.at, timer.payload)

    This code illustrates three principles: queue events before processing them, keep state in persistent storage, and route outgoing side effects through the Outbox.

    4. Key Design Practices

    Idempotency

    Receiving the same event more than once should not change the intended outcome. Common techniques include assigning each event a unique identifier, checking whether it has already been completed, and supplying idempotency keys when sending emails or calling external APIs.

    Backoff and Retry Limits

    Failed operations should use exponential backoff—for example, doubling the wait between attempts—and have a maximum retry count.

    Events that exceed the limit should move to a dead-letter queue for manual investigation. This prevents endless retries and excessive log growth.

    Execution Budgets

    Set maximum steps, token usage, and execution time for each Run. When a budget is exhausted, the agent should save its progress and end the Run rather than continue trying.

    Externalized State

    Store context, task progress, and intermediate results in a database rather than process memory. Processes can then restart and resume work by consuming events from the inbox.

    Observability

    Record the trigger source, duration, token usage, and outcome of every Run. Resource and cost problems are often difficult to identify until usage is tracked per execution.

    Housekeeping During Idle Periods

    Idle periods can accommodate low-priority maintenance tasks, such as summarizing recent experience, compressing conversation history, and removing expired state.

    These tasks resemble memory consolidation during sleep: they help preserve the quality of later work without requiring continuous model activity.

    5. Revisiting the Monitoring Script Failure

    Consider the monitoring-script failure described earlier. Three issues explain the outcome: the persistent loop had no sleep mechanism, API failures had neither backoff nor retry limits, and logging lacked severity levels and rotation. The same error was recorded indefinitely.

    The redesign is straightforward. Monitoring events enter the inbox first. Failed API operations are requeued with backoff. After repeated failures reach a threshold, the event moves to a dead-letter queue and triggers an alert.

    With no new events, the system consumes very few resources. It remains available over long periods while tying compute use more closely to useful work.

    6. Boundaries and Trade-Offs

    A standby architecture is not a universal solution. Several trade-offs matter.

    First, event-driven processing introduces queueing latency and additional components to maintain. Applications requiring millisecond-level responses need a separate assessment of whether that complexity is justified.

    Second, each Run should remain relatively short. Very long tasks must be split into smaller units linked by persistent state. Splitting them too finely, however, increases the overhead of reconstructing context. The right balance depends on the task.

    Third, follow-up schedules need explicit stopping conditions. Otherwise, an agent may send reminders indefinitely, interrupting users and wasting resources.

    Ultimately, reliable long-running agents depend less on how long a model can work continuously than on how well the system bounds each wake-up, keeps execution lightweight, and preserves state between Runs.