Skip to main content
Back to all articles
AI Engineering 11 min readUpdated October 28, 2026

Coalescing Change Events Without Losing Background Agent Work

Combine background-agent triggers safely with a durable event inbox, bounded debounce windows, generation tracking, fenced completion, and explicit freshness metrics.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#Background Agents#Event-Driven Architecture#Durable Execution#Idempotency#TypeScript#Python
On this page

Background agents often receive several notifications about work that could be handled by one reconciliation run. A document save emits a webhook, a repository sync emits another event, and a periodic scan notices the same document again. Starting a model workflow for every notification can create redundant work. Dropping notifications while a worker is busy can lose necessary work.

For a workspace documentation assistant, I would persist the fact that a resource needs reconciliation, combine compatible change notifications, and track exactly which generation a worker completed. The agent can then regenerate a module summary from an authoritative source snapshot while the scheduler preserves changes that arrive during that run.

This design is useful when the product wants the latest correct state. Its correctness depends on the event contract, durable state transitions, and the output commit—not on asking the model to notice duplicate requests.

First decide whether notifications may be combined

Some events mean “this resource may have changed.” Others represent distinct commands that must each receive an outcome. Those are different contracts.

Several edits to the same document can often become one refresh of its derived summary. Three separate user requests to send three messages cannot automatically become one send. A deletion may require an explicit tombstone or authoritative absence check; a permission error must not be interpreted as a deleted document.

The reconciliation idea is familiar from Kubernetes controllers: observe state and move the managed resource toward the desired state. Applying that idea to an AI workflow is an architectural choice, not a guarantee provided by an agent framework.

Define a work key as an unambiguously encoded tuple of tenant, workflow, and resource. Combine only notifications whose product semantics permit reconciliation under that same key. Avoid a global debounce window that mixes tenants or unrelated resources.

IdentityWhat it protects
Delivery identityRepeated receipt of the same upstream event
Work keyIndependent scheduling and ownership for one reconciliation scope
Requested generationNew accepted work that a completed run must not accidentally erase
Source revisionThe actual input snapshot used to produce an artifact
Business action keyRepeated execution of the same consequential operation

A generation is an application bookkeeping number. It is not an upstream document version, an event timestamp, or proof that the source was read.

Accept an event durably before acknowledging it

The receiver should authenticate the sender, validate the event type and size, and resolve the tenant and resource from trusted routing context. An event’s source field is useful for identity, but does not authenticate its sender.

The CloudEvents specification defines source plus ID as the identity of a distinct event and permits duplicate deliveries to retain that identity. Use the actual producer’s contract when building an inbox key. Stripe’s webhook guidance also documents duplicate deliveries and warns that events need not arrive in generation order. These examples support designing for duplicates; they do not make every provider’s identity rules interchangeable.

In one short storage transaction, insert the inbox receipt under a unique delivery key and update the corresponding work record. Only a newly accepted receipt advances the requested generation or extends the pending window. If insertion loses a uniqueness race, acknowledge the already durable receipt after checking its scope; do not create another generation.

If the same identity arrives with incompatible event content, record an integrity failure and investigate rather than silently treating it as a harmless retry. Compare the producer’s stable event fields; per-delivery headers or signatures may legitimately change between attempts. Keep raw content out of ordinary logs.

For scheduled triggers, derive the delivery identity from the schedule and its intended occurrence time, rather than the time a retry happens to execute. Define whether missed occurrences require every run or a single current-state reconciliation. Preserve the original identity across retries of the same occurrence.

Keep pending work in the database

A useful work record contains requested and completed generations, a pending notification window, a next eligible time, the active claim’s generation and fencing token, and a lease expiry. Keep attempt history separately when needed for recovery and audit.

The receiver transaction and the worker’s claim and completion transactions must serialize their updates to the same work record. Otherwise a completion can overwrite a newer event that arrived between its read and write. PostgreSQL’s row-locking documentation describes how locking a row for update prevents competing modifications until transaction end. Conditional updates with appropriate conflict handling are another implementation option.

Enforce a unique work key during row creation as well as updates. Use a consistent lock order and retry aborted transactions according to a bounded storage policy.

Keep these transactions short. Commit the claim before calling the model or a remote tool; holding a database lock throughout generation would turn a slow request into a scheduling bottleneck.

Use queue messages as notifications that durable work may be ready. A scanner should also find eligible records so a failed notification cannot strand committed work. Conversely, receiving a queue message does not grant ownership: the worker still needs a valid durable claim. Amazon SQS’s standard-queue delivery documentation explicitly allows repeat delivery, so consumers must tolerate it.

Durable event reconciliation workflow

*Flow: authenticated event → durable work record → queue notification or scanner → atomic claim → agent execution → fenced completion. Unfinished generations return to pending work.*

The inbox, work update, and any notification-outbox entry should commit together. A separate sender can publish the notification afterward. This prevents a database commit followed by a process crash from losing the scheduling intent.

Bound the wait while combining a burst

A quiet-period debounce keeps moving the eligible time as changes arrive. Used alone, it can postpone a busy resource indefinitely. Add a maximum wait measured from the first accepted notification in the pending window.

For each window, choose the earlier of the last notification plus the quiet period and the first notification plus the maximum wait. The TypeScript function below computes that deadline. Its times come from trusted server ingestion time, not an upstream event’s timestamp.

TypeScript
type PendingWindow = Readonly<{ firstMs: number; lastMs: number }>;type ScheduledWindow = Readonly<{ window: PendingWindow; dueMs: number }>;​function milliseconds(value: number, positive = false): boolean {  return Number.isSafeInteger(value) && (positive ? value > 0 : value >= 0);}​// Call only after a new, authenticated event wins durable inbox insertion.function extendWindow(  pending: PendingWindow | null,  receivedMs: number,  quietMs: number,  maxWaitMs: number,): ScheduledWindow {  if (!milliseconds(receivedMs) || !milliseconds(quietMs, true) ||      !milliseconds(maxWaitMs, true)) {    throw new RangeError("Invalid scheduling policy");  }  if (pending && (!milliseconds(pending.firstMs) ||      !milliseconds(pending.lastMs) || pending.firstMs > pending.lastMs)) {    throw new RangeError("Invalid pending window");  }​  const firstMs = pending?.firstMs ?? receivedMs;  const lastMs = Math.max(pending?.lastMs ?? receivedMs, receivedMs);  const quietDeadline = lastMs + quietMs;  const maximumDeadline = firstMs + maxWaitMs;  if (!Number.isSafeInteger(quietDeadline) ||      !Number.isSafeInteger(maximumDeadline)) {    throw new RangeError("Scheduling timestamp overflow");  }​  return {    window: { firstMs, lastMs },    dueMs: Math.min(quietDeadline, maximumDeadline),  };}

Persist the returned window and deadline in the same transaction that advances the generation. A duplicate inbox receipt must not call this transition again. Use a consistent server or database time policy and monitor clock anomalies.

The maximum wait bounds scheduling eligibility for that pending window. It does not guarantee that a worker has capacity to start or finish by then. Track those later delays separately.

When a worker claims the current generation, consume its pending window. New accepted notifications during execution begin a new window. Completion must preserve that new window rather than restarting its quiet period. A window whose deadline has already passed should remain immediately eligible once ownership is available.

Complete only the generation that was claimed

Suppose a worker claims generation 5. While it reads documents and generates a summary, two more unique notifications advance the requested generation to 7. Successful completion may acknowledge generation 5. Setting completed equal to the latest requested generation would erase work that the worker never claimed.

The following Python transition preserves that distinction. The key and ownership values come from the scheduler’s trusted state. A storage adapter must read the current record, apply this transition, and persist it within one transaction or equivalent conditional update.

Python
from dataclasses import dataclass, replace​@dataclass(frozen=True)class WorkState:    key: str    requested: int    completed: int    active_generation: int | None    active_fence: int | None    lease_until_ms: int | None    next_due_ms: int | None​@dataclass(frozen=True)class Claim:    key: str    generation: int    fence: int​class StaleClaim(Exception):    pass​def finish_success(state: WorkState, claim: Claim, now_ms: int) -> WorkState:    """Pure transition; read, validate, and persist under one DB transaction."""    if type(now_ms) is not int or now_ms < 0:        raise ValueError("Invalid server time")    if (state.key != claim.key            or state.active_fence != claim.fence            or state.active_generation != claim.generation            or state.lease_until_ms is None            or now_ms >= state.lease_until_ms):        raise StaleClaim("Ownership is no longer current")    if not 0 <= state.completed <= claim.generation <= state.requested:        raise ValueError("Invalid generation state")​    more_work = state.requested > claim.generation    due = state.next_due_ms if more_work else None    if more_work and due is None:        due = now_ms  # Recovery fallback for a missing follow-up hint.​    return replace(        state,        completed=claim.generation,        active_generation=None,        active_fence=None,        lease_until_ms=None,        next_due_ms=due,    )​

If another worker has acquired a newer fence, or the lease has expired, the old completion is rejected. A follow-up generation retains its existing deadline. If a recovery path finds dirty work without a scheduling hint, it makes that work eligible immediately.

This is a pure state-transition example. It does not implement database locking, lease acquisition, renewal, or an external side effect. Those boundaries need integration tests in the chosen storage system. See worker races, leases, and fencing tokens for the ownership mechanism.

On a failed attempt, leave the requested generation unacknowledged. Persist retry timing and attempt limits for that generation. If a claim expires after consuming its pending window, recovery must recognize requested greater than completed and recreate a retry deadline. Do not wait for another webhook to rediscover the unfinished work.

Bind the artifact to the source snapshot

A notification tells the agent that work may be needed; it does not supply an authoritative current document. Read the resource under the correct tenant and permissions, and record the source revision or snapshot digest used for generation.

Publish a derived summary only under the application’s freshness policy. For strict current-state publication, compare the source revision again at commit and reject a stale artifact if it has changed. If the product permits an explicitly versioned historical summary, store that revision clearly and schedule the newer work. The generation counter alone cannot establish source freshness.

A late event describing an older source revision should not roll back the derived state. Reading current authoritative state often makes that event harmless. If the workflow instead consumes every transition, preserve ordering and process those transitions under a different contract.

Keep output commitment and generation acknowledgment consistent. When the artifact and scheduler state share a database, commit them in the same transaction where practical. For external actions, use a durable dispatch intent, stable business action identity, and reconciliation of uncertain outcomes. Trigger deduplication does not make an external write atomic. The side-effect idempotency pattern remains necessary.

Set limits around both admission and execution

Combining notifications reduces redundant starts, but it does not create unlimited capacity. A tenant can send unique events for many resources and still overwhelm the system. Bound event acceptance, pending keys, queued age, active workers, and model spend according to product policy.

Choose limits at the right scope. Per-resource serialization protects one summary; per-tenant concurrency and spend reservations protect neighbors; a service-wide cap protects downstream capacity. Do not charge a duplicate delivery for a new model run when no new run was admitted. Record ingestion cost separately where it matters.

Persist execution deadlines and cancellation state. A disabled workflow should stop receiving new claims, and active workers should check cancellation before expensive stages and consequential writes. Cancellation does not establish whether an earlier remote write succeeded; unresolved outcomes still need reconciliation.

Link the trigger policy to backpressure and rate limits and deadline propagation. Retry transient failures within a bounded attempt and time budget. Route persistent invalid events to an inspectable failure state without repeatedly waking a model to interpret the same error.

Retain inbox identities for the documented delivery and replay horizon. Expiring deduplication records too early can re-admit an old event. Permanent retention has a storage cost, so define replay procedures and keep business action protection independent of the inbox’s lifetime.

Measure freshness and avoided work separately

Useful measurements include received deliveries, accepted unique events, duplicate receipts, new generations, admitted runs, completed generations, and follow-up runs. Split them so a high duplicate rate is distinguishable from a high rate of legitimate change.

Measure event-to-eligibility, eligibility-to-claim, execution duration, and source-to-artifact freshness separately. Also monitor the age of the oldest unfinished generation, lease-expiry recoveries, stale completion rejections, conflicting event identities, and resources that repeatedly reach their maximum wait.

A coalescing ratio is meaningful only for a defined population: accepted compatible notifications compared with reconciliation runs for the same work keys and interval. Retry attempts and commands should not be quietly mixed into that denominator. A high ratio is useful only if freshness and correctness remain within the product’s requirements.

Use bounded labels such as workflow, trigger class, and outcome for metrics. Keep event IDs, resource keys, and tenant-specific investigation details in access-controlled traces or records. The telemetry export boundary applies to scheduler data too.

Test arrivals at the transaction boundaries

The scheduling function should preserve the first notification time during a continuous burst, enforce the maximum eligibility deadline, reject invalid timestamps, and start a fresh window after a claim. The completion transition should acknowledge only its claimed generation and preserve later arrivals.

Then test the storage integration with deliberate interleavings:

  • Two receivers insert the same event concurrently: one receipt and one generation result.
  • A process crashes after inbox acceptance: a scanner or notification outbox still exposes the work.
  • A new event arrives while the model runs: completion leaves that generation pending.
  • A lease expires and another worker claims the resource: the earlier worker cannot commit.
  • A worker crashes after taking a window: recovery schedules the uncompleted generation.
  • An external write succeeds but its response is lost: retry follows the business action’s reconciliation policy.

Add out-of-order notifications, resource deletion, permission changes, continuous hot keys, schedule catch-up, duplicate completion, and workflow disablement. Keep timestamps and source changes under test control. Offline transition tests are useful evidence, but do not prove distributed transaction behavior.

For a cheap periodic read with harmless repetition, a simpler scheduler can be enough. This design earns its complexity when events overlap, reconciliation is expensive, and changes must survive worker failures. It complements durable agent execution by deciding which work should be admitted and which generation remains unfinished.

Primary sources and topic provenance

Topic discovery: Viral Ruparel’s Your Background Agent Wakes Up More Than You Think, published October 19, 2026 on the reference site. The documentation-assistant scenario, generation-based scheduling design, code, and diagram here are original.

KEEP READING

Related engineering notes