Async jobs and events

From latitude-dev/latitude-llm · View interactive version

Async jobs and events is an AI agent skill from the GitHub repository latitude-dev/latitude-llm. Queues and workers, domain event publishers, async notifications or projections, or not doing that work inside HTTP handlers.

How to use this skill

Skill file

Background jobs, domain events, and side effects

When to use: Queues and workers, domain event publishers, async notifications or projections, or not doing that work inside HTTP handlers.

Side effects and eventing

Domain event naming and publisher–consumer decoupling

Domain events represent facts that happened — state transitions on an aggregate — not instructions for what should happen next. The publisher must never know or care which handlers are subscribed.

Rules

  1. Name events after what the aggregate did, not what consumers need to hear. Good: ScoreCreated, ScoreStatusChanged. Bad: ScoreDraftSaved (named to route around a handler), ScoreReadyForDiscovery (named after a consumer concern).
  2. Smell test: if you deleted every event handler, would you still emit this event because it describes a meaningfully different thing that happened? If the answer is no, the event is coupling in disguise.
  3. One canonical event per state transition. Do not split a single write operation into multiple event types to route to different handlers. If a score is written, emit ScoreCreated — regardless of whether the score is a draft or published.
  4. Consumers own their filtering logic. If a handler only cares about published scores, the handler checks the payload or re-fetches state and skips drafts. The publisher does not pre-filter by emitting different event names.
  5. Dedupe keys must not collide across lifecycle stages. If the same entity emits the same event at different lifecycle points (e.g., draft save then final publish), include the relevant discriminator in the dedupe key — not in the event name. Example: issues:discovery:${scoreId}:${status} instead of splitting into separate event types.
  6. Payload carries facts, not routing hints. Include the aggregate's current state (or the fields consumers might filter on) in the payload. Let consumers decide relevance from payload data.

When a new event type IS warranted

A new event type is justified when it represents a genuinely distinct state transition that would exist even with zero handlers — for example, ScoreDeleted is a different fact from ScoreCreated. The test: does the aggregate's lifecycle model include this transition independently of downstream concerns?

Anti-pattern: conditional event publishing

// BAD — publisher decides routing based on consumer needs
const eventName = score.draftedAt === null ? “ScorePublished” : “ScoreDraftSaved”
yield* outboxEventWriter.write({ eventName, ... })

// GOOD — one canonical event, consumers filter
yield* outboxEventWriter.write({
  eventName: “ScoreCreated”,
  payload: { scoreId: score.id, organizationId, projectId, status: score.draftedAt === null ? “published” : “draft” },
})

// Consumer side — handler owns its filtering
ScoreCreated: (event) =>
  Effect.all([
    // discovery uses status-aware dedupe key, skips drafts internally
    pub.publish(“issues”, “discovery”, event.payload, {
      dedupeKey: `issues:discovery:${event.payload.scoreId}:${event.payload.status}`,
    }),
    pub.publish(“annotation-scores”, “publishHumanAnnotation”, event.payload, {
      debounceMs: SCORE_PUBLICATION_DEBOUNCE,
    }),
  ])

Async and background tasks

Choosing between `debounceMs` and `throttleMs`

PublishOptions exposes two mutually exclusive delay fields. Both accept a window in ms and coalesce repeated publishes against dedupeKey, but they answer different questions.

debounceMs — fires after N ms of quiet on the dedupe key. Each publish within the window pushes the fire time forward and replaces the pending payload (BullMQ extend: true, replace: true). Use when the task should wait for a stream of events to settle.

Example: trace-end:run after TracesIngested. The batch event fans out one publish per deduped trace id; every new publish for the same trace resets the clock, so end-of-trace work fires once that trace is actually idle. If spans keep arriving every few seconds, that means the trace is still active — not firing is correct.

throttleMs — fires at most once per N ms per dedupe key. The first publish schedules the fire time; subsequent publishes within the window are dropped (BullMQ extend: false, replace: false). Requires dedupeKey. Use when you need a hard upper bound on fire latency and a cap on frequency, and where starvation under a continuous publish stream would be a product bug.

Example: annotation-driven alignment refresh (evaluations:automaticRefreshAlignment, 1h) and its escalation (evaluations:automaticOptimization, 8h). We want at most one refresh per evaluation per hour, firing at most 1h after the first new annotation, even if annotations keep arriving every 30 min.

Decision heuristic

Ask: if a publisher fires every 30 min forever on the same dedupeKey, what should happen?

Anti-pattern

Reaching for debounceMs when the intent is "run at most once per hour". With a continuous publish stream every publish extends the TTL and the task never fires — silent starvation. If the wording in the spec or PR is "at most once per X" or "every X at most", that is throttle semantics; use throttleMs.

// Debounce — wait for events to settle
pub.publish("trace-end", "run", payload, {
  dedupeKey: `trace-end:run:${traceId}`,
  debounceMs: TRACE_END_DEBOUNCE_MS,
})

// Throttle — at most once per window, bounded latency
pub.publish("issues", "refresh", payload, {
  dedupeKey: `issues:refresh:${issueId}`,
  throttleMs: ISSUE_REFRESH_THROTTLE_MS,
})

Name the constant to match the semantic: *_DEBOUNCE_MS vs. *_THROTTLE_MS. A constant named for one semantic that is passed as the other is a lie readers will trip over.

New infrastructure dependencies

When adding a new external system the product talks to:

  1. Add a concrete provider package in packages/platform/*-<provider>.
  2. Wire it in the app composition root from environment-driven config.
  3. Change domain only if business rules change — not for every new adapter.

For env var naming when wiring config, see env-configuration. For layer rules, see architecture-boundaries.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.