On-Demand Wake-up for Always-On Agents: Inbox and Timer Architecture
This article explores the architecture of always-on AI agents, detailing how they remain dormant and wake up only upon event arrival to minimize idle compute usage. It covers the sleep-wake loop, event inbox buffering, timer components for proactive tasks, state persistence, deployment choices, and monitoring strategies to build a resilient and efficient agent system.
The “always-on” nature of an always-on agent means users can assign tasks at any time, rather than implying the underlying process is constantly running. An agent capable of long-term autonomous work spends most of its time in a dormant state, waking up only when an event arrives and releasing resources once the task is complete. This on-demand execution model significantly reduces compute usage during idle periods.
It should be noted that the sleep-wake mechanism primarily reduces idle compute, which is not directly equivalent to a reduction in model inference costs. The price of a single model call depends on the provider’s pricing and the selected model, so specific reduction figures are not cited here. When teams estimate costs, they should base their calculations on their own call volumes, event frequencies, and individual run durations.
1. The Basic Sleep-Wake Cycle
A typical work cycle consists of five steps:
- Event occurs: A user sends a message, or an external system triggers a callback.
- System wakes up: The scheduling layer initiates an agent run.
- Context restoration and execution: The agent reads its historical state from persistent storage and calls tools to complete the task.
- State persistence: The latest progress and key data are saved.
- Re-dormancy: Compute resources are released, waiting for the next event.
Each step can fail. Network interruptions, model timeouts, and tool return exceptions are common. Therefore, the core focus of the cycle design is recoverability after failure. The following three components handle different responsibilities.
2. Event Inbox
External events should not directly invoke the agent instance. Multiple events arriving simultaneously can cause concurrency conflicts, and events may be lost if the service crashes. The inbox serves as a buffer layer to solve these two problems. It consists of three parts:
- Event table: Records event ID, source type, payload, status, retry count, lease expiration time, and creation time. Statuses typically include pending, processing, completed, and failed. Indexes should be created for the “pending” status and “lease expiration time” to allow consumers to query quickly.
- Ingestion API: Only performs authentication and basic validation, returning a 200 response immediately after writing to the database. Time-consuming operations like security checks and data cleansing are deferred to the agent execution phase.
- Worker service: Polls or listens to the event table, claims events, and starts the agent.
Keep the following points in mind during design:
- Single source of truth: The event records in the database are the standard. If the worker service goes down, a new instance can continue pulling unfinished events.
- Lease claiming: When a consumer claims an event, it writes the lease expiration time simultaneously, rather than just changing the status to “processing”. If the process crashes, a scanning task will reset the events with expired leases back to “pending”, preventing them from being permanently stuck.
- Limited retries: Each failure increments the retry count. After exceeding the limit, the event transitions to a failed state for manual or alert-based handling, avoiding infinite retries.
- Event merging: Multiple consecutive messages sent by a human can be merged into a single run. This reduces redundant model calls.
The following pseudocode demonstrates the basic logic of claiming, leasing, and failure handling:
MAX_RETRY = 3LEASE_SECONDS = 300def process_events(agent_id, worker_id):# Atomically claim a batch of pending events and write the lease expiration timebatch = db.claim_pending_events(agent_id, worker_id, lease_seconds=LEASE_SECONDS, limit=50)if not batch:returntry:agent = Agent.load_from_db(agent_id)agent.run([e.data for e in batch])# Commit state saving and event completion marking in the same transactionagent.save_state_and_mark_done([e.id for e in batch], worker_id)except Exception as exc:db.release_or_fail([e.id for e in batch], error=str(exc), max_retry=MAX_RETRY)
This code is just a skeleton. Three things need to be added before going to production.
First is idempotency. Systems usually adopt at-least-once delivery semantics, meaning the same event might be processed twice. If the agent sends emails, creates tickets, or calls payment APIs, each external action should carry an idempotency key, such as a unique identifier composed of the event ID and action sequence number. The receiver uses this to determine if the action has already been executed.
Second is timeout reclamation. A background scanning task periodically finds “processing” events with expired leases and resets them to “pending”.
Third is a dead-letter queue. Events that repeatedly fail should be moved to a separate queue or table, retaining the original payload and error information for easy troubleshooting and replay.
3. Timer Component
The inbox solves the problem of passive responses. For an agent to follow up proactively, a timer is needed. Timers fall into two categories:
- Follow-up timers: Delayed tasks set by the agent for itself. For example, after sending an email, the agent registers a check two hours later. When the time arrives, the timer writes a trigger event to the inbox.
- Scheduled timers: Periodic tasks set by humans, typically using Cron expressions. For example, compiling a news brief at 8:00 AM every day.
Timers themselves need to be persistent. If they only exist in memory, tasks will be lost when the service restarts. Note the following during implementation:
- Deduplication: The same follow-up task might be registered repeatedly. Uniqueness should be guaranteed using a business key.
- Missed compensation: For triggers missed during service downtime, a strategy must decide whether to fire them once immediately or skip them altogether.
- Timezone handling: The database should uniformly store UTC time. When displaying or parsing Cron expressions, convert them according to the user’s timezone to avoid cross-timezone and daylight saving time errors.
4. State Persistence and Context Management
Every wake-up is a cold start, so the agent must restore its state from storage.
- Session state: Short-term memory, task progress, and tool call results should be serialized and stored in a relational database or object storage. The serialization format should ideally include a version number to facilitate future migrations when the data structure upgrades.
- Long-term memory: Cross-cycle historical interactions can be vectorized and stored in a vector database. Upon waking, relevant fragments are retrieved based on the current event, and only the necessary context is placed into the model input, thereby controlling token consumption.
State writes and event completion markings must remain consistent. If they are committed separately, a situation might occur where the event is marked as complete, but the state was never saved.
5. Deployment Choices
Serverless functions are well-suited for hosting on-demand agent instances. Functions start only when triggered by an event and are reclaimed after the task ends. They incur no compute costs during dormancy, aligning perfectly with the sleep-wake approach.
Before using them, confirm the following limitations (refer to the chosen cloud provider’s documentation for specific limits):
- Execution duration limit: Functions exceeding the limit will be forcibly terminated. Long tasks should be split into multiple checkpointed steps, saving state after each step and continuing with the next event.
- Cold starts: Starting an instance from zero takes extra time. For latency-sensitive interactions, a few pre-warmed instances can be retained, though these will incur fixed costs.
- Concurrency limits: The number of simultaneously running instances is constrained by account quotas. Burst traffic might be queued or rejected.
If the agent needs to run for a long time or frequently execute complex tool calls, an always-on worker service might be simpler. Both approaches can be combined based on the scenario. The table below summarizes common trade-offs:
| Dimension | Serverless Function | Always-on Worker Service |
|---|---|---|
| Idle cost | Near zero | Fixed cost |
| Cold start | Yes | No |
| Long tasks | Requires splitting | Suitable |
| Operational overhead | Lower | Higher |
Message queues and object storage can serve as event buffers and state storage, respectively. These components are mostly managed by cloud providers, allowing teams to focus their efforts on business logic.
6. Monitoring and Risk Warnings
After deployment, at least the following metrics should be monitored: event backlog volume, latency from receipt to processing completion, failure rate and dead-letter count, average token consumption per event, cold start frequency, and the number of lease timeout reclaims. A continuous increase in lease reclaims usually indicates that the single-run duration of the agent exceeds the configured lease time, requiring parameter adjustments or task splitting.
There are three main types of risks: duplicate execution, state inconsistency, and unnoticed failures. The first is controlled by idempotency keys, the second by committing state and completion marks in the same transaction, and the third by alerts and dead-letter queues. As long as the agent can send messages externally or modify data, these measures cannot be omitted.
Conclusion
The sleep-wake mechanism allows agents to occupy no compute power normally, starting up only when events arrive. Its reliability stems from the inbox’s persistence, lease and retry mechanisms, timer deduplication and compensation, and consistent state saving. Mastering these designs is a crucial foundation for building recoverable agent systems.
