Skip to content
ModuleM2 — The platform’s architecture and contracts
After this session you canRead a message on the bus and say who sent it, who consumes it and what happens when a consumer fails; explain the outbox and live push.
TimeFacilitated: 62 min · On your own: 62 min
Before you startM2-S1: your request traces. Larkspur Lab with the bus tap from M0-S2 and RabbitMQ’s management port-forward (workbench).
Go deeperBus and socket contracts · Real-time internals · Data model and events

◆ Orientation (1 min) — The half you cannot see from the screen

Section titled “◆ Orientation (1 min) — The half you cannot see from the screen”

In M2-S1’s second trace, one save fanned out to a reaction, the search index and the timeline, all after the user had their answer. That fan-out is the message bus, and most of what the platform does happens there: automation, workflow moves, notifications, search, history. In ACDE you ran the bus as infrastructure: one queue per service, retries, dead letters, the correlation id travelling with each message (ACDE M1-S2). In ACE you consumed its events as an integrator (ACE M6-S1). Here you read the messages themselves, as contracts: what kinds exist, what each carries, who sends and who receives, what is guaranteed when something fails, and how the same messages become live updates on Maya Idris’s phone.

▤ Concept (14 min) — Commands, events, and what travels with them

Section titled “▤ Concept (14 min) — Commands, events, and what travels with them”

Every message on the bus is one of two kinds, and the difference decides who receives it.

  • A command is an instruction: do this. It is addressed to the one service that owns the action and is handled by exactly one handler there. Creating or updating a record, executing a workflow action, scheduling a job and sending a push notification are commands. A reaction that updates another record, for example, sends the data service a command rather than writing to the database itself.
  • An event is a fact: this happened. It is published once and fanned out to every service that subscribes to it, each through its own queue. A record created, updated or archived, a workflow step reached, an access right changed, a scheduled job fired: all events.

The rule of thumb when you read a design: the owner of a piece of data receives commands about it and publishes events about it. Everyone else sends commands to the owner, or listens to its events.

The platform’s messages are TypeScript classes in a shared package that every service uses, built on an open-source bus library, @node-ts/bus. Each declares three things:

PartExampleWhat it is for
$nameosos/data-entry/data-entry-updatedThe wire name and routing key, namespaced osos/<domain>/<message>. Consumers subscribe by it.
$version1The contract version of the payload’s shape. Today every message is at 1.
The payloaddataEntry, userId, normalizedEntity, valueDiff, …The constructor’s arguments, read-only, serialised as they are.

Three rules follow, and they are the same rules you will apply to your own extensions in M6 and M10. The $name is the contract, not the class: renaming the class is harmless; changing the string breaks every subscriber. A few names even contain historical typos (a scheduler event is …-triggerd), and they stay, because correcting them would break the wire. An addition is not a new version: when an optional field is added (as the entry-updated push gained the record’s updateIdentifier on 1.10), $version stays 1, because a consumer that ignores the field is unaffected. An incompatible change needs a new version and a period in which both are supported, because old and new services will be running side by side during an upgrade.

An event about a record carries the record itself, as the data service stored it (you read its shape in ACE, and its stored form in M2-S3), plus who did it (userId), the entity in brief (normalizedEntity: normalized name, name, type and module) and, for updates, what changed (valueDiff, the fields before and after). That is why a consumer rarely needs to call back for the record: the event is self-sufficient at the moment it was published.

Next to the payload, every message carries attributes, which the bus moves in the message’s properties rather than in its body:

  • messageId, unique to this message, and the correlation id of the request or message that caused it (or NO_TRACE_ID when there was none). That is how M2-S1’s id appeared in services that never saw the HTTP request.
  • Sticky attributes: the acting user’s id, the space and, in a multi-tenant cell, the tenant. Sticky means they are copied automatically onto every message a handler publishes while handling this one, so a chain of reactions three steps long still knows who started it and in which space.

When a service receives a message, it builds a fresh per-message context, the bus equivalent of M2-S1’s request scope: the correlation id goes into the logging context, the space and tenant scopes are opened, and the acting user’s profile is loaded. The handler then runs exactly as a controller would, scoped and attributed. A message that arrives without a space is dead-lettered without running its handler (M2-S1).

Queues, retries and dead letters, from the inside

Section titled “Queues, retries and dead letters, from the inside”

You know the delivery contract from ACDE: each service has one durable queue, a failed message is retried (five times by default) and then moved to that service’s dead-letter queue. Two consequences matter for an engineer reading a design.

Each consumer fails alone. Because every subscriber of an event has its own queue, a timeline handler that keeps failing on a malformed record dead-letters its copy of the event while the reaction, indexing and notification services process theirs normally. A failure is therefore never “the event failed”; it is “service X failed on the event”, and the evidence is in service X’s dead-letter queue and logs.

Delivery is at least once. A message may be delivered again: after a retry, after a broker reconnect, after a pod is replaced mid-handler. Every handler that changes something must therefore be safe to run twice. You met this as a builder rule in ACE (“every chain that creates something is harmless if it runs twice”); here you see why it exists.

What happens to the messages a handler sends while it runs, if it then fails? Before 1.10 they had already left: a handler could publish “work order raised”, then fail on its next line, be retried, and publish it again, or leave downstream services acting on something that was rolled back. On the 1.10 line every service runs with a transactional outbox: a send or publish issued inside a handler is held in memory and dispatched to the broker only when the handler finishes successfully. If the handler fails, everything it staged is discarded with it. A message sent outside a handler (from an HTTP request, say) goes out immediately, as before.

flowchart LR
  M["message arrives"] --> H["handler runs"]
  H -->|"publish / send"| O["staged in memory<br/>(the outbox)"]
  H -->|"succeeds"| F["staged messages<br/>dispatched to the broker"]
  H -->|"fails"| X["staged messages<br/>discarded; message retried"]
  O --> F
  O --> X

What to notice: a handler’s outgoing messages are all or nothing with the handler’s own success. A message that is about to be retried can no longer have caused effects downstream.

Three facts keep you from over-reading it. It is on for every service, with no setting to turn it on or off: it is a property of the bus library’s version, pinned exactly for that reason. It is in memory, per handler run, not a database table, so it protects against a handler failing, not against the process dying between the handler’s end and the dispatch. And it has one sharp edge: a handler that sends a command and then waits for the reply now waits for ever, because the command cannot leave until the handler finishes. That is why the reaction engine’s multi-step runs were rebuilt as sagas, whose state is stored and resumed when the reply arrives; you open them in M4-S2.

For each group of events the platform has one emitter and many consumers. The map below is the one you will use most when you trace work after a save.

Events aboutPublished byConsumed by
Records (created, updated, archived, …)The data service’s write engineReactions (triggers), workflow (requests, time limits), timeline, notifications, audit, users, Functions, and the data service itself (history, proxy and aggregate refresh, cache)
Definitions (entities, views, queries, modules)The data serviceReactions, timeline, audit, workflow, the dependency graph, caches
Workflow movesThe workflow serviceReactions, timeline, the data service (history, request state), audit
Reactions and announcementsThe reaction serviceThe reaction service itself (chains, announced events), notifications
SchedulerThe scheduler serviceReactions (timers), timeline, report schedules
Users, spaces, access, tokensThe identity server and the data serviceThe data service (permission recompute, caches), notifications, audit

Search indexing is fed differently: the indexing service consumes record and definition changes through its own work queues (M3-S4).

Some work is too big for one message: re-indexing an entity, updating ten thousand records, exporting a large list. For these the platform uses BullMQ, an open-source job queue kept in Redis. A service adds a job (often a parent with many chunk children), and workers, discovered by a booter like every other pluggable piece (M2-S1), take chunks off the queue, report progress, and retry chunks that fail. When the work finishes, the service publishes a job-executed event on the bus. An HTTP call that starts such work answers at once with 202 Accepted and a job id, and the caller follows the job by its id. So “jobs” and “messages” are two planes: Redis carries the work, the bus carries the facts about it. You meet the time-based half of this, the scheduler, in M4-S1.

The browser’s live updates (a record changing under your eyes, a notification toast, a workflow moving on) come from the public socket service, web-socket-service. It is a bus consumer: it handles selected events (record updated, record archived, workflow events, notification records, job executed) and re-emits each one over Socket.IO, a WebSocket library, to the clients that joined the matching room: a user’s own room for notifications, a record’s room for its updates, a job’s room for its progress. ACE taught you to subscribe as a client (ACE M6-S2); here is what is behind it.

  • The connection is authenticated once, in the handshake, by validating the same OAuth access token the HTTP API uses (or the anonymous token on public pages). A handshake without a token is refused.
  • On a multi-tenant cell the socket’s tenant comes from the host name, and every room is scoped to that tenant, so a client cannot join another tenant’s room.
  • Delivery is best effort: an event is pushed to whoever is in the room at that moment, and nothing is kept for a disconnected client. The platform’s own UI treats a push as “something changed: re-read it”, which is why it uses HTTP for the truth and the socket for speed.

Two more services complete the real-time picture. rtc-service hands out tokens for audio and video calls; it is not a socket server. And an internal service-to-service relay over sockets existed until 1.8; the bus reference records it as removed in 1.10, replaced by the bus and the Redis job cache. Some older pages still describe it; do not design on it.

flowchart LR
  D["data service<br/>publishes record updated"] --> B[("bus")]
  B --> Q1["reaction queue"]
  B --> Q2["timeline queue"]
  B --> Q3["web-socket queue"]
  Q3 --> W["web-socket service"]
  W -->|"room: this record"| P1["Omar's browser"]
  W -->|"room: this record"| P2["Maya's phone"]

What to notice: the live update is just one more consumer of the same event. If the web-socket service is down, nothing else is affected; the screens simply stop updating until people refresh.

▶ Guided demo (10 min) — One update, seen on the bus

Section titled “▶ Guided demo (10 min) — One update, seen on the bus”

In Larkspur Lab. The tap from M0-S2 catches published messages; for this session you also catch deliveries, so you can see the fan-out.

  1. Switch the tracer on, bind the tap to deliveries as well, and empty it:

    Terminal window
    kubectl -n datastores exec deploy/rabbitmq -- rabbitmqctl trace_on -p lk
    curl $R -X POST http://localhost:15672/api/bindings/lk/e/amq.rabbitmq.trace/q/acm-tap -d '{"routing_key":"deliver.#"}'
    curl $R -X DELETE http://localhost:15672/api/queues/lk/acm-tap/contents
  2. In the portal, open the work order Replace mechanical seal on P-101 and change its Description. Save.

  3. Read the tap, one line per trace message:

    Terminal window
    curl $R -X POST http://localhost:15672/api/queues/lk/acm-tap/get \
    -d '{"count":50,"ackmode":"ack_requeue_false","encoding":"auto"}' > tap.json
    jq -r '.[] | .routing_key' tap.json

    One publish.… line for the record-updated event, followed by several deliver.… lines, one per service queue that received it.

  4. Open the published one and read its contract:

    Terminal window
    jq '[.[] | select(.routing_key | startswith("publish"))][0].payload | fromjson
    | {name: ."$name", version: ."$version", entity: .normalizedEntity.normalizedName,
    changed: [.valueDiff[]?.path | join(".")], user: .userId}' tap.json

    Screenshot pending The terminal showing the tap's routing keys for one save: a single publish line followed by several deliver lines naming service queues What to notice: one publish, many deliveries. Each deliver line names a queue, and each queue belongs to one consuming service.

  5. Read the message’s attributes, which the tracer keeps under the original message’s properties: jq '[.[] | select(.routing_key | startswith("publish"))][0].properties.headers.properties' tap.json. Find the correlation id and the sticky user and space.

  6. Look at the queue list for the same moment: kubectl -n datastores exec deploy/rabbitmq -- rabbitmqctl list_queues -p lk name consumers messages. Every service queue has a consumer and 0 messages waiting: the fan-out was processed in well under a second.

✓ Practice (4 min) — Commands and events

Section titled “✓ Practice (4 min) — Commands and events”
PracticeChoose one answer.

A reaction in Quality and Compliance must change a supplier’s rating, which the data service owns. What does the reaction service put on the bus?

  1. Explanation for A

    ✗ Incorrect

    Not this one: an event reports a fact that has already happened; nothing has changed yet. See Two kinds of message.

  2. Explanation for B

    ✓ Correct

    Correct: the owner receives commands about its data and publishes events about what it did. See Two kinds of message.

  3. Explanation for C

    ✗ Incorrect

    Not this one: services never write each other’s data; they ask the owner. See Two kinds of message.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A release renames the class behind osos/data-entry/data-entry-archived and keeps its $name. What must the consumers of that event change?

  1. Explanation for A

    ✗ Incorrect

    Not this one: consumers inside the platform share the package, but the routing is by name, not class. See A message is a contract.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the version changes only when the payload changes incompatibly. See A message is a contract.

  3. Explanation for C

    ✓ Correct

    Correct: the wire name is the contract; the class name is a code detail. See A message is a contract.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A reaction three steps into a chain creates a work order. The work order’s history says it was created by Omar Haddad, who only changed a priority at the start. Why Omar?

  1. Explanation for A

    ✓ Correct

    Correct: sticky attributes ride from a triggering message onto everything it causes, unless a step sets another executor (M4-S2). See What travels beside the payload.

  2. Explanation for B

    ✗ Incorrect

    Not this one: who acts is carried with the messages, not looked up from the module. See What travels beside the payload.

  3. Explanation for C

    ✗ Incorrect

    Not this one: every message carries the acting user as a sticky attribute. See What travels beside the payload.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

Goal. Three real messages from Larkspur Lab, each read as a contract: its name and kind, who sent it, who consumed it, and what happens if a consumer fails.

Before you start. Larkspur Lab; the tracer on and the tap bound to publish.# and deliver.# (demo step 1); R set (workbench). A file m2-s2-envelopes.md.

Envelope 1: a record update

  1. Empty the tap. In the portal, change the Description of Inspect bearing noise on C-201 and save. Save the tap to env1.json (demo step 3).
  2. From the published message, write down its $name, $version, the entity’s normalized name, which fields valueDiff says changed, and the correlation id from the attributes.
  3. From the deliver lines, list the queues that received it.

Envelope 2: a workflow move

  1. Empty the tap. Open the work order Lubricate bearings on P-102 (at Raised) and run its workflow action to Planned. Save the tap to env2.json.
  2. List every published message’s $name in order. Pick the one that reports the step change and read it as in step 2.

Envelope 3: a message caused by a reaction

  1. Empty the tap. Set Priority to Urgent on Lubricate bearings on P-102. Wait five seconds. Save the tap to env3.json.
  2. Find a message that was published while the reaction ran (its correlation id is the same as the save’s, but it was not published by the save itself). Read its $name and decide whether it is a command or an event.

Name sender, consumers and failure path

  1. For each envelope, name the sender: use the fan-out table and, to confirm, the tracer’s connection header, which gives the publishing pod’s address (jq '.[0].properties.headers.connection' envN.json, then kubectl -n larkspur get pods -o wide).
  2. For each, name the consumers from its deliver lines, as services.
  3. For each, write the failure path: what happens if one named consumer fails on it every time (retries, its dead-letter queue, the others), and what the outbox means for any message that consumer would have sent while handling it.
  4. Switch the tracer off (workbench).
  5. Under the three envelopes, write one sentence comparing envelope 1’s consumers with envelope 3’s sender: the same service appears in both. Which, and why?

Check.

  • For each envelope you recorded its $name, kind (command or event) and correlation id.
  • Envelope 1 shows the fields that changed, from valueDiff.
  • Each envelope names its sender, with the fan-out table or the connection as evidence.
  • Each envelope lists its consuming services from the deliver lines.
  • Each failure path names the retry count, the dead-letter queue and what the outbox discards.

Pass condition. All five checks hold, and envelope 3’s correlation id equals the urgent save’s.

If something goes wrong

What you seeWhat to do
The tap holds hundreds of messagesOther activity in the lab (the nightly plan, indexing) is published too. Empty the tap right before your action, act, and read at once; filter with jq on the entity’s normalized name.
Only publish. lines, no deliver. linesThe deliver.# binding is missing: repeat demo step 1’s second command.
`payloadfromjson` fails
No workflow action on the work orderThe work order is not at Raised, or you are not its step’s owner; use Inspect bearing noise on C-201 after resetting the seed, or take ownership first.
Envelope 3 shows no reaction messageCheck that the reaction Notify planner of urgent work order is active, and that the priority actually changed (it may already have been Urgent from M2-S1; set it back to Medium, then to Urgent).
Model answer

Envelope 1. osos/data-entry/data-entry-updated, version 1, an event. Entity work_orders; valueDiff names description. Correlation id: the save’s. Sender: the data service (it owns records; the connection is the core-data pod). Consumers: one deliver line per subscribing service queue, typically reaction, workflow, timeline, notification, audit, web-socket and data service itself, plus Functions where provisioned. Failure path: if, say, the timeline’s handler fails every time, its copy is retried five times and moved to the timeline queue’s dead-letter queue; every other consumer processes its own copy normally; anything the timeline handler staged while failing is discarded by the outbox, so no half-made history entry is announced.

Envelope 2. Several messages in order: the workflow action executed, the step Raised exited, the step Planned reached (osos/workflow/… names), then the record-updated event for the work order’s stored workflow state. The step change is an event published by the workflow service. Consumers: reactions, timeline, the data service (history), audit, web-socket.

Envelope 3. After the update event (published by the data service), the reaction service matched Notify planner of urgent work order and, while running it, sent a command, osos/data-entry/create-data-entry, to create the notification record, carrying the same correlation id and Rami Aziz as the sticky user. Its consumer is the one service that owns that action, the data service. If that handler fails every time, the command is retried and dead-lettered in that service’s queue, and the reaction run records the failure (you read run records in M4-S2).

Step 12. The reaction service is a consumer of envelope 1 and the sender of envelope 3: it receives record events, matches reactions, and acts by sending commands to the owners of the data. That is the whole of automation, in two messages.

◇ Worked scenario (3 min) — The scorecard that stopped updating

Section titled “◇ Worked scenario (3 min) — The scorecard that stopped updating”

Tariq Saleh reports that the Supplier Scorecard stopped changing three days ago, though non-conformances are being closed every day. Nothing else seems wrong. Reason through it before you read each step.

Step 1: where would the work happen? Closing a non-conformance is a record update (a workflow move, then the stored state). The scorecard is an aggregate: the data service refreshes it when the records it aggregates change, as one of the consumers of record events. So the question is which consumer is not doing its part.

Step 2: what does the bus say? You list the queues. Every service queue has a consumer and no backlog, but the data service’s dead-letter queue holds a few hundred messages, growing by a few each day. The data service itself is answering requests normally.

Step 3: what is in the dead letters? Reading one with the management view (on the dead-letter queue, which nothing consumes, so reading it steals nothing) shows a record-updated event for a non-conformance, and the data service’s log for its correlation id shows the refresh handler failing on every retry: the aggregate’s definition refers to a field that a Quality builder renamed three days ago. The failing handler is the refresh; every other consumer of the same events (reactions, timeline, notifications) is fine, which is why only the scorecard went stale.

Step 4: what about the messages that refresh would have sent? None leaked. The outbox discarded whatever the failing handler staged, so there is no half-refreshed scorecard, just a stale one. That is what made the symptom clean.

Step 5: the fix and the recovery. The builder corrects the aggregate’s field in Development and promotes the fix (M1-S2). Then the dead letters: ACDE taught you to move them back to their queue once the cause is fixed (ACDE M7-S2). Because handlers are safe to run twice, replaying three days of events refreshes the scorecard correctly.

The lesson. “The event failed” is never the diagnosis. One consumer failed on it, alone, and its dead-letter queue and its log hold the evidence. The rename was also a Class B change that nobody classified; it goes in the register.

✓ Practice (6 min) — Read the bus as a master

Section titled “✓ Practice (6 min) — Read the bus as a master”
PracticeChoose one answer.

A handler in the reaction service publishes a “work order raised” event and then throws on its next line. On the 1.10 line, what happens to the event?

  1. Explanation for A

    ✗ Incorrect

    Not this one: that was the behaviour before 1.10; the outbox now holds it until the handler ends. See The transactional outbox.

  2. Explanation for B

    ✓ Correct

    Correct: messages published inside a handler leave only when the handler succeeds. See The transactional outbox.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the outbox is held in memory for one handler run; there is no outbox table. See The transactional outbox.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

Your colleague’s new handler sends a command to the workflow service and then waits for a reply message before continuing. In testing it hangs every time. Why?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the workflow service never receives the command, so it cannot answer. See The transactional outbox.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a handler may stage many messages; they all leave together when it succeeds. See The transactional outbox.

  3. Explanation for C

    ✓ Correct

    Correct: waiting inside a handler for the reply to its own send deadlocks; multi-step work is a saga instead. See The transactional outbox.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

Maya Idris’s phone lost its connection for two minutes in a basement. When it reconnects, which updates does it receive from those two minutes?

  1. Explanation for A

    ✓ Correct

    Correct: live push is best effort with no replay; HTTP is the source of truth after a gap. See Live push.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the socket service keeps nothing for disconnected clients. See Live push.

  3. Explanation for C

    ✗ Incorrect

    Not this one: rooms are joined per connection, and nothing in any room is stored for later. See Live push.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

A new release adds an optional plant field to the record-updated event’s normalized entity. Should $version change from 1?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the version marks incompatible changes; an optional addition breaks no consumer. See A message is a contract.

  2. Explanation for B

    ✓ Correct

    Correct: consumers that ignore the field are unaffected, which is the condition for keeping the version. See A message is a contract.

  3. Explanation for C

    ✗ Incorrect

    Not this one: changing the name would break every subscriber for a change none of them needed. See A message is a contract.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

An export of 40,000 work orders is started from the API and answers 202 with a job id. Where is the work itself queued?

  1. Explanation for A

    ✗ Incorrect

    Not this one: bulk work is cut into chunks of a job, not sent as one command per record. See Jobs: long work in Redis.

  2. Explanation for B

    ✗ Incorrect

    Not this one: the scheduler runs timed work; an export starts at once. See Jobs: long work in Redis.

  3. Explanation for C

    ✓ Correct

    Correct: Redis carries the work, the bus carries the fact that it finished. See Jobs: long work in Redis.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

↺ Recap (1 min) — The bus as a contract

Section titled “↺ Recap (1 min) — The bus as a contract”

You can now tell a command from an event, read a message’s name, version, payload and attributes as a contract, name who sends and who consumes it, follow its failure path through one consumer’s retries and dead letters, explain what the outbox guarantees and the deadlock it forbids, and place jobs and live pushes on the same map.

Next. M2-S3 opens the record that every one of these events carries: how definitions and records are stored, and which of their values are a contract that must never change.