Practical technical guides / Agent-era architecture

Queued Agent Commands Need an Expiry: Message Expiration for Decisions That Go Stale

An agent decision queued during an outage can execute hours later. Put a per-command valid-until in the message and check it right before the effect.

By Sandeep Belgavi · Published 2026-12-04 · Prepared 2026-12-03

An agent decision queued during an outage can execute hours later. Put a per-command valid-until in the message and check it right before the effect.

A decision that waits in a queue keeps aging

When an agent decides to do something, it rarely does it in the same breath. A well-built harness turns the decision into a command and puts it on a queue, so that a worker can execute it with retries, rate limits and an audit trail. That is the right shape. It also creates a gap between the moment the decision was correct and the moment it takes effect. On a quiet day that gap is a few hundred milliseconds. During an outage of the service that executes the command, it can be hours.

Enterprise messaging has a name for the fix: Message Expiration. A message carries a time after which it should no longer be acted on, and the receiver discards or reroutes it instead of processing it. The pattern predates agents by decades. What changes with agents is how much of the queue consists of commands whose correctness depends on the moment they were decided. A person who drafts a reply and leaves it in an outbox knows it is stale when they come back. A queued command does not know anything, so the system has to carry that knowledge for it.

This guide follows the help desk at Belgavi's Book Store, where an agent handles return and order cases and queues its actions for a dispatcher service.

Worked example: a three-hour dispatcher outage

The dispatcher that executes agent commands is down from 09:00 to 12:10. The agent keeps working cases, so six commands pile up. When the dispatcher recovers it drains the queue in order, one command every two minutes. Each command type has a validity window chosen by the business, not by the model.

CommandCaseDecidedValid forValid untilExecuted
Send: your return label is readyCASE-710109:052 hours11:0512:10
Hold a replacement copyCASE-710209:2030 minutes09:5012:12
Issue a refundCASE-710310:1024 hoursnext day 10:1012:14
Send: pickup today before 17:00CASE-710410:40until 17:0017:0012:16
Cancel an unshipped orderCASE-710511:151 hour12:1512:18
Send: we are looking into itCASE-710611:504 hours15:5012:20

Three policies give three different outcomes.

PolicyExecutedCorrectly skippedWrongly executedWrongly skipped
No expiry603 (CASE-7101, 7102, 7105)0
One queue TTL of 2 hours in the broker321 (CASE-7105)1 (CASE-7103)
Per-command valid-until, checked by the consumer3300

The single broker TTL is the interesting row. It treats every command alike, so it throws away a refund that was valid for a day and still runs a cancellation whose window closed three minutes earlier. The figures come from the companion example command_message_expiration, which replays this fixture; they are a constructed illustration, not data from a real outage.

Put the deadline in the command and check it where the effect happens

The command should carry an absolute valid_until computed at decision time from a policy table keyed by command type. Absolute time matters: a relative "valid for 30 minutes" is ambiguous after a retry, a redelivery or a dead-letter replay, because nobody knows which 30 minutes were meant.

from dataclasses import dataclass
from datetime import datetime, timedelta, timezone

VALIDITY = {  # set by the business, versioned with the rest of the policy
    "send_message": timedelta(hours=2),
    "hold_copy": timedelta(minutes=30),
    "issue_refund": timedelta(hours=24),
    "cancel_order": timedelta(hours=1),
    "pickup_notice": timedelta(hours=12),  # always capped by the pickup slot
    "status_message": timedelta(hours=4),
}

@dataclass(frozen=True)
class Command:
    command_id: str
    case_id: str
    kind: str
    decided_at: datetime
    valid_until: datetime
    case_version: int  # the case state the decision was based on

def new_command(command_id, case_id, kind, now, case_version, hard_deadline=None):
    until = now + VALIDITY[kind]
    if hard_deadline is not None:      # an explicit business deadline can only shorten it
        until = min(until, hard_deadline)
    return Command(command_id, case_id, kind, now, until, case_version)

def execute(cmd, now, current_case_version, effects):
    if now >= cmd.valid_until:
        return "expired: send back to the agent to decide again"
    if current_case_version != cmd.case_version:
        return "stale: case changed since the decision; decide again"
    return effects[cmd.kind](cmd)   # idempotent adapter keyed by command_id

decided = datetime(2026, 12, 3, 9, 20, tzinfo=timezone.utc)
cmd = new_command("cmd-2", "CASE-7102", "hold_copy", decided, case_version=4)
print(execute(cmd, decided + timedelta(hours=2, minutes=52), 4, {}))
# expired: send back to the agent to decide again

The check runs in the worker immediately before the side effect, and again after anything slow that happens inside the worker, such as waiting for a rate-limit slot or a human approval. A check done when the message was dequeued is not enough if the worker then waits ten minutes for a token bucket.

Broker features are a useful backstop, not the guarantee. RabbitMQ supports a per-queue x-message-ttl and a per-message expiration property, and can dead-letter expired messages. Its documentation is explicit that expired messages are discarded only when they reach the head of the queue, and that a message can expire after it was written to the socket but before the consumer received it. A broker TTL therefore bounds how long stale commands sit in the queue; only the consumer's own check decides whether an effect happens.

What happens to an expired command

Silently dropping an expired command is almost as bad as running it. The case still needs an outcome. Treat expiry as a typed result with its own route:

  • Decide again. Most expired agent commands go back to the agent with the current case state and a note saying why. The agent may reach the same decision, which is fine: the new command gets a new validity window.
  • Notify a person. Some commands, such as a refund that has expired, should never be re-decided silently. Route them to the help desk queue with the original reasoning attached.
  • Drop with a record. A status message such as "we are looking into it" can simply be dropped once a newer message has gone out. Record that it was dropped and why.

Count expirations per command type. A rising rate is an early sign that the executing service is slow or that the validity windows are tighter than the business really needs.

What stays deterministic

The model does not choose validity windows. It chooses the action; the policy table maps the action type to a window, and an explicit business deadline in the case, such as a pickup slot, can only shorten it. The clock comes from the executing service, not from a timestamp the model wrote into the command text. The expiry check, the case-version check and the routing of expired commands are ordinary code with tests. Whichever model drafts the decision, a command that is too old does not execute.

The same rule applies to the content of the effect. A message that says "today" was decided against a date. If the queue can hold it past midnight, either render the date at execution time from structured fields or let the command expire before the date changes.

Migration steps for an existing agent

  1. List every command type an agent can enqueue and write down, with the business owner, how long a decision of that type stays valid. Most teams discover two or three types where the honest answer is minutes.
  2. Add decided_at, valid_until and the case version to the command schema. Keep the fields optional for one release so old producers keep working, and treat a missing valid_until as the type's default window from decided_at.
  3. Add the check to every consumer, immediately before the side effect, and log the decision. Run it in report-only mode for a week to see how many commands would have expired.
  4. Add the expired route: re-decide, escalate or drop with a record, per command type.
  5. Configure the broker TTL as a backstop that is longer than the longest validity window, so it only cleans up what the consumer check would also reject.
  6. Add a dashboard of expirations per type and an alert on the queue age of the oldest message.

Failure modes to watch

  • Clock skew. If producers and consumers disagree about time by minutes, short windows misbehave. Use a synchronized clock and compare against the consumer's clock only.
  • Retries that renew the window. A retry must reuse the original valid_until. Creating a fresh command on retry quietly extends every deadline.
  • Expiry without the version check. A command can be within its window and still wrong because the case changed. The window bounds time; the version bounds state. You need both.
  • Expired refunds that nobody sees. If the expired route is a log line, money-related commands disappear. Route them to people.

When an agent is not needed here

Expiry is not an agent technique; it is a property of any queued decision. If the queued commands are deterministic state syncs, such as "set the shelf count to the value in the inventory system", last-write-wins with versioning is usually enough and no expiry is needed. If the dispatcher executes commands within seconds and never queues for long, a single generous broker TTL may cover the risk. Add per-command validity when commands encode a judgement that depends on time, and when the queue can realistically hold them long enough for that judgement to go stale.

Primary references and authorship

Sources checked 2026-12-03. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/command_message_expiration. Views are my own and do not represent any employer, past or present.