A Five-Component Architecture for Cutting Token Costs in Always-On AI Agents

    Always-on AI agents burn tokens even when nothing has changed. This article breaks down where that waste comes from, then introduces a five-component pipeline—inbox, timer, memory, permissions, and outbox—where each layer acts as a cost gate. It includes prompt-level constraints you can reuse directly, minimal code examples for idempotency and output gating, and four metrics to prove your optimization actually works.

    1. Diagnose first: where always-on agents leak tokens

    Always-on (resident) agents have a fundamentally different cost structure than agents that are invoked on demand. A resident agent stays in the background indefinitely and is woken on a schedule. An on-demand agent only consumes tokens when it is called. Many people migrating from the latter to the former simply reuse the “be diligent” prompt, and waste ends up concentrated in three places.

    Leak 1: Wake frequency is decoupled from content changes. Scheduled tasks fire on time regardless of whether the upstream data source has actually changed. A wake-up with nothing new costs almost as much as one with new content—it still has to load memory, retrieve sources, and make judgments.

    Leak 2: Writing summaries to “prove it wasn’t idle.” Models have a strong action bias: when asked to “report,” they tend to produce a well-structured, professional-looking report even when the conclusion is “no change.” This output carries zero information for the user but a very real cost on the bill.

    Leak 3: Scope creep and ineffective retries. Suggestions the agent raises mid-execution (“while we’re at it, we could also…”) are gradually accepted, and the task boundary keeps expanding. Meanwhile, when a source cannot be opened, the agent fails to make a failure judgment—it retries repeatedly and feeds the failed context back into the conversation, compounding costs.

    Separating these three items, total cost can be approximated as:

    1. Total cost ≈ Σ(wake count × per-turn context tokens) + output tokens + duplicated context from ineffective retries

    The optimization direction follows directly: reduce unnecessary wakes, compress per-turn context, suppress ineffective output, and set termination conditions for failures. These are exactly the problems that the five-layer structure below is designed to solve.

    2. The five-component model: turning an always-on agent into a controllable pipeline

    A mature always-on agent (whether its underlying implementation is a code-based Skill, a workflow engine, or a purely prompt-driven personal agent) can be abstracted into five components. The key insight is that these five layers are not a feature list, but a pipeline with gates, and each layer is a cost gate.

    Component Responsibility Primary cost suppressed
    Event inbox Accept work, idempotent deduplication, failure judgment Duplicated context from repeat processing
    Timer Decide when to wake and how long to wait Wake count when nothing changed
    Memory Record reported versions and watermarks Repeat pushes and context bloat
    Permissions Limit actions available after waking Rework and rewrites caused by out-of-bounds actions
    Outbox Control output cadence and granularity Summary output when there is no update

    2.1 Event inbox: make sure “the same thing” is only processed once

    The inbox’s first responsibility is idempotency. Deciding whether something is “the same thing” cannot rely on timestamps—almost every data source has an update time field, and timestamp changes often just reflect noise from scraping or rendering. A reliable approach is to construct a composite idempotency key for each task:

    1. Idempotency key = task identifier + content hash after normalization

    Normalization should strip timestamps, sort-order differences, whitespace, and templated boilerplate, keeping only semantic content. The second step is failure judgment: unreachable sources, failed structure parsing, and login requirements should all be marked as “needs verification” and enter a bounded exponential backoff retry, rather than retrying indefinitely. The third step is delivery: put new-version events that pass judgment into a pending area, awaiting batched processing at the wake-up window.

    2.2 Timer: change “polling on schedule” to “backoff + event-driven”

    A fixed-interval poll is the easiest part to get out of control. The recommended combination is:

    • Event-driven first: when the upstream supports change notifications or queue delivery, use a message notification instead of polling;
    • Idle backoff: if several consecutive wakes show no substantive change, exponentially lengthen the next wake interval until a change appears, then reset;
    • Aggregation window: don’t wake for each of multiple same-type events in a short window—merge them and process them together at the next window;
    • Watermark alignment: before waking, first check whether there is a new version this round; if there is no new version, skip the inference step entirely.

    Illustrative implementation:

    1. def next_wake(state):
    2. """Back off on consecutive idle rounds; reset to the base interval immediately when a new version appears."""
    3. if state.has_new_version:
    4. state.idle_rounds = 0
    5. else:
    6. state.idle_rounds += 1
    7. interval = min(
    8. state.base_interval * (2 ** state.idle_rounds),
    9. state.max_interval, # backoff ceiling, to avoid prolonged disconnection
    10. )
    11. return interval

    2.3 Memory: store only “what was judged,” not “what was seen”

    The thing that most easily bloats in an always-on agent is actually the context, not the logic. Memory should only retain the minimum information needed to support deduplication and noise reduction: task identifier, reported content version, last successful report time, needs-verification flag, backoff count. Full original text, historical reports, and retrieved snippets should not stay resident long-term—retrieve them on demand when needed.

    The direct benefit of holding to this is that the context volume injected on each wake is essentially constant, and per-turn cost does not grow with runtime. This is the key to flattening the long-term bill.

    2.4 Permissions: three-tier separation of read, write, and external side effects

    The permissions layer governs “what the agent can do after waking,” and it is also a cost-control measure. It is recommended to split it into three tiers:

    • Read-only: inspection, comparison, and generating suggestions, freely executable;
    • Internal writes: writing workspace files and updating memory, limited to specific paths and scopes;
    • External side effects: sending messages, changing live configuration, creating new tasks, and calling billable interfaces must be explicitly authorized and logged for audit.

    It is worth emphasizing the relationship between the permissions layer and scope creep: an agent “creating a few more tasks while it’s at it” or “expanding a few more sources” is essentially an external side effect. Bringing these into the authorization list turns cost runaway from a “prompt persuasion problem” into a “permission denial problem,” which is far more reliable.

    2.5 Outbox: when nothing changed, reply with just three words

    The outbox decides the output cadence and granularity, corresponding to two modes:

    • Instant mode: each update with substantive changes stands as a separate message, containing the task itself, the new facts, and the impact on the task;
    • Digest mode: accumulate updates into a window (for example, early each morning) and merge them into a single report.

    Whichever mode is used, when there is no substantive change, output only “No update”, and forbid generating summaries, trend analyses, or improvement suggestions to prove that work is being done. This may seem simple, but in practice it is the single most effective measure for saving output tokens.

    3. Prompt-level implementation: a reusable resident constraint

    For purely prompt-driven agents with no code layer, the five layers above need to be translated into a resident constraint in the system prompt or long-term memory. Here is a directly usable example:

    1. [Deduplication] Deduplicate by task ID + content version; a timestamp change alone does not count as an update.
    2. [Failure handling] When a source cannot be opened, mark it as "needs verification"; stop after at most two retries—do not retry repeatedly.
    3. [No update] When there is no substantive change, reply only "No update"; do not generate summaries, analyses, or suggestions.
    4. [With update] For each item, state clearly: the task itself / new facts / impact on the task.
    5. [Dedup push] Do not push the same content version again if it has already been reported.
    6. [Boundaries] Do not expand sources on your own, do not create new tasks, and do not write to external systems without authorization.
    7. [Output] Merge all changes into a single message, unless I explicitly ask for instant push.

    The mapping between this constraint and the five components is clear: the first two items govern the inbox; the third and last items govern the outbox; the fourth standardizes output structure; the fifth takes effect via version records in memory; the sixth keeps scope creep out.

    4. Code-level examples: three minimal implementations

    Idempotency and failure judgment:

    1. import hashlib
    2. def content_fingerprint(raw: str) -> str:
    3. """Take a fingerprint after stripping templated noise, to decide whether this is the same version."""
    4. lines = [ln.strip() for ln in raw.splitlines()
    5. if ln.strip() and not ln.startswith(("Updated at", "Generated at"))]
    6. return hashlib.sha256("\n".join(lines).encode()).hexdigest()[:16]
    7. def on_event(inbox, event):
    8. key = f"{event.task_id}@{content_fingerprint(event.body)}"
    9. if key in inbox.reported:
    10. return None # already-reported version, discard directly
    11. if not event.reachable:
    12. inbox.mark_unverified(event.task_id)
    13. return None # needs verification, do not enter the main flow
    14. inbox.enqueue(key, event)

    Output gating:

    1. def flush(outbox, memory):
    2. if not outbox.pending:
    3. memory.append("No update", outbox.today)
    4. return "No update" # no summary, no proving that work is being done
    5. lines = [f"[{e.task_id}] New facts: {e.new_facts}; impact: {e.impact}"
    6. for e in outbox.pending]
    7. outbox.pending.clear()
    8. for e in lines:
    9. memory.mark_reported(e)
    10. return "\n".join(lines)

    Deployment shape: this kind of resident logic typically runs on a container platform or a long-lived process. Scheduled wake-ups can be implemented via a scheduling service or delayed delivery from a message queue. Runtime logs and usage should be wired into logging services and monitoring alerts, and “wake count” and “no-update count” should be collected as first-class metrics—otherwise you cannot tell whether your optimization actually works.

    5. How to prove the savings: four metrics

    The most common failure in optimizing always-on agents is “feels cheaper but can’t articulate it.” At minimum, collect the following:

    1. Idle rate = number of wakes with no substantive change / total wake count;
    2. Ineffective push rate = number of messages unread or clearly useless to the user / total pushes;
    3. Average tokens per task = total consumption per period / number of tasks effectively processed;
    4. Duplicated context ratio = tokens generated by retries and repeated injection / total tokens.

    A real tuning record serves as a reference (single-scenario data, not a universal conclusion): a certain inspection-type always-on workflow saw its weekly idle wakes drop from about 18 to 3 after the constraints above were added. The agent’s own share of the monthly quota fell from about 75% to 30%, and with normal tasks and example calls added in, the overall reduction was about 55%, allowing a high-tier subscription to fall back to a basic tier. More notably, the long-term trend: once average tokens per task drops, growth in task count no longer translates proportionally into cost growth.

    6. Common anti-patterns

    • Trying to solve a cost problem with a “more diligent” prompt: this only amplifies output; it does not reduce wakes.
    • Deduplicating by timestamp: this almost inevitably misjudges as “there’s an update,” and the backoff mechanism then stops working.
    • Retrying failures indefinitely: this turns one network blip into hundreds of rounds of context consumption.
    • Storing full text in memory: per-turn context grows linearly with runtime.
    • Leaving scope control entirely to the prompt: a model’s resistance to “optimize it while you’re at it” is limited; the permissions layer is an unavoidable backstop.

    7. Implementation checklist

    • Define an idempotency key for each task (identifier + content fingerprint), stripping timestamp noise;
    • Change the timing strategy to “event-driven + idle backoff + aggregation window”;
    • Keep only the minimal fields needed for deduplication and noise reduction in memory; retrieve historical reports on demand;
    • Split permissions into three tiers—read-only / internal write / external side effect—with external side effects requiring explicit authorization;
    • When nothing changed, always reply “No update”; forbid generating summaries and suggestions;
    • Explicitly prohibit expanding sources and creating new tasks on your own;
    • Collect the four metrics: idle rate, ineffective push rate, average tokens per task, and duplicated context ratio.

    The value of an always-on agent comes from being continuously present, not from continuously outputting. Decoupling presence from output—waking only when necessary, processing only new versions, and saying only what needs to be said—is the root reason these systems can keep costs under control.