# Emitting an event

An action announces an event with `emit`, a statement written like
`reject` ([Raising a failure](raising-a-failure-reject.md)).
The event reaches its subscribers only once the action's writes have
committed.

`domains/planning/actions/complete_todo.jadpo`:

```jadpo
// domains/planning/actions/complete_todo.jadpo
action complete_todo(todo_id: Todo.id) fails TodoNotFound -> Todo {
    var todo: Todo = attempt mark_complete(todo_id)
    emit TodoCompleted {
        todo_id: todo.id
        completed_at: clock.now
    }
    return todo
}
```

## Saved with the action, delivered after it

The event is saved in the same database transaction as the action's
writes, and delivered only after that transaction commits. If the action
fails or rolls back, the event is thrown away and no subscriber ever
sees it. This is known as a transactional outbox: the **outbox** is the
table where events wait to be delivered.

## Who can emit

Only actions emit, and they emit only events. A function, a query, a
test, a fixture or a seed can't (`event.emit_invalid`). Routes,
schedules and subscribers emit by calling an action.

## No `attempt`, and nothing back

`emit` needs no `attempt`. It can't fail with a domain failure, and a
storage problem is a fault that fails the whole action
([Faults](faults.md)).

`emit` returns nothing. The caller can't wait for, or read, what
subscribers do. A route that needs the finished result waits with
`settle:` ([Waiting for follow-on work](waiting-for-follow-on-work.md)).

## Where the event is kept

The event goes in the outbox of the store the action's transaction is
in, written as the action commits, with a delivery record for each
subscriber, `pending` and due at once. An action that began no
transaction keeps them in the store it writes or, if it writes none, in
the one `events: { store: }` names, beginning its transaction there for
them.

An action that emits but writes no store, itself or through what it
calls, needs `application { events: { store: main } }`. Without it, it is
`event.store_required`, even when it reads a store.

An event nothing subscribes to is still written. Its row keeps its
type's key, its payload as the contract's JSON, when it was emitted, the
emitting action's `traceparent`, the encoding its payload was written
in, and how deep in a chain of events it is. A route whose action emits
but writes no store keeps its `Idempotency-Key`s beside its events
([Idempotent writes](idempotent-writes.md)).

## Limits

More than 1,000 events in one action, or an event whose JSON is over
64 KB, is a defect as it is emitted, and the action rolls back.
