Notifications and webhooks

When an action commits, people and systems often need to know. The shop manager should hear that tonight's delivery is on the ferry. The dispatch board should redraw. Side effects are the notifications and webhooks an action type declares for this. They are queued in the same commit as the edits, sent after it, retried until they land, and never able to undo the change that caused them

WhenAfter the commit, from the outbox
DeliveryAt least once, retried for up to 72 hours
NotificationsEmail, Slack, Teams and the in-app inbox, checked per recipient
WebhooksSigned with HMAC-SHA256, deduplicated by event id

In the platform today

Built
  • An action type's notify: entries write rows to ops.notifications after the commit, with the message filled from the parameters and objects
  • The short form names a group or a user; the full form works recipients out from the action: named users and groups, parameters, properties of object parameters (matchUser: name, email or attributes.<key>, and as: group), the objects linked to a parameter one hop away (follow), people by attribute, functions and the actor, with exclude, when, title, message, category and required
  • Each recipient is checked against the action's main object, and the people left out are recorded in ops.notification_skips with the reason, such as RECIPIENT_LACKS_ACCESS
  • The in-app inbox shows each person their notifications, with read state per person, checked against what they may read now and muted unless required, plus proposals waiting for them to approve, proposals that expired and failed writeback on an action they ran: GET /api/v2/inbox?status=unread|all&pageSize=50, POST /api/v2/inbox/{id}:read and POST /api/v2/inbox:readAll
  • The app has a bell in the Operations and Simple views and a Notifications page
  • Notification routes in ontology.yaml send those, and any event type, to email through an SMTP relay, Slack and Microsoft Teams
  • Webhooks are subscriptions as described in the webhooks reference
  • All of them share one dispatcher with the same retries for 72 hours, dead letters and replay, and a branch never sends anything
  • Templates (notifications.templates, or per destination) fill {{ path }} slots from the event, including before, after, object, changed, objectType and objectKey, and run no code
  • Email is checked per person, each getting only what they may read, rendered with their own view; a Slack or Teams channel needs every runAs and audience member to have access (RECIPIENT_LACKS_ACCESS) and gets no object events without one (RECIPIENT_UNCHECKED)
  • groupSeconds groups a destination's notifications into one message (0 by default), and mutes by event pattern or route category are kept with GET and POST /api/v2/webhooks/mutes and DELETE /api/v2/webhooks/mutes/{id}; routes with required: true are never muted
  • Each person also sets a channel per category, app, email (in app plus email) or none, for comments, mentions, watched, proposals and alerts, with GET and POST /api/v2/notification-preferences and defaults under notificationPreferences.defaults
  • People who comment on or are mentioned on an object or proposal watch it, and watchers get inbox notices of kind comment, mention and watched for new comments and for actions and undos on any object an action edited; with email those go to the person's own address as a delivery to the destination person:<user id>, through the same dispatcher, as described on discussion and object history
On request
  • The sideEffects: block with channels per entry, rendering per recipient, a daily email digest, time zones and filters in templates, the status of each side effect on the action log entry, and webhook side effects on an action type
Requirements
  • Editor or Owner on the ontology to add side effects to an action type, through a branch and a proposal
  • Administrator, or a group in webhooks.managers, to create webhook subscriptions, set the SMTP relay and notification routes and maintain the egress allow-list
  • For notifications: recipients who can see the objects the message refers to, and a verified sender domain for email
  • For webhooks: a subscription with an HTTPS destination on the egress allow-list and a runAs service principal, plus an edge agent for destinations on a private network

Side effects and writeback

Both run after the commit from the same outbox, and both retry. They differ in what they promise, and choosing the wrong one is a common design mistake

WritebackSide effects
PurposeMake a system of record match the decisionTell people and systems that something happened
OrderingStrict, per target recordPer object sequence numbers, no global order
Conflict checkYes, against the target's current valuesNo
FailureDead letter, shown on the object and the log entry, owner alertedDead letter in the delivery log, replayable, and in delivery metrics
ExamplesUpdate the ERP shipment, reassign a WMS wave, confirm an order to a customerTell the shop manager, redraw the dispatch board, post to a team channel

If a missed message would leave the operation in the wrong state, it is writeback. If a missed message would leave someone less informed, it is a side effect

Notifications

A notification sends a message to people. In the platform service it is declared on the action type with notify:, naming a group or a user and a message that can use {{parameter}} and {{object.property}}

actionTypes:
  ground-aircraft:
    notify:
      - { group: maintenance-control,
          message: "{{aircraft.fleetNumber}} grounded: {{reason}}" }
      - { group: operations,
          message: "{{aircraft.fleetNumber}} is AOG; its flights need cover. Next flight {{aircraft.nextFlightNumber}}" }

notifications:
  smtp: { host: smtp.example.com, port: 587, security: starttls,
          user: ops, password: SMTP_PASSWORD,
          from: "Ops <ops@example.com>" }
  destinations:
    control-email: { kind: email, to: [control@example.com, "group:maintenance-control"] }
    ops-slack:     { kind: slack, url: SLACK_OPS_URL }
    qa-teams:      { kind: teams, url: TEAMS_QA_URL }
  routes:
    - { group: maintenance-control, to: [ops-slack, control-email] }
    - { events: [writeback.failed, webhook.disabled], to: [ops-slack] }

Passwords and Slack and Teams URLs are secrets, so they are named as environment variables. group: in an email list expands to the members' attributes.email. Each destination can be tested with POST /api/v2/webhooks/destinations/{name}:test

The full form works the recipients out from the action. Each one gets a row only if they may read the action's main object; a group needs one member who may, and everyone left out is recorded in ops.notification_skips. A failure here never undoes the action

actionTypes:
  reroute-delivery:
    notify:
      - to:
          # the shop leads at each stop
          - { follow: delivery-stop-delivery, from: delivery,
              property: shopId, matchUser: attributes.shops }
          - { attribute: shops, value: { parameter: delivery, property: shops } }
          - { group: dispatch }
        exclude: [actor]                       # the dispatcher already knows
        when: { all: [ { left: { parameter: sailing }, op: isNot,
                         right: "Bridge, after the wind restriction lifts" } ] }
        title: "{{delivery.deliveryId}} now via the ferry"
        message: "{{actor.name}}: {{sailing}}"
        category: deliveries                   # for mutes
        required: false                        # true: never muted

On request, an action type declares its side effects in one block, with channels per entry and templates that show times in each recipient's zone

Recipients

SourceSyntax
Named users or groups{ user: … }, { group: dispatch }. A group is one row, read per member
A user parameter{ parameter: assignee }, a user id, or group:x for a group
A property of an object parameter{ parameter: qatest, property: analyst, matchUser: name }, as committed; as: group reads it as a group id
A property of linked objects{ follow: delivery-stop-delivery, from: delivery, property: shopId }, one hop; { linked: { from, link, property } } is the same
People by attribute{ attribute: shops, value: { parameter: delivery, property: shops } }, whose attribute equals or lists the value
A function{ function: …, args: … }, returning user ids, group: ids or lists of them
The actor{ actor: true }, the person who ran the action

matchUser: name, email or attributes.<key> finds the people whose field equals the value, for a name or an employee number rather than a user id

Access checks

Destinations are channels and lists chosen by an administrator, and a notification never shows a person data they could not open themselves. Access labels apply in the same way

  • Email. Checked per person and rendered with each recipient's own view
  • Slack and Teams. A channel is sent object events only when every runAs and audience member has access
  • Recipients from an action. Checked against its main object: a shop manager in another region with a row policy on region who cannot see the delivery is skipped, and the skip is recorded in ops.notification_skips with RECIPIENT_LACKS_ACCESS
  • Inbox. Checks again against what each person may read when they open it
  • On request. The check covers every object the message refers to and the skip is shown on the action log entry. With renderPerRecipient: true, the message is rendered separately for each recipient instead, and properties a recipient cannot see appear as restricted

Templates

Templates render from the committed state and can show both sides of a change with before and after, through {{ path }} slots with no code. notifications.templates, or a destination's own templates, map an event type to its message. On request, templates take filters and time zones, and every notification links to the objects it mentions

Delivery to people

Email through the SMTP relay, the in-app inbox, grouping, mutes, preferences per category, watching and notices to approvers are built; the rest of this list is delivered on request

  • Grouping. Today, groupSeconds sets a window per destination, 0 by default, and its notifications go as one message. On request, notifications of the same template to the same person within 60 seconds are grouped into one. Six reroutes during a causeway closure reach a dispatcher as one message listing six deliveries
  • Preferences. People can mute an event pattern or a route category, for good or until a time. Routes with required: true, such as a food safety hold, cannot be muted. Each person also picks a channel per category: app, email or none for comments, mentions, watched, proposals and alerts. Proposals and alerts reach email only through the routes an administrator set up, which app and none mute for that person, and none also hides them from the inbox. A change applies to what has not gone yet, because the dispatcher checks the preference again when it sends. On request, a category can switch to a daily email digest
  • Watching. Writing a comment on an object or a proposal, or being mentioned in one, subscribes a person to it. Watchers hear of new comments and of actions and undos on any object an action edited, not only its main one, unless the action's own notify: entries already reached them. Each notice is checked against what the person may read when it is written, read and sent. See discussion and object history
  • Email. Sent from your tenant's configured sender domain, with SPF, DKIM and DMARC, and a plain-text part. Bounces are recorded per recipient
  • Inbox. Each person's notifications in the app, by name or through their groups, with their own read state, behind the bell in the Operations and Simple views and on the Notifications page. A group notice is not shown to the person whose action wrote it
  • Agents. When an agent or automation proposes an action, nothing has committed yet, so the notice comes from the proposal: a waiting proposal reaches the people who may approve it in their inbox, worked out from the proposal, and leaves once it is decided or expires
notificationPreferences:
  defaults: { comments: app, mentions: email, watched: app, proposals: email, alerts: email }
POST /api/v2/notification-preferences
{ "preferences": { "comments": "email", "alerts": "none" } }

Choices are kept per person and category, and every change is audited as notification.preferences. An administrator can read or set anyone's with user. Comment, mention and watched email needs the person's attributes.email and notifications.smtp or a mail drop

Webhooks

A webhook sends an event to another system over HTTPS. Webhooks are configured as subscriptions: a destination, a set of event types and filters, and a signing secret. On request, an action type can also declare a webhook side effect that targets a named subscription, as reroute-delivery does for the dispatch board

POST /api/v2/webhooks
{
  "name": "dispatch-board",
  "url": "https://board.creamery.example/hooks/ontology",
  "events": ["action.applied", "action.proposed"],
  "filter": { "actionType": ["reroute-delivery", "top-up-delivery"],
              "objectType": ["delivery"] },
  "runAs": "svc-dispatch-board"
}

The response includes the signing secret once. runAs names the person or service account whose access shapes what is sent: an event about an object type or row it cannot see is not sent, and the skip is recorded. Object events also drop the properties it cannot see. action.reverted is delivered on request

Payload

The envelope in the platform today, with data holding the action log id, action type, object, parameters and writeback status, is in the webhooks reference. On request, the payload also lists each object the action changed, with its before and after values

Signatures

Every request carries three headers: MS-Webhook-Id, the event id; MS-Webhook-Timestamp, Unix seconds when the attempt was signed; and MS-Webhook-Signature, one or more v1= values, each a hex HMAC-SHA256 of {id}.{timestamp}.{raw body} keyed with the subscription's secret. Verify it before trusting the payload, and reject requests whose timestamp is more than 5 minutes old, which stops a captured request from being replayed later

import hmac, hashlib, time

def verify(raw_body: bytes, headers, secrets: list[str], tolerance: int = 300) -> bool:
    event_id, ts = headers["MS-Webhook-Id"], headers["MS-Webhook-Timestamp"]
    if abs(time.time() - int(ts)) > tolerance:
        return False
    signed = f"{event_id}.{ts}.".encode() + raw_body
    sigs = [v.strip()[3:] for v in headers["MS-Webhook-Signature"].split(",")
            if v.strip().startswith("v1=")]
    # During rotation two secrets are valid, so check each
    return any(
        hmac.compare_digest(hmac.new(s.encode(), signed, hashlib.sha256).hexdigest(), sig)
        for s in secrets for sig in sigs
    )

Rotating a secret with POST /api/v2/webhooks/{id}:rotateSecret issues a new one and signs with both for 24 hours, so receivers can switch without dropping events

Delivery guarantees

  • At least once. An event may arrive more than once, for example when the receiver processed it but its response timed out. Deduplicate on id, which is stable across retries
  • Order per subject. Events about one subject are sent in sequence order, and a subject whose head keeps failing holds later events for at most an hour. There is no global order. Object events carry the object's version, so a receiver can ignore a change older than one it has already applied
  • Timeout and success. The receiver has 10 seconds to answer. Any 2xx is success. Anything else, including a redirect, is a failure
  • Retries. 30 seconds, then 1, 2, 5, 15 and 30 minutes, then hourly and 3-hourly, with up to 20% jitter, for 72 hours. Email, Slack and Teams deliveries use the same schedule. Undelivered events then become dead letters and can be replayed from Admin, then Webhooks and notifications, or with POST /api/v2/webhooks/dead-letters:replay. Finished deliveries and dead letters are kept for webhooks.retentionDays, 30 by default
  • Disabling. A subscription that has failed every attempt for 72 hours, or got 410 Gone, is disabled and a webhook.disabled event goes to the notification routes. Deliveries keep queueing while it is paused or disabled and go out once it is active again

Destinations

Webhook destinations must be HTTPS, except hosts listed in webhooks.allowHttp, and must match webhooks.allowHosts when it is set. On request, destinations on a private network, such as a dispatch board inside the plant, are reached through an edge agent, which receives the event over its outbound connection and delivers it locally, so nothing on the plant network has to accept inbound traffic

Receiving webhooks reliably

A receiver that follows four rules handles every delivery pattern above correctly

  1. Verify the signature on the raw body before parsing it
  2. Answer with 2xx as soon as the event is stored, and do the work afterwards, since slow handlers cause timeouts and timeouts cause duplicates
  3. Record each event id you have processed and skip repeats
  4. Compare each object's version with the last one you applied and skip older ones
// Node.js with Express
app.post("/hooks/ontology", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.body, req.headers, secrets)) return res.sendStatus(401);
  const evt = JSON.parse(req.body.toString("utf8"));

  // Store first, answer fast, work later
  const inserted = await db.events.insertIfAbsent({ id: evt.id, payload: evt });
  res.sendStatus(204);
  // a repeat of an event already stored
  if (!inserted) return;

  if (evt.type === "object.changed" || evt.type === "object.deleted") {
    const { objectType, objectKey, op, version } = evt.data;
    // a large commit: reload the type
    if (op === "summary") return board.reload(objectType);
    const seen = await db.versions.get(objectType, objectKey);
    // older than what the board already shows
    if (seen && seen >= version) return;
    await board.apply(evt.data);
    await db.versions.set(objectType, objectKey, version);
  }
});

Designing side effects

Side effects are easy to add and easy to overdo. A few habits keep them useful

  • Notify the person who has to act. A reroute matters to the shop manager who has to staff the late delivery, not to everyone in Operations. Recipients from linked objects, such as the manager of each shop a delivery serves, are almost always better than a group
  • Say what changed and what it means. Templates that show before and after values, and the consequence in plain words, save the recipient from opening the object. "Arrives 19:05 instead of 17:40" beats "Delivery DLV-5521 was updated"
  • Leave the applier out. The person who applied the action already knows. Exclude them, as the example above does
  • Use webhooks for systems, not people. A team channel post is better built as a webhook to the chat tool than as an email to a distribution list, because it can be threaded, muted and searched where the team already works
  • Keep commitments out of side effects. Anything a customer or a regulator will rely on, such as a confirmed delivery date to a wholesale customer, belongs in writeback, with its ordering, dead letters and record of delivery

Event types

EventSent whenStatus
action.appliedAn action commitsBuilt
action.revertedAn applied action is revertedOn request
action.proposedAn agent or automation stages an action for approvalBuilt
notification.createdA notify: entry writes a notificationBuilt
writeback.deliveredA writeback row is delivered to its targetBuilt
writeback.failedA writeback row becomes a dead letterBuilt
object.changedAny object of a subscribed type changes, from sync or an action, with a filter requiredBuilt
object.deletedAn object of a subscribed type is deleted, or leaves what the subscription may seeBuilt
alert.firedA time series alert opensBuilt
alert.clearedA time series alert clearsOn request

Every built event type, with its schema, is in the webhooks reference

Failures, previews and branches

A side effect that fails never rolls back the action. Built: each delivery and its attempts are in ops.webhook_deliveries and ops.webhook_attempts, and a branch never sends. On request: the action log entry records the status of each side effect, and the person who applied the action sees a notice such as "Applied. 2 of 3 notifications sent" with a link to the details. Validate requests and test runs render every side effect as a preview and send nothing. On a branch, side effects are off, since a notification from a branch reaches a real person. On request, they can be turned on per branch by an Ontology administrator, and the branch banner says so while they are on

Limitations

  • Side effects run after the commit and can never roll an action back. A failed notification or webhook is recorded on the log entry and the edits stand
  • Webhooks are delivered at least once and in no global order. Receivers must deduplicate on the event id and compare object versions
  • Notifications skip any email recipient who cannot see an object the message refers to, so a recipient list is a maximum, not a promise. A channel gets object events only when everyone checked on it has access
  • Recipients from linked objects reach one hop. Anything further needs a function
  • Recipients worked out from an action reach email, Slack and Teams only through routes for their user or group; on request, each entry chooses its channels
  • Side effects have no conflict check. Failed deliveries become dead letters that a person can replay, but nothing reconciles them with a system of record. Messages that must arrive belong in writeback
  • On a branch, side effects are off, and validate requests and test runs send nothing
ItemDefault
Recipients per notification500
Notification grouping window0 s by default, set with groupSeconds; on request: 60 s
Webhook subscriptions per ontology50, set with webhooks.maxSubscriptions
Webhook payload256 KB. Larger data is truncated; on request: object references only
Receiver timeout10 s
Retry window72 hours, from 30 s to 3 h between attempts
Undelivered event retentionDead letters kept 30 days (webhooks.retentionDays)
Signature tolerance5 minutes

Related