
Why stale AI work should expire before it reaches a model
Learn how to expire stale AI work before model calls, define useful deadlines, cancel superseded jobs and preserve an auditable workflow trail.
Stale AI work should expire before it reaches a model. If a queued task can no longer change a decision, serve a user or produce a current result, running it is not reliability. It is delayed waste with a token bill.
The problem usually hides during normal traffic. A request enters a queue, waits briefly and starts while its assumptions are still current. Under overload, an outage or a provider slowdown, that same request may wait for twenty minutes. By then the user has left, a newer request has replaced it, the source record has changed or the action's approval window has closed. A worker still sees a valid payload and does exactly the wrong thing: it calls the model.
I treat freshness as an execution precondition, not a cleanup preference. Every perishable job needs an explicit statement of when starting it stops being useful. The worker must check that condition immediately before reserving expensive capacity, and the workflow must record expiry as a deliberate terminal outcome.
What makes AI work stale
Age alone does not make a job stale. A document migration may remain useful for a week, while an AI-generated reply suggestion can become irrelevant in seconds when a human sends a response first. Staleness is the loss of business value or validity, not simply time spent in a queue.
I use four common expiry conditions:
- Time expiry: the latest useful start or finish time has passed.
- Supersession: a newer request now represents the same intent, entity or user action.
- State invalidation: the source record, approval, permissions or workflow state no longer satisfies the job's preconditions.
- Demand cancellation: the user or calling system no longer wants the result.
Consider an agent that summarizes an inbox thread whenever a new message arrives. Five messages land during an incident and create five queued summaries. Processing all five in order produces four historical snapshots nobody requested. The current thread summary is useful; the earlier jobs have been superseded.
Now consider a nightly compliance classification over immutable documents. Those jobs can wait without becoming incorrect. They may have a service deadline, but they should not disappear merely because they are old. Expiry policy must follow product semantics. “Delete everything after ten minutes” is not a freshness design.
Why stale work is more than wasted tokens
The visible cost is the model call. The larger cost is capacity displacement. An obsolete ten-minute research job can occupy a concurrency permit while a current interactive request waits. The stale job may also call search, open a browser, retrieve documents, write intermediate state and trigger retries. One useless execution becomes load across the whole workflow.
Stale work creates five operational problems:
- It increases queue delay. Useful jobs wait behind work whose result will be discarded.
- It amplifies overload. Old backlog consumes capacity after the original traffic spike has ended.
- It produces misleading side effects. A draft, notification or recommendation may be based on state that is no longer current.
- It corrupts metrics. A model call can count as technically successful while delivering zero product value.
- It makes recovery harder. Restored workers race through an obsolete backlog instead of serving present demand.
This is why expiry belongs beside backpressure decisions. Backpressure controls what happens when capacity is unavailable. Expiry prevents accepted work from becoming an unbounded future obligation.
A durable queue should preserve work that remains valuable, not preserve every request forever.
Define product expiry before queue TTL
Message brokers offer time-to-live controls, but broker TTL and product expiry answer different questions. Broker TTL asks how long a message may remain in a queue. Product expiry asks whether executing the underlying intent is still correct.
| Control | Purpose | What it knows | Typical outcome |
|---|---|---|---|
| Broker message TTL | Limit queue retention | Message age in one queue | Discard or dead-letter |
| Retry deadline | Stop further delivery attempts | Attempt history and time window | Fail the queued job |
| Product expiry | Prevent work after value is gone | Intent, current state, version and demand | Explicit expired transition |
| Execution timeout | Bound one running attempt | Elapsed execution time | Interrupt or mark timed out |
RabbitMQ's TTL documentation states that message TTL controls how long a message can be retained in a queue and that an expired message will not be delivered. That is useful transport protection. It cannot know that version 43 of a support reply replaced version 42, or that a user withdrew approval.
Use broker TTL as a second line of defence when its semantics match the workload. Keep the domain deadline in durable application state as well. A message may move between queues, be re-created from an outbox, sit in a scheduler or be delivered just before broker expiry. The worker still needs an authoritative business check.
Store an absolute latest useful start time
A relative setting such as ttl_seconds=600 becomes ambiguous after retries, republishing and recovery. Six hundred seconds from which event: user submission, queue publication, retry or restoration from a checkpoint?
I prefer an absolute field such as latest_start_at, derived once from the product promise:
created_at = 2026-11-24T07:00:00Z
latest_start_at = 2026-11-24T07:05:00Z
latest_finish_at = 2026-11-24T07:07:00Z # only when the product needs it
The start deadline answers whether a new attempt may begin. The finish deadline is harder because execution duration is uncertain. If completion time matters, admission should compare the remaining window with a conservative duration estimate. Starting a five-minute model workflow with thirty seconds left is functionally the same as starting after expiry.
Do not let every caller invent deadlines. Define them by workload class: perhaps an interactive suggestion has thirty seconds, an asynchronous report has two hours and an immutable indexing job has no product expiry. The policy should be reviewable in code and product documentation.
Use UTC timestamps for durable coordination and a monotonic clock for measuring a running attempt. Distributed clocks can drift, so allow a small safety margin and keep time synchronization observable. A deadline is a decision boundary, not a claim that every machine has perfectly identical time.
Expire work that has been superseded
Time cannot detect every obsolete job. Many AI tasks become stale because a newer version exists. The system needs a stable key that identifies replaceable intent.
Examples include:
- the latest summary for
conversation:1842; - the current classification for
document:77and its content hash; - the newest draft for
campaign:19; - the current recommendation for
account:52and policy version.
Store a generation number, source version or immutable input hash with the run. Before execution, compare it with current authoritative state. If the queued run targets generation 8 and the entity is already at generation 10, transition generation 8 to superseded. Do not call a model to discover that its input was old.
Coalescing can prevent duplicate work earlier. Instead of enqueuing ten separate “rebuild current summary” jobs, keep one pending job per entity and let it read the latest committed version when it starts. Coalescing is not suitable when each event must be processed for legal, accounting or audit reasons. In those workflows, preserve every event and expire only derived work whose product contract permits it.
This is also an idempotency concern. A supersession key answers which intent is current; an idempotency key prevents the same accepted intent from applying its side effect twice. A production workflow often needs both.
Check freshness at the last responsible moment
Checking only when work enters the system is insufficient. A job can be valid at admission and stale after waiting. Check again after dequeue and immediately before the first expensive or irreversible operation.
A practical worker sequence is:
- load the durable run and its current state;
- acquire a short lease or state-transition lock;
- verify it is still pending and not canceled;
- compare
latest_start_atwith the authoritative clock; - compare the source version and supersession key with current state;
- verify approval, permissions and other business preconditions;
- transition atomically from
pendingtorunning; - only then reserve model capacity and create the request.
The order matters. Acquiring an expensive model permit before checking freshness lets stale work briefly block valid work. Checking without a lock can race with cancellation or a newer generation. Keep the protected section small, but make the transition conditional.
UPDATE agent_runs
SET state = 'running', started_at = :now
WHERE id = :id
AND state = 'pending'
AND latest_start_at > :now
AND generation = :current_generation;
If the update affects no row, reload the run and record the correct reason. That reason may be expired, superseded, canceled or already claimed. These are normal scheduling outcomes, not exceptions that deserve identical retries.
Implement expiry in a Laravel AI workflow
Laravel's retryUntil() method defines when the queue system should stop attempting a job. It is valuable, but it should complement the domain check rather than replace it. Queue retry exhaustion usually treats the job as failed; a stale business request should normally become expired without an alarming stack trace.
final class ExecuteAgentRun implements ShouldQueue
{
public function __construct(public readonly string $runId) {}
public function retryUntil(): DateTimeInterface
{
return AgentRun::query()->findOrFail($this->runId)->latest_start_at;
}
public function handle(AgentRunner $runner): void
{
$run = DB::transaction(function (): ?AgentRun {
$run = AgentRun::query()->lockForUpdate()->findOrFail($this->runId);
if ($run->state !== RunState::Pending) {
return null;
}
if ($run->latest_start_at->isPast()) {
$run->expire(reason: 'latest_useful_start_passed');
return null;
}
if (! $run->matchesCurrentSourceVersion()) {
$run->supersede(reason: 'newer_source_version');
return null;
}
$run->markRunning();
return $run;
});
if ($run === null) {
return;
}
$runner->execute($run);
}
}
The example is intentionally explicit. The database owns durable workflow truth. The queue transports an instruction to inspect that truth. The model runner receives only a run that has passed the freshness gate.
If the state transition must emit another message, write an outbox record in the same transaction. The transactional outbox pattern for Laravel AI workflows prevents a crash from committing the state change while losing the follow-up event.
Laravel's queue documentation covers time-based attempts, worker timeouts and job middleware. Those mechanisms bound delivery and execution. Product expiry remains an application-level decision.
Handle work that becomes stale while running
A preflight check cannot guarantee freshness for the entire execution. A long research agent may become obsolete after two of six steps. Cancellation therefore needs checkpoints.
Re-check demand and version at safe boundaries:
- before each model or external tool call;
- after a long wait, retry delay or rate-limit backoff;
- before committing a generated artifact;
- before any external side effect;
- when resuming from an agent checkpoint.
Cancellation is cooperative. A provider may not be able to stop a request already in flight, and closing the client connection may not prevent billing. The important rule is to stop starting new work, ignore late results when the run is no longer current and protect side effects with a final state and version check.
Do not roll back a useful completed step just because a later step expired. Store accepted artifacts by checkpoint, record what was skipped and let a newer run reuse safe results when their input hash matches. Expiry should reduce waste, not force every workflow back to zero.
Make expiry an auditable outcome
Silently deleting stale jobs makes the queue smaller but the system harder to explain. Operators need to know whether work completed, failed, was canceled, expired or was superseded.
I model at least these terminal states:
completed— the promised result was produced;failed— execution was attempted and could not complete;canceled— demand was explicitly withdrawn;expired— the useful execution window closed;superseded— a newer intent or source version replaced the run.
Record a reason code, decision timestamp, policy version and relevant source version. Keep payload retention separate from the audit record. Sensitive prompts and retrieved documents may need deletion, while a minimal event such as run_expired: latest_useful_start_passed remains useful for operations.
Expired work should not go to a dead-letter queue by default. A dead-letter queue is for work that needs diagnosis or recovery. Expected product expiry usually needs metrics and a terminal transition, not manual replay. Replaying it would recreate the mistake the expiry policy prevented.
Measure stale-work prevention
Expiry is not automatically good. A high expiry rate may prove that the guard works, or reveal that the service accepts more work than it can serve. Measure both the prevention and its cause.
- expired before model call, split by workload and reason;
- superseded runs and how often coalescing could avoid them;
- model calls prevented and estimated token or tool cost avoided;
- useful-window consumption at dequeue, such as p50 and p95 age divided by allowed age;
- late results discarded after in-flight cancellation;
- false expiry incidents where the product still needed the result;
- expiry by capacity pool to locate the actual bottleneck.
An increasing expiry rate is often a backpressure signal. If half of interactive jobs expire in the queue, shortening their TTL only hides the backlog faster. Reduce admission, reserve capacity, degrade the request or change the product promise. Pair expiry metrics with oldest-job age, queue wait, concurrency and completion value.
Test the policy with a virtual clock where possible. Cover the boundary exactly at the deadline, a cancellation racing with worker claim, two generations dequeued out of order, retry after expiry and a provider response arriving after supersession. The difficult bugs live between states, not in the happy path.
Production checklist
- Classify which workloads are perishable and which must never expire silently.
- Define
latest_start_atfrom product semantics, not arbitrary queue settings. - Give replaceable work a stable supersession key and source generation.
- Store deadlines and current state in durable application data.
- Use broker TTL and retry deadlines as supporting transport controls.
- Check time, cancellation, source version and approval after dequeue.
- Perform the final freshness check before reserving model capacity.
- Re-check at long-running step and side-effect boundaries.
- Represent expired and superseded as explicit terminal outcomes.
- Emit reason-coded events and preserve a minimal audit trail.
- Never retry expected expiry or replay it from a dead-letter queue.
- Alert when expiry shows that accepted demand exceeds useful capacity.
Reliable AI automation is not a system that eventually runs every queued prompt. It is a system that knows which promises remain worth keeping. By making freshness a precondition, the workflow spends model capacity on current intent, sheds obsolete demand safely and can explain exactly why a job never ran.
Sources and further reading
