Handlers

Plain async functions that react to events. Concurrent by default, serialized by lanes, retried after failures.

server/orders.ts
import { createServer } from 'experimental-a2/server'
import { orders } from '@/contracts'

export const ordersServer = createServer({
  contract: orders,
  handlers: {
    created: async ({ event }) => {
      // your side effect, e.g. email the shop, idempotent via event.id:
      // await sendEmailToShop(event.payload, { idempotencyKey: event.id })
      return { type: 'shop.notified', payload: {} }
    },
  },
})

A handler runs when its event lands: a plain async function that can call a database, hit an API, or stream a model response. A2 claims the event while it runs and retries it after a crash.

createServer from experimental-a2/server binds the contract to a store and one complete handler table, so a handler can't go missing because its module was never imported. Compose the table across files by spreading objects into handlers. It is the only entry point that touches a store, and it fails loudly in a browser bundle.

Events without handlers

server/order-history.ts
import { createServer } from 'experimental-a2/server'
import { postgres } from 'experimental-a2/store-postgres'
import { orders } from '@/contracts'

export const orderHistory = createServer({
  contract: orders,
  store: postgres({ connectionString: process.env.DATABASE_URL }),
})

Handlers are optional per event type. An event without one is still logged, folded into state, and streamed; it settles in its append transaction, with no claim or scheduler message. Adding a handler later doesn't replay settled events. Append a new event or run a migration when you want that.

The context

PropertyWhat it is
ctx.eventThe triggering event: { id, type, payload, index, sessionId, createdAt }.
ctx.attemptThe durable 1-based dispatch claim for this event.
ctx.sessionThis session's handle: id, append, schedule, clear, history, state, stream, and setPresence (presence contracts only).
ctx.signalAn AbortSignal. Fires on matching abortOn events and when the attempt loses its claim (CLAIM_EXPIRED, SUPERSEDED_ATTEMPT). See Cancellation.

ctx.attempt increments on every durable claim. It can skip a number when a process dies between the claim and handler entry.

ctx.session.state(reducer) folds through ctx.event.index, so later concurrent appends don't change what this event sees. Pass { through: 'latest' } to read the current committed frontier instead.

Return what happens after success

server/return-many.ts
import { createServer } from 'experimental-a2/server'
import { orders } from '@/contracts'

export const fanout = createServer({
  contract: orders,
  handlers: {
    'shop.started': async () => {
      return orders.batch(
        { type: 'shop.notified', payload: {} },
        { type: 'driver.notified', payload: { driverId: 'driver-7' } },
      )
    },
  },
})

Return one event or an array when it should exist only if the handler succeeds. A2 marks the trigger processed and appends the batch in one atomic operation, at consecutive positions. If the handler throws or the process dies first, none of it exists. Returned events get deterministic ids, so a retry after a lost acknowledgement doesn't duplicate them.

contract.batch(...) is a type helper that keeps each event's literal type; A2 still validates at commit.

Append what should happen now

server/append-now.ts
import { createServer } from 'experimental-a2/server'
import { orders } from '@/contracts'

export const immediate = createServer({
  contract: orders,
  handlers: {
    created: async ({ session }) => {
      await session.append('notify-shop', {
        type: 'shop.notified',
        payload: {},
      })

      // The shop.notified handler may already be running here.
      // await continueCurrentWork()
    },
    'shop.notified': async () => {},
  },
})

ctx.session.append() commits immediately, so the appended event can start while its parent is still running. Use it for streaming progress, independent fan-out, or any fact that stays true even if the handler later fails. Each call is atomic.

The first argument names the append within the triggering event. A2 derives the ids of events without an id from the trigger, the name, and each event's position, so a retry gets the existing events back, whatever order parallel branches finish in. Keep the name stable; reusing it with a different batch conflicts. An explicit id wins, so different triggers can converge on one fact. Top-level server.session(id).append(...events) takes no name.

Concurrent by default

// anywhere on the server:
await ordersServer.session('order-42').append(
  { type: 'created', payload: { shopId: 'shop-7', items: [] } },
  { type: 'shop.started', payload: {} },
)

Every eligible event has its own claim, so both handlers start without waiting for each other. Log order stays stable; handler order doesn't. A failure retries that event without holding up unlaned events or other lanes.

Lanes

server/serial-orders.ts
import { createServer } from 'experimental-a2/server'
import { orders } from '@/contracts'

export const serialOrders = createServer({
  contract: orders,
  handlers: {
    created: {
      lane: 'order-work',
      handler: async () => {},
    },
    'shop.started': {
      lane: 'order-work',
      handler: async () => {},
    },
    'driver.notified': {
      lane: ({ event }) => `driver:${event.payload.driverId}`,
      handler: async ({ event }) => {
        // your work for this driver, using event.payload.driverId
      },
    },
  },
})

Use a lane when events share a resource and must not overlap. Within one session, same-lane events run one at a time in log order; different lanes and unlaned events stay concurrent. A lane is a constant (a serial queue) or a function of the validated event.

A2 stores the resolved lane at append, so a deployment can't reinterpret pending work. Lanes are per session, not distributed locks across sessions. If a lane's first unfinished event fails, later events in that lane wait; other lanes continue.

Handlers can run twice

Handlers are at-least-once. A crash after your side effect but before A2 records completion runs the handler again.

  • External side effects take an idempotency key. event.id is stable across attempts.
  • Named appends are deduplicated. A retry gets the existing events back.
  • Returned events commit with completion. They all exist with the processed marker, or none do.

When handlers throw

Throwing means "retry me." A2 records the failure and retries with backoff. The failed event blocks only its lane. After ten failed attempts it dead-letters and keeps blocking its lane until you retry or skip it.

When someone presses stop, catch the abort and return normally instead. See Cancellation.

Resolve a dead letter

A dead-lettered event waits for you. List a session's dead letters, then retry or skip each one:

// anywhere on the server, behind your own operator checks:
import { ordersServer } from '@/server'

const order = ordersServer.session(orderId)
const [dead] = await order.deadLetters()
if (dead) {
  // dead.lastError says why (null if every attempt timed out or crashed);
  // deploy the handler fix first, then:
  await order.redrive(dead.index, { action: 'retry' })
}
  • Retry. { action: 'retry' } runs the handler again with a fresh ten-failure budget. Once it completes, its lane continues.
  • Skip. { action: 'skip' } marks the event processed without running it, accepting that its effects never happen. The next event in its lane runs.

Each redrive is one atomic store operation, and it wakes the session like an append, so the lane resumes without another write. An event that isn't dead-lettered anymore is left alone: redrive reports { redriven: false }.