Designing Long-Running Agents: An Architecture Philosophy from "Always-On" to "Wake-on-Demand"

    Long-running agents don't need to run continuously—they need to be continuously wakeable. This article explains an event-driven architecture for long-running agents built on inbox/outbox persistence, wake-up cycles, task orchestration with follow-up reminders, and event sourcing for memory management. It covers key components, code examples, and best practices for building stable, cost-efficient agent systems that treat the LLM as an on-demand function rather than a perpetually running process.

    Understanding “Always-On”: Continuously Available, Not Continuously Running

    When building long-running autonomous agents, a common misconception is that the agent should act like a sentinel, never tiring, constantly watching every input source. This “resident in memory + continuous inference” pattern not only wastes compute but also rapidly degrades system stability through context window bloat, stale state reads, and similar problems.

    Mobile device power management offers a useful analogy. A phone does not run at full capacity all the time; instead, it follows a rhythm of “lock screen—event trigger—wake and handle—lock again” to maximize battery life. The design philosophy for long-running agents is isomorphic: the system’s goal is to be “always wakeable,” not “always running.”

    This means the agent’s “brain”—the underlying large model—should spend the vast majority of its time on standby. All external trigger signals, whether webhook callbacks, asynchronous user messages, or timer signals, should not directly wake the inference process. Instead, they should enter a lightweight, persistent storage layer and wait in a queue. An independent scheduler service monitors this queue. When a task arrives, it loads the necessary context from storage, wakes the model for a short, focused inference (called a “wake-up cycle” or “Run”), writes the results back to storage, and then lets the agent go dormant again.

    The core advantage of this architecture is decoupling: the receiving system and the inference system are completely separated, each with its own lifecycle and scaling strategy. Even if a burst of events arrives simultaneously, the system only accumulates messages in the queue rather than overwhelming the inference engine.

    Key Architectural Component 1: Event Inbox/Outbox and Persistent State Management

    The foundation of this “standby” pattern is a reliable storage structure with event persistence. This draws on the classic “Outbox” and “Inbox” patterns.

    Event Inbox: All external inputs—including user replies, system callbacks, sensor data, and deferred task reminders produced by the agent itself—are first serialized into a standard event structure and appended to the Inbox table. This table typically exists as a database table or message queue topic, ensuring data survives agent process crashes.

    Event Outbox: At the end of each wake-up cycle, all outgoing instructions, replies, and API call requests are written to the Outbox. An independent sender process consumes the Outbox, reliably delivers messages to external systems, and updates event status based on delivery receipts.

    Under this model, the agent’s “memory” is no longer a fragile token sequence in the model’s context window, but structured state persisted in a database. Each wake-up cycle is recorded as a state snapshot. When the agent needs to resume execution, it doesn’t need to re-read the entire conversation history—it only loads the latest state summary and a small number of related key events from the state store to fully reconstruct its context.

    1. # Example: a typical event-driven agent run loop
    2. import asyncio
    3. from dataclasses import dataclass
    4. from typing import Dict, List
    5. @dataclass
    6. class AgentState:
    7. thread_id: str
    8. status: str # 'idle', 'processing', 'waiting'
    9. context_brief: Dict[str, str]
    10. pending_tasks: List[str]
    11. class LongRunningAgentLoop:
    12. def __init__(self, state_store, event_bus):
    13. self.state_store = state_store # reads/writes agent state (e.g., Redis or a relational database)
    14. self.event_bus = event_bus # event ingestion and dispatch hub
    15. async def process_next_event(self):
    16. # 1. Fetch one pending inbox event (blocking pull or polling)
    17. event = await self.event_bus.consume_inbox()
    18. if event is None:
    19. # No events: stay dormant and wait for notification
    20. # (optionally implement long polling to reduce resource consumption)
    21. return
    22. # 2. Wake the model to process the event (pseudocode; calls the model API in practice)
    23. current_state = await self.state_store.load_state(event.thread_id)
    24. response = await self.invoke_model(event.payload, current_state.context_brief)
    25. # 3. Update state and write to the outbox
    26. new_state = self.update_state(current_state, event, response)
    27. await self.state_store.save_state(event.thread_id, new_state)
    28. await self.event_bus.publish_to_outbox(event.thread_id, response.outbound_messages)
    29. # 4. If this run produced follow-up plans, schedule delayed reminders
    30. if response.scheduled_followups:
    31. for followup in response.scheduled_followups:
    32. await self.event_bus.schedule_event(followup, delay=followup.delay_seconds)
    33. def invoke_model(self, payload, brief):
    34. # Simulated LLM call
    35. return {
    36. "outbound_messages": [],
    37. "scheduled_followups": [],
    38. "state_delta": {}
    39. }

    Key Architectural Component 2: Task Orchestration and Timing Control

    For complex multi-step tasks, the “single event trigger—single reply” model falls short. The agent needs the ability to proactively initiate the next action, which is the problem the task orchestration layer solves.

    Follow-up reminders: from passive listening to active planning. If the agent only passively responds to external requests, it struggles with scenarios requiring asynchronous waiting, such as “check whether the other party replied in three days.” A “Follow-up” mechanism addresses this well. After completing a wake-up cycle, the agent can write “check something at a certain time” as a timed signal into its own inbox. When that signal fires, the scheduler wakes the agent, which sees the plan it originally set in context and continues advancing the task.

    Task dependencies and timeouts. Long-running tasks often have strict DAG (directed acyclic graph) dependencies. The orchestration layer needs to record inter-step dependencies and add timeout monitoring. For example, after the agent issues a request to call an external tool, it may enter a waiting state. If the tool call doesn’t return within two minutes, the orchestration layer should trigger a timeout event that wakes the agent to decide whether to retry, degrade, or abandon the task. This timing control is best handled at the state machine level rather than relying on model intelligence.

    Key Technical Insight: Event Sourcing and Memory Replay

    Let’s go deeper on state management optimization. Beginners often dump the entire message history into the model to provide memory. This is intuitively simple but enormously expensive in compute. A better approach borrows from the Event Sourcing pattern:

    The event store is the memory store. Every agent response to external stimuli, every internal decision, and every execution result is stored as an immutable, append-only event. When you need to rebuild a thread’s latest state, you don’t replay all events—instead, restore from a periodically generated “state snapshot,” then replay only the incremental events after that snapshot. This turns “memory compression” into a standard engineering problem and makes agent behavior easy to audit and review.

    Context compression and attention focusing. Combined with event sourcing, the system can distill key state into a structured summary at each wake-up cycle (for example: goal list, completed steps, current blockers, related object IDs). What gets sent to the model is not the raw history but this cleaned summary. This dramatically reduces inference token counts, significantly lowering per-inference cost and latency.

    1. # Example: context state update and compression strategy
    2. def update_context_brief(prev_brief, new_event):
    3. # prev_brief is a dict containing the current task goal and recent state summary
    4. # Overwrite stale temporary variables with new event info while keeping key clues
    5. brief = {
    6. "task_goal": prev_brief.get("task_goal"),
    7. "last_step_result": new_event["step_result"],
    8. "retry_count": prev_brief.get("retry_count", 0) + new_event.get("needs_retry", 0),
    9. "pending_question": new_event.get("question_to_user"),
    10. "related_entities": list(set(prev_brief["related_entities"]) | set(new_event["entity_ids"]))[:5]
    11. }
    12. return brief

    Best Practices and Debugging Strategies for the Orchestration Layer

    Although model inference is the agent’s decision-making core, system stability depends on the engineering shell around it. When building the orchestration layer, several practical techniques are worth attention:

    Strategy 1: Producer-consumer model with backpressure. The scheduler should dynamically adjust consumption rates. During event surges, prioritize low-latency “respond to user” events and defer background events like “generate daily report.” A priority queue can ensure users perceive the interaction as fluid.

    Strategy 2: Treat “idle” as a first-class state. When there are no new events to process, the agent process should actively block on event waiting rather than busy-polling (this is exactly why the example above uses a blocking consume API). If you genuinely need scheduled execution (such as checking a mailbox every 10 minutes), implement it via scheduler timer callbacks rather than in-memory sleeps, avoiding long-term occupation of worker processes.

    Strategy 3: Detailed logs and trace chains. Assign a unique TraceID to each wake-up cycle, recording the input event summary, model output actions, and actual state transitions. When a long-running task fails, this logging system helps you quickly locate where the timeline went wrong or which external call was silently dropped.

    Conclusion: From “Robot” to “Robust Asynchronous Workflow”

    Treating an agent as an “always-on virtual employee” leads into a quagmire of over-engineering. Treating it as an event-driven asynchronous workflow engine with persistent memory and planning capabilities opens up new architectural thinking.

    In summary, the secret to building long-running agents isn’t prompt engineering tricks—it’s treating the LLM as a function: invoked at key points, handling its business, then immediately exiting to release resources. Combined with persistent state management, retryable scheduled task mechanisms, and carefully designed state compression strategies, this yields a high-performance, low-cost agent service. This architecture doesn’t become obsolete as models iterate; it stands as a long-term technical asset that continues to deliver value as model capabilities grow.