DRAFTThis page is not published. Only visible in development mode.

Events

An event is a declared type with variants that carry typed payloads. Handlers subscribe to a specific variant, and dispatch runs every matching handler synchronously, inside the dispatching transaction - in-database domain events with transactional guarantees.

Events and handlers

Declare the event's variants and payload fields, then bind handlers with create handler ... on ns::event::Variant. Inside the handler body, payload fields are available with an event_ prefix - the id field below is read as event_id. Handlers covers them in depth: several handlers per variant, scripted bodies, chained dispatch, lifecycle. Run the snippets on this page in order:

$ Declare an Event and a Handler
$ ctrl+enter to run

Dispatching

dispatch names a variant and supplies its payload. The result reports how many handlers ran; several handlers can subscribe to the same variant and each one runs:

$ Dispatch Runs Handlers in the Same Transaction
$ ctrl+enter to run

Because handlers run in the same transaction, their writes are already visible - and if the transaction rolls back, the handler's effects roll back with it:

$ The Handler Wrote to the Audit Table
$ ctrl+enter to run

Events or views?

Both react to change, so choose by what you are modeling. State that is a function of other state - counts, sums, projections - belongs in a view: declarative, incrementally maintained, impossible to forget. Events are for actions with their own meaning - "an order was placed" - where several independent reactions should fire and each reaction is an imperative step. If a change stream for external consumers is what you need, see subscriptions.

Synchronous by design
Dispatch does not queue. Handlers execute before the dispatching statement returns, and chained dispatches from within handlers execute in the same transaction as well.