Design
The design turns the Event Storming board into the model the services implement, at the two levels DDD distinguishes. The strategic design starts from the subdomains found in the analysis, in the problem space, and settles the bounded contexts and their relations. The tactical design works in the solution space: for each bounded context it describes the aggregates, the rules they protect and the events they publish.
Every name below is a term of the ubiquitous language, and every aggregate is one of the large yellow stickies of step 9.
Strategic Design
Bounded Contexts
The bounded contexts are the ones drawn at step 10 of the Event Storming, and each implements one or more of the subdomains found in the analysis. Two of them hold two subdomains each.
| Bounded context | Subdomains | Aggregates |
|---|---|---|
| Account | Identity, Workspace organisation | User, Workspace |
| Membership | Membership and roles | Workspace Membership |
| Editing | Page content, Real-time collaboration | Page, Page Block Tree, Real-time Editing Session |
| Discussion | Discussion | Comment Thread |
| Notification | Notification | Notification |
Editing keeps page content and real-time collaboration together because an edit merged by the session turns at once into commands on the Page Block Tree; splitting them would put a network hop inside the path that QA-02 bounds at 300 ms. Account keeps identity and workspace organisation together because a user’s first workspace is created when the user registers, and the main workspace belongs to the user. Account therefore mixes a generic subdomain with a supporting one: if identity is covered by an existing component, Account is where it plugs in.
Context Map
The context map shows how the five bounded contexts depend on each other, in the notation of Khononov: every relation has an upstream end (U), whose model the other side depends on, and a downstream end (D), each marked with the integration pattern it plays. Each context is filled with the type of the subdomains it implements: Account is half generic (identity) and half supporting (workspace organisation).
The map is kept as code, in Context Mapper’s
language: gotion.cml is the source, and
assets/context-map/render.sh regenerates the picture from it.
| Upstream | Downstream | Patterns | What crosses the boundary |
|---|---|---|---|
| Account | Membership | OHS, PL → CF | Workspace Created (accept the creator as Admin), Workspace Deleted (delete its membership); on request, the UserId registered with an email address (invite member) |
| Account | Editing | OHS, PL → CF | Workspace Created (create its root page), Workspace Deleted (delete its root page) |
| Membership | Account | OHS, PL → CF | The roles: only an Admin renames or deletes a workspace; opening a workspace requires membership. Member Removed, Member Left and Workspace Membership Deleted clear a lost main workspace |
| Membership | Editing | OHS, PL → ACL | The roles, read as whether a user may read or change the content |
| Membership | Discussion | OHS, PL → CF | Who is a member: only members post, resolve and are mentioned, whatever their role |
| Membership | Notification | OHS, PL → ACL | Member Invited (send the invitation) |
| Editing | Discussion | OHS, PL → CF | Page Deleted, Block Deleted (delete its comment threads) |
| Discussion | Notification | OHS, PL → ACL | Comment Posted (notify the mentioned user) |
Membership shares the roles through the events that change them: Member Joined, Member Role Changed, Member Removed, Member Left and Workspace Membership Deleted. Editing listens to all of them. Account listens to Member Removed, Member Left and Workspace Membership Deleted to clear a main workspace the user has lost. Account and Discussion read the roles and the members through queries instead (see ADR-03).
The same two people build all five contexts, so from a team point of view every relation would be a partnership. The map shows customer-supplier relations anyway, because each context becomes its own microservice, deployed and versioned separately.
- Upstream, open-host service with a published language (OHS, PL). Every upstream publishes its events in a format kept separate from its internal model, so it can change the model without breaking the contexts downstream. The events carry identities (
UserId,WorkspaceId,PageId,BlockId) as plain values. For calls between contexts, Account’s open-host service also answers one query, synchronously, in the same published language: which user is registered with an email address, which Membership asks before adding an invitation. Membership’s answers two: the role of a user in a workspace, which Account and Editing ask, and which of a set of users are members of a workspace, which Discussion asks. The gateway also queries Membership for a user’s workspace identities and roles, and Account for their names and the user’s main workspace, to compose the Workspace directory. - Downstream conformist (CF): it uses the events as they are. Membership and Editing only need the workspace identity from Workspace Created and Workspace Deleted, and Membership takes the
UserIdreturned by the user lookup as it is. Discussion only needs the identities in Page Deleted and Block Deleted, and who is a member, which it asks Membership. Account uses the roles with the names Membership gives them. - Downstream anticorruption layer (ACL): it translates the events into its own terms. Notification turns Member Invited and Comment Posted into its own
Subject(an invitation, a mention), so it never needs to know the models of Membership and Discussion. Editing turns the roles into the one thing it cares about: can this user read the content, or also change it? Editing holds a core subdomain, which is where an anticorruption layer pays off most, and with it a new role only changes the translation, not the Editing model.
Account and Membership depend on each other: Account tells Membership when a workspace is created or deleted and which user an email address belongs to, and Membership sends the roles back; each one also queries the other while it runs a command (ADR-03). This is the tightest coupling on the map. If the two contexts keep changing together, this is the first place to look.
The table says what Account, Editing and Discussion get from Membership; how the roles and the membership reach them was PP-04, settled by ADR-03: Editing keeps a local copy of the roles, fed by the events, and asks Membership only when the copy has no row; Account and Discussion ask Membership on each command that needs it. Notification is not part of PP-04: it reacts to Member Invited and never checks a role or a membership.
Tactical Design
Building blocks
Each bounded context has its own model, drawn as a UML class diagram with the DDD stereotypes Aggregate Root, Entity, Value Object, Repository, Factory, Domain Service and Domain Event. A box groups the classes of one aggregate. Every aggregate root has a repository that stores and loads it whole, and a factory only where creating it has a rule to keep. Of the domain events, the diagrams draw only User Registered: it is what makes Account create the first workspace of a new user on its own, with no command from the user (US-01). The other events are listed in the command table of the aggregate that emits them.
Three rules shape every aggregate:
- Only the root is referenced from outside. Inner entities, such as the blocks of a Page Block Tree, change only through a command on the root, which checks the invariants first.
- Aggregates refer to each other by identity. A Page holds a
WorkspaceId, never the Workspace. Across contexts the identities are the only thing shared:UserId,WorkspaceId,PageId,BlockId. - One command changes one aggregate, in one transaction. A rule that spans two aggregates is kept by a policy that reacts to an event, so it holds eventually rather than at once. Those rules are collected in Rules across aggregates.
An aggregate and its factory keep only what lies inside the aggregate. A check on data outside it, such as an email address no other user has or a role held by Membership, is a precondition of the command, not an invariant: the application service that handles the command asks a domain service first, and calls the factory or the root only if the check passes. The domain services that ask another context are ports, so their call over the network never runs inside a method of an aggregate. The diagrams therefore draw no aggregate or factory using a domain service.
For each aggregate, the commands are listed with who issues them: an actor, named by the role the command requires, or a policy. A role is held by Membership, so the commands of the other contexts check it from outside, as summarised in Roles.
Account
classDiagram
direction LR
namespace User_aggregate {
class User {
<<Aggregate Root>>
id: UserId
email: Email
password: PasswordHash
mainWorkspace: WorkspaceId [0..1]
createWorkspace(name) Workspace
}
class Email {
<<Value Object>>
}
class PasswordHash {
<<Value Object>>
}
}
namespace Workspace_aggregate {
class Workspace {
<<Aggregate Root>>
id: WorkspaceId
name: WorkspaceName
}
class WorkspaceName {
<<Value Object>>
}
}
class UserRepository {
<<Repository>>
}
class WorkspaceRepository {
<<Repository>>
}
class UserFactory {
<<Factory>>
create(email, password) User
}
class EmailAvailability {
<<Domain Service>>
isAvailable(email) Boolean
}
class UserRegistered {
<<Domain Event>>
user: UserId
}
User --> Email
User --> PasswordHash
Workspace --> WorkspaceName
User ..> Workspace : mainWorkspace, by id
UserRepository ..> User : stores
WorkspaceRepository ..> Workspace : stores
UserFactory ..> User : creates
EmailAvailability ..> UserRepository : uses
UserRegistered ..> User : createFirstWorkspace
User ..> Workspace : creates
User
The identity that signs in (US-01), and the owner of the user’s main workspace (US-02).
- The email address is unique among users. The rule spans every User, so Register asks
EmailAvailabilityto check the address against theUserRepositorybefore the User factory creates the user. Checking and then creating is not atomic, so the store of the users also keeps the address unique, and of two concurrent registrations with the same address the second fails. - The password is kept only as a
PasswordHash; signing in compares against it and changes no state. - Opening a workspace checks that it exists and that the user is a member, then sets it as the user’s main workspace (see Roles and ADR-03). If Membership does not answer, the opening is refused and main stays as it was. This check only decides what Account saves as main; the pages of the workspace are guarded by Editing.
- At login the client opens the main workspace. When main is unset, or the user no longer belongs to it, the client opens the first workspace of the Workspace directory instead, and that one becomes main. A user with no workspaces sees an empty directory, from which they can create a workspace or accept an invitation.
- If the user loses the workspace they are working in, Editing makes them leave its sessions and the client opens the first workspace of the Workspace directory, as at login, and that one becomes main.
- On Member Removed, Member Left or Workspace Membership Deleted, a policy clears main if it is the workspace the user lost. If the user has opened another workspace since, main already points there and stays.
| Command | Issued by | Event |
|---|---|---|
| Register | Visitor | User Registered |
| Sign in | User | User Signed In |
| Set main workspace | User, on opening a workspace; policy when the user loses their main workspace, clear it | Main Workspace Changed |
The main workspace belongs to User, since login must remember it across sessions. Opening a workspace updates that one aggregate. The active workspace stays a navigation choice of each client, which takes the workspaces it can open from the Workspace directory, composed by the API gateway from Membership and Account (API Composition).
Workspace
A separate space of pages (US-02). The name is a WorkspaceName, never blank.
- A workspace is created by a user, through
createWorkspaceon User, so it always has a registered creator, whom Workspace Created carries. The user itself does not change, so one command still changes one aggregate: recording a visit stays a separate command. - Only an Admin of the workspace renames or deletes it.
- A deleted workspace accepts no further command. Its root page and its Workspace Membership are removed by policies, not in the same transaction.
| Command | Issued by | Event |
|---|---|---|
| Create workspace | User; policy whenever a user registers, create their first workspace | Workspace Created |
| Rename workspace | Admin | Workspace Renamed |
| Delete workspace | Admin | Workspace Deleted |
Membership
classDiagram
direction LR
namespace Workspace_Membership_aggregate {
class WorkspaceMembership {
<<Aggregate Root>>
workspace: WorkspaceId
members: Member[1..*]
invitations: Invitation[*]
}
class Member {
<<Entity>>
user: UserId
role: Role
}
class Invitation {
<<Value Object>>
invitee: UserId
role: Role
invitedBy: UserId
}
class Role {
<<Value Object>>
Admin
Editor
Viewer
}
}
class WorkspaceMembershipRepository {
<<Repository>>
}
class WorkspaceMembershipFactory {
<<Factory>>
create(workspace, creator) WorkspaceMembership
}
class UserLookupService {
<<Domain Service>>
findByEmail(email) UserId
}
WorkspaceMembership "1" *-- "1..*" Member
WorkspaceMembership "1" *-- "*" Invitation
Member --> Role
Invitation --> Role
WorkspaceMembershipRepository ..> WorkspaceMembership : stores
WorkspaceMembershipFactory ..> WorkspaceMembership : creates
Workspace Membership
Who belongs to one workspace, with which role, and who has been invited to it (US-03). It is
identified by the WorkspaceId of its workspace.
- A workspace always keeps at least one Admin. Change member role, Remove member and Leave workspace are refused when they would leave no Admin: the last Admin has to promote another member before stepping down or leaving. The board had this rule as a purple sticky, but it forbids an operation rather than reacting to an event, so it is an invariant, not a policy.
- The membership starts with the creator of the workspace as its only member, an Admin. The
WorkspaceMembershipFactorycreates it that way, with no invitation, so there is no moment without an Admin. - A user is a member at most once, with exactly one role.
- Only an Admin invites, changes roles and removes members. This check is local, since the roles live here.
- Remove member and Leave workspace may leave the user with no workspaces (US-03); only the last-Admin invariant prevents either operation.
- An invitation is addressed to a registered user, who receives it as an in-app notification (US-10), and who is neither a member nor already invited. It carries the role the invitee will have, chosen by the Admin.
- The Admin invites by email. Before the command reaches the membership, the
UserLookupServiceasks Account whether the address belongs to a registered user and gets theirUserId; only then does the membership add the invitation. The other checks are local to the membership. - Only the invitee accepts or declines an invitation, and either answer ends it. An invitation does not expire: it stays pending until the invitee answers. It never changes in between, and a user has at most one pending invitation per workspace, so it is a value object told apart by its invitee.
| Command | Issued by | Event |
|---|---|---|
| Create workspace membership | Policy whenever a workspace is created, accept the creator as Admin, carried out by the factory | Member Joined |
| Invite member | Admin | Member Invited |
| Accept invitation | Invitee | Member Joined |
| Decline invitation | Invitee | Invitation Declined |
| Change member role | Admin | Member Role Changed |
| Remove member | Admin | Member Removed |
| Leave workspace | Member | Member Left |
| Delete workspace membership | Policy whenever a workspace is deleted, delete its membership | Workspace Membership Deleted |
Editing
classDiagram
direction TB
namespace Page_aggregate {
class Page {
<<Aggregate Root>>
id: PageId
workspace: WorkspaceId
metadata: PageMetadata
createSubPage(id) SubPage
openSession(collaborator) RealTimeEditingSession
}
class RootPage
class SubPage {
parent: PageId
}
class PageMetadata {
<<Value Object>>
title: String
icon: IconName[0..1]
cover: Url[0..1]
}
}
namespace Page_Block_Tree_aggregate {
class PageBlockTree {
<<Aggregate Root>>
page: PageId
blocks: Block[*]
text: Sequence
}
class Block {
<<Entity>>
id: BlockId
content: BlockContent
children: Block[*]
}
class BlockContent {
<<Value Object>>
}
class TextContent {
<<Value Object>>
}
class HeadingContent {
<<Value Object>>
level: Integer
}
class BulletedListContent {
<<Value Object>>
}
class NumberedListContent {
<<Value Object>>
}
class ToDoContent {
<<Value Object>>
checked: Boolean
}
class CodeContent {
<<Value Object>>
language: CodeLanguage[0..1]
}
class PageBlockContent {
<<Value Object>>
subPage: PageId
}
}
namespace Real_time_Editing_Session_aggregate {
class RealTimeEditingSession {
<<Aggregate Root>>
page: PageId
workspace: WorkspaceId
presence: Presence
replicas: Replica[*]
closed: Boolean
}
class Presence {
<<Value Object>>
collaborators: UserId[*]
}
class Replica {
<<Value Object>>
number: Integer
user: UserId
}
class Edit {
<<Value Object>>
author: UserId
change
}
}
class PageRepository {
<<Repository>>
}
class PageBlockTreeRepository {
<<Repository>>
}
class RealTimeEditingSessionRepository {
<<Repository>>
}
class AccessLookupService {
<<Domain Service>>
canRead(user, workspace) Boolean
canChange(user, workspace) Boolean
}
Page --> PageMetadata
PageBlockTree "1" *-- "*" Block
Block "1" *-- "*" Block : children
Block --> BlockContent
BlockContent <|-- TextContent
BlockContent <|-- HeadingContent
BlockContent <|-- BulletedListContent
BlockContent <|-- NumberedListContent
BlockContent <|-- ToDoContent
BlockContent <|-- CodeContent
BlockContent <|-- PageBlockContent
RealTimeEditingSession --> Presence
RealTimeEditingSession "1" *-- "*" Replica
RealTimeEditingSession ..> Edit : relays
Page <|-- RootPage
Page <|-- SubPage
SubPage ..> Page : parent, by id
PageBlockTree ..> Page : page, by id
PageBlockContent ..> SubPage : subPage, by id
RealTimeEditingSession ..> Page : page, by id
PageRepository ..> Page : stores
PageBlockTreeRepository ..> PageBlockTree : stores
RealTimeEditingSessionRepository ..> RealTimeEditingSession : stores
Page ..> SubPage : creates
Page ..> RealTimeEditingSession : creates
Page
A document of a workspace, with its metadata and its place in the page tree (US-04, US-05).
- A page is either the root page of its workspace or a sub-page.
RootPageandSubPageare the two forms of the one root of the Page aggregate, and a page never turns from one into the other. Only a sub-page has a parent, and it always has one. - Each workspace has exactly one root page. It is created only by the policy on Workspace Created and deleted only by the policy on Workspace Deleted. Its
PageIdis derived from theWorkspaceId, so a second root page of the same workspace would have the same identity and cannot be stored: the rule holds without looking at the other pages. - Every
PageIdholds theWorkspaceIdof its page. The root page’s is the workspace alone, a sub-page’s adds an identifier of its own. A page never changes workspace, so any context tells the workspace of a page from its identity, with no query to Editing. - A sub-page is created, moved and deleted only through its page block. Inserting, moving or deleting the page block in the tree of the parent page fires the matching command on Page. Each sub-page therefore has exactly one page block, and nothing flows back from Page to the block, so the loop raised while reviewing the board cannot happen.
- The parent of a sub-page is the page whose tree holds its page block, in the same workspace. The parent creates it, through
createSubPageon Page, so the sub-page always gets the workspace of its parent, and thePageIdthat its page block already holds. The parent itself does not change, so one command still changes one aggregate. - Deleting a page is final (US-04): its content and its sub-pages are deleted with it, by policies. A page knows its parent but not its sub-pages, which only the page blocks of its tree name, so the deletion goes through the tree: the tree of the page is deleted, and each sub-page whose page block it held is deleted in turn, down to the last level.
- The metadata is set only on the page itself. The page block shows the title, icon and cover through the read model, without keeping a copy, so nothing in the block has to follow it.
- Setting the metadata on the page itself needs a role that may change the content. The roles live in Membership, so the
AccessLookupServiceis asked before the command reaches Page. It only says whether a user of the workspace can read the content or also change it. It reads a local copy of the roles, fed by the events of Membership, and asks Membership only when the copy has no row (ADR-03). - The title is plain text. Icon and cover are optional. The icon is the name of an icon from the Lucide set, which the client draws, so the page stores no image. The cover is a link to an image, because no story asks for uploading files.
| Command | Issued by | Event |
|---|---|---|
| Create page | Policies whenever a workspace is created, create its root page and whenever a page block is inserted, create the sub-page | Page Created |
| Set title, icon, cover | Editor | Page Metadata Changed |
| Move page | Policy whenever a page block is moved, move it in the tree as well | Page Moved |
| Delete page | Policies whenever a page block is deleted, delete the page as well, on Block Deleted and on Block Tree Deleted, and whenever a workspace is deleted, delete its root page | Page Deleted |
Page Block Tree
The content of one page (US-06, US-07). It is identified by the PageId of its page and starts empty together with it. It needs no factory: no command creates it, and the first operation finds it empty and stores it.
The tree is replicated (ADR-01). Every client that has the page open holds a replica and applies its own edits to it at once, and Editing holds the replica that decides what the others get. An edit is an operation of our CRDT, the same package in the client and in Editing (ADR-04): insert, update, move or delete a block, join a block to the one before it, or edit the text of a block. The text of the whole page is one sequence of characters, where each block has a marker and owns the characters after it, so BlockContent holds every field of a block but its text. Editing takes the operations of a page one at a time. For each one it checks the rules below on its replica, appends the operation to the session log (ADR-02) and applies it to its replica before it takes the next. The check therefore always runs on a replica that holds every operation accepted so far: only the snapshots of the tree lag behind the log, not the replica in memory.
The rules fall into two groups, by how they can be broken.
Kept by the CRDT. Two concurrent operations, each valid on the replica of its author, can break these rules only together. Editing cannot refuse either of them, because each one passes the check on its own, so the CRDT keeps the rules on every replica by construction:
- The blocks form an ordered tree: every block has exactly one parent, the page or another block, and a position among its siblings, given by its position key and, between equal keys, by the order of the markers in the sequence (CRDT package). A block divided from another takes its key, so the blocks divided from one block, at once or not, follow the order of their text, and two blocks inserted at the same position at once end up in the same order on every replica.
- A block cannot be nested under itself or one of its descendants. When two concurrent moves would make a cycle (A under B while B goes under A), every replica orders the moves by their timestamps and the one that would close the cycle has no effect, after Kleppmann et al., “A highly-available move operation for replicated trees”.
- Deleting a block deletes the blocks nested in it, including a block moved under it at the same time. An operation on a deleted block has no effect.
- Of two concurrent updates of the same block, every replica keeps the one with the greater identity, so the block ends with one type and one content everywhere (CRDT package).
- Joining a block takes it out of the tree: a concurrent update or move of the joined block has no effect, while its characters, those typed meanwhile included, go with the join.
- A code block shows its text plain, and a page block has no text. Since the text of the page is one sequence, a concurrent style can reach the characters of a code block, and a concurrent insertion can put characters after the marker of a page block: every replica ignores the styles of the characters of a code block, and gives the characters after the marker of a page block to the block of the nearest marker before them in the sequence that is not the marker of a page block. Editing writes the Markdown of BR-03 the same way.
Checked by Editing. One operation can break these rules on its own. Editing refuses it before any other replica sees it, together with the later operations of the same author that build on it, and the author reverts them:
- The type of a block is the subtype of its
BlockContent, and each subtype holds only the fields its type needs. The text is written out as Markdown (BR-03), so a heading also has its level, from 1 to 6 as in Markdown. A to-do has its checkbox, and a page block holds only its sub-page, so no other block can refer to one. A code block may name its language in one word, the one written after the opening fence of a Markdown code block (python). Editing refuses a field that the type does not have and a value out of its range, such as a heading of level 7. - The editor of the client works on styled text, not Markdown, so Editing refuses a style that Markdown cannot express, and the Markdown of BR-03 loses nothing (see Editing client).
- Update block can turn a block into another type by replacing its content. The block keeps its
BlockId, its place in the tree and the comment threads anchored to it. Page blocks are the exception: no block becomes a page block and a page block becomes nothing else, because a sub-page is created and deleted only by inserting and deleting its page block. For the same reason, Editing refuses a page block inserted with thePageIdof a page that already exists, and one whosePageIdholds another workspace than the page of the tree, since a sub-page belongs to the workspace of its parent. A page block holds nothing but its sub-page, which never changes, so Editing also refuses any update of a page block. - Join block removes the marker of the joined block and gives its characters to the block of the marker before. Editing therefore refuses joining a page block, or a block to a page block, and, until a later decision settles the join of blocks that are not neighbours in the sequence, which ADR-01 leaves open, joining a block whose marker is not the next one after the marker of the block before it in the tree. That includes joining a block to the one before after the block between them was deleted, since the marker of a deleted block stays.
- Edit text deletes characters only: Editing refuses a deletion that covers a marker, or an identity that is not a character of the page.
Events come from the effect of an operation, not from the operation. Editing derives them from what the operation changed on its replica, so a move that has no effect emits no Block Moved.
- Block Deleted is emitted for every deleted block, because Discussion deletes the threads anchored to it. It lists the page blocks removed with it, so that every sub-page underneath is deleted, not only the top one.
- Block Tree Deleted lists the page blocks the tree held, for the same reason: it is how the sub-pages of a deleted page are found and deleted.
- Block Inserted and Block Moved are emitted only for page blocks, which the policies on Page follow. The edits of the other blocks stay in the session log.
A new block type is a new subtype of BlockContent and its rendering, both inside Editing, with no change to any other aggregate or context (QA-09). The content is saved as the name of its type plus its fields, so a new type needs no change to the persistence schema, as long as its edits fit the generic operations of the CRDT (ADR-01).
| Command | Issued by | Event |
|---|---|---|
| Insert block | Collaborator, as an operation through Submit edit | Block Inserted, for a page block |
| Update block | Same | None: the operation stays in the session log |
| Move or nest block | Same | Block Moved, for a page block that moved |
| Delete block | Same | Block Deleted |
| Join block | Same | Still to be settled, with what a join does to the comment threads anchored to the joined block (ADR-01) |
| Edit text | Same | None: the operation stays in the session log |
| Delete block tree | Policy whenever a page is deleted, delete its block tree | Block Tree Deleted |
Real-time Editing Session
The shared editing of one page (US-08). It is identified by the PageId of its page. As agreed
while reviewing the board, the session exists even with a single collaborator: the first Join
session opens it, so editing alone and editing together follow the same path.
- Opening goes through
openSessionon Page, so a session exists only for a page that exists, and it starts with the collaborator who joined in its presence. It keeps the workspace of its page, which never changes, for the checks on later joins and edits. The page itself does not change, so one command still changes one aggregate. - Join session gives the replica of the collaborator its number, the next one of the page, and the session records the user it gave it to, so two replicas of the same page never share one (CRDT package). A replica that reconnects keeps its number if the session gave it to the same user, even after Editing restarts; an older connection of that replica still open is closed first. Submit edit refuses an operation that carries another number than the one of its replica, or a counter that does not grow past the last one of its replica, unless the operation is already in the log: Editing acknowledges it again if it is the same operation, without checking it again, and closes the connection as malformed otherwise (ADR-02).
- Only a collaborator who has joined can submit edits, and only with a role that may change the content. A Viewer can join to follow the edits and appear in the presence, but cannot submit. Before Join session and Submit edit reach the session, or Page when it opens one, the
AccessLookupServiceis asked whether whoever joins can read the content and whoever submits an edit can also change it. - The session does not merge. Every replica merges concurrent edits on its own with a CRDT of ours, which settles PP-01 (ADR-01), so the
changecarried by anEditis an operation of that CRDT. Submit edit checks that the author has joined the open session, once the role has been checked, then hands the operation to the Page Block Tree, which checks it against its own rules and applies it. The session itself does not change, so one command still changes one aggregate. An accepted operation is appended to the session log and acknowledged, and only then relayed to the other collaborators (ADR-02). Every collaborator converges to the same content, and no acknowledged edit is dropped except where QA-05 allows it: an edit of a block deleted or joined at the same time, and the losing one of two concurrent updates of the same block. - A closed session accepts no join and no edit. It is closed when its page is deleted, and the collaborators learn it from Session Closed itself: the notify its participants of the policy is that event, not an in-app notification, which US-10 keeps for invitations and mentions.
| Command | Issued by | Event |
|---|---|---|
| Join session | Collaborator | Session Joined |
| Leave session | Collaborator; policy when a member is removed or leaves, or the workspace membership is deleted, make them leave the sessions of the workspace | Session Left |
| Submit edit | Editor | The events of the Page Block Tree |
| Close session | Policy when a page is deleted, close its editing session and notify its participants | Session Closed |
Discussion
classDiagram
direction LR
namespace Comment_Thread_aggregate {
class CommentThread {
<<Aggregate Root>>
id: ThreadId
anchor: Anchor
comments: Comment[1..*]
resolved: Boolean
}
class Anchor {
<<Value Object>>
page: PageId
}
class PageAnchor {
<<Value Object>>
}
class BlockAnchor {
<<Value Object>>
block: BlockId
}
class Comment {
<<Entity>>
id: CommentId
author: UserId
text: Markdown
mentions: Mention[*]
}
class Mention {
<<Value Object>>
user: UserId
}
}
class CommentThreadRepository {
<<Repository>>
}
class CommentThreadFactory {
<<Factory>>
open(anchor, author, text, mentions) CommentThread
}
class MembershipLookupService {
<<Domain Service>>
areMembers(users, workspace) Boolean
}
CommentThread --> Anchor
Anchor <|-- PageAnchor
Anchor <|-- BlockAnchor
CommentThread "1" *-- "1..*" Comment
Comment --> Mention
CommentThreadRepository ..> CommentThread : stores
CommentThreadFactory ..> CommentThread : creates
Comment Thread
A conversation attached to a page or to one of its blocks (US-09).
- The anchor is fixed when the thread opens and never changes. A page anchor holds a thread on the whole page, a block anchor a thread on one block. Both name the page, because a
BlockIdalone does not tell Discussion which page the block is on, and the threads of a page must be found when it is shown or deleted. - The workspace of a thread is the one held by the
PageIdof its anchor, never one stated by the client: a member of one workspace could otherwise open a thread on a page of another and pass the membership check (QA-06). - A thread is never empty: the
CommentThreadFactoryopens it together with its first comment and the mentions in it. - A resolved thread accepts no new comments.
- A mention names a member of the workspace. The members live in Membership, so before the thread or its factory is called, the
MembershipLookupServiceis asked whether the author of a comment, every user it mentions and whoever resolves the thread are members, all in one query to Membership (ADR-03). - Any member of the workspace posts and resolves, whatever their role: a comment does not change the content of the page, so a Viewer can take part in the discussion too.
| Command | Issued by | Event |
|---|---|---|
| Post comment | Collaborator | Comment Posted |
| Resolve thread | Collaborator | Thread Resolved |
| Delete thread | Policies whenever a page is deleted, delete its comment threads and whenever a block is deleted, delete its comment threads | Thread Deleted |
Notification
classDiagram
direction LR
namespace Notification_aggregate {
class Notification {
<<Aggregate Root>>
id: NotificationId
recipient: UserId
subject: Subject
status: Status
}
class Subject {
<<Value Object>>
Invitation
Mention
}
class Status {
<<Value Object>>
Raised
Delivered
Read
}
}
class NotificationRepository {
<<Repository>>
}
Notification --> Subject
Notification --> Status
NotificationRepository ..> Notification : stores
Notification
A message telling one user about an invitation or a mention (US-10).
- The status only moves forward: Raised, then Delivered, then Read.
- Delivery is best effort and may be repeated: delivering an already delivered notification changes nothing.
- Only the recipient marks it as read.
- Mentioning oneself raises nothing: the policy fires only when another user is mentioned.
| Command | Issued by | Event |
|---|---|---|
| Raise notification | Policies when MemberInvited then send the invitation and when another user is mentioned | Notification Raised |
| Deliver notification | Policy notification delivery with best effort | Notification Delivered |
| Mark as read | User | Notification Read |
Rules across aggregates
The rules that span more than one aggregate, and the policies that keep them. Between the event and the reaction the rule does not hold yet: right after Workspace Created, for instance, the root page may not exist, and the read models must allow for it.
| Rule | Kept by | Traces to |
|---|---|---|
| A new user has a first workspace | Whenever a user registers, create their first workspace | US-01, US-02 |
| Losing the main workspace clears it; users may have no workspaces | On Member Removed, Member Left or Workspace Membership Deleted, clear main if it is the lost workspace | US-02, US-03 |
| A workspace has an Admin from its creation | Whenever a workspace is created, accept the creator as Admin | US-03 |
| A workspace has exactly one root page | Whenever a workspace is created, create its root page, plus the identity of the root page, derived from its workspace | US-04 |
| Every page block has its sub-page, and every sub-page its page block | Whenever a page block is inserted, moved or deleted… | US-04 |
| Deleting a workspace deletes everything in it | Whenever a workspace is deleted, delete its root page, then the cascade below; whenever a workspace is deleted, delete its membership | US-02, PP-05 |
| Deleting a page deletes its content, sub-pages, session and threads | Whenever a page is deleted, delete its block tree, then whenever a page block is deleted, delete the page as well for each page block the tree held; when a page is deleted, close its editing session; whenever a page is deleted, delete its comment threads | US-04, US-09, PP-05 |
| Deleting a block deletes the threads anchored to it | Whenever a block is deleted, delete its comment threads | US-09, PP-05 |
| A member who is no longer one stops following the edits | When a member is removed or leaves, or the workspace membership is deleted, make them leave the sessions of the workspace | US-03, QA-06 |
| Invited and mentioned users are told | When MemberInvited then send the invitation; when another user is mentioned | US-10 |
Roles
The roles live in Membership, but most of the commands that need them belong to other contexts. The table states which role each command requires; the relations that carry them are in the Context Map, and how the roles reach the other contexts is settled by ADR-03.
| Command | Context | Admin | Editor | Viewer |
|---|---|---|---|---|
| Rename workspace, Delete workspace | Account | ✓ | ||
| Invite member, Change member role, Remove member | Membership | ✓ | ||
| Leave workspace | Membership | ✓ | ✓ | ✓ |
| Set title, icon, cover; Submit edit | Editing | ✓ | ✓ | |
| Join session | Editing | ✓ | ✓ | ✓ |
Three more checks read Membership without a role: opening a workspace requires membership, only a member posts a comment or resolves a thread, and a mention names a member of the workspace.
Changes from the board
The model refines the board, and these changes are to be carried back to it:
- Set main workspace moves to User and runs every time the user opens a workspace. Switch workspace with Workspace Switched is covered by Set main workspace → Main Workspace Changed.
- Rename workspace → Workspace Renamed is added, as US-02 requires.
- Decline invitation → Invitation Declined settles PP-02, and Leave workspace → Member Left settles PP-03. The sticky not possible to leave the workspace if you are last Admin becomes an invariant of Workspace Membership.
- The deletion policies of Membership and Discussion, with Workspace Membership Deleted and Thread Deleted, settle PP-05.
- The Editor no longer issues Move page and Delete page: the Editor moves or deletes the page block, and the policies do the rest.
- Edits Merged and the policy when edits are merged, apply them to the page block tree leave the model: every replica merges on its own, and Submit edit hands each operation to the Page Block Tree, which checks and applies it (ADR-01).
- Moving a sub-page under a different parent page is not modelled: a page block moves only within the tree of its own page.
Architecture
Components and Connectors
The view below is the whole system as it is planned for now: it guides the development and will change with the design. Each bounded context is a service with its own database, the client reaches them through the API gateway, the events between contexts go through Kafka, and Prometheus pulls the metrics of every service. Account, Membership, Discussion, Notification and the API gateway run on Go, Editing on Node.js, where it imports the same CRDT package as the client (ADR-04).
| Element | Type | Responsibility | Properties |
|---|---|---|---|
| Web client | Client | Edits the pages with BlockNote, through the editor adapter and a CRDT replica of each open page | Talks only to the API gateway: REST for the requests, one WebSocket for each open page |
| API Gateway | Infrastructure | The one entry point from outside: authenticates each request, routes it to its service and composes the Workspace directory from Membership and Account (API Composition) | Forwards the WebSocket of a page to the instance of Editing that owns the page; written in Go, on the same chassis as the Go services (ADR-04, ADR-07) |
| Account | Service | Users and workspaces (User, Workspace) |
Answers the user registered with an email address to Membership, and workspace names in a batch and the user’s main workspace to the gateway; asks Membership for the role before renaming or deleting a workspace and for membership before opening one; remembers the main workspace; publishes Workspace Created and Workspace Deleted |
| Membership | Service | Members, roles and invitations (Workspace Membership) |
Asks Account for the user of an email address before an invitation; answers the role of a user and which users are members (ADR-03), and the workspace identities and roles of a user to the gateway; publishes the changes of membership and roles, and Member Invited |
| Editing | Service | Pages and their content (Page, Page Block Tree, Real-time Editing Session); the one relay of the operations of a page |
One instance owns each page; event-sourced (ADR-02); keeps a local copy of the roles and asks Membership only when it has no row (ADR-03); publishes Page Deleted and Block Deleted |
| Discussion | Service | Comment threads on pages and blocks (Comment Thread) |
Asks Membership which users of a command are members; publishes Comment Posted |
| Notification | Service | The in-app notifications of invitations and mentions (Notification) |
Only subscribes, publishes nothing |
| Service databases | Repository | One PostgreSQL server for each service, with the data of its context only (ADR-06) | Read and written only by the service that owns it (Database-per-Service); in Account, Membership and Discussion it also holds the outbox of the events still to publish (ADR-05) |
| Prometheus | Monitoring | Pulls the metrics of every service from /metrics and keeps them as time series |
The only accessor of the metrics store |
| Grafana | Monitoring | The SLO dashboards and the alerts | Reads the metrics only through Prometheus, with PromQL |
| REST | Call-return connector | A synchronous request and its response: from the client through the gateway, from Membership to Account, and from Account, Editing and Discussion to Membership | The caller waits for the response |
| WebSocket | Event channel connector | The session of a page: the answer to Join session with the snapshot, operations, acks and refusals, and the presence | One per client and open page, through the gateway |
| Apache Kafka | Publish-subscribe connector | Carries the events of each upstream context to the contexts that subscribe | One channel for each upstream context, in its published language. Kafka keeps the order only within a partition, so each event is keyed by the identity of its aggregate; it can deliver an event twice, so every subscriber must handle a repeated event with no effect |
| DB access | Data-access connector | A service reading and writing its own database | Never across services |
| Scrape | Pull connector | Prometheus reading /metrics |
Started by Prometheus, not by the service |
That picture mixes styles and is meant as an overview. The three views that follow take one C&C style at a time (event-based, data flow, repository), in the UML notation of Clements et al.: components with an instance name, ports and connectors, where the colour of each element gives its type in the style, as the legend of each view says.
Each view is kept as a draw.io file next to its picture in
assets/components-and-connectors/, and render.sh in the same folder exports every picture
with the draw.io CLI.
Event-based. How the services react to each other without knowing who listens. Each upstream context publishes its events, in its published language, on a Kafka publish-subscribe connector. The downstream contexts subscribe as conformists (CF) or through an anticorruption layer (ACL), as in the context map. Of the Membership events, Editing takes all but Member Invited, to keep its local copy of the roles, and Account takes Member Removed, Member Left and Workspace Membership Deleted, to clear a main workspace the user has lost; Discussion takes none, because it asks Membership instead (ADR-03). Apart from Kafka, the page session channel is how Editing, the one relay of a page (ADR-01), pushes each operation and the presence to the other collaborators, after the durable append and the ack, within the 300 ms (p95) of QA-02 (US-08). A client opens a page by joining its session on that channel: the answer carries the number of its replica and a snapshot of the page up to a sequence number of the session log, and the operations after that number follow in the order of the log. Opening a page and joining late are therefore the same step, over the WebSocket, and QA-03 times it. The presence lists the users who have the page open (US-08) and goes straight to the collaborators, without the session log. When Editing cannot go on with a session, because the client speaks another version of the protocol, sent a malformed message or may not read the page, or because the role cannot be checked or the session belongs to another instance for now, it closes the WebSocket with a code that says which, whatever the version of the client. Each page belongs to one instance of Editing, which the gateway forwards its WebSocket to (State and scaling).
Data flow. The path of one edit operation, as filters joined by one-way pipes. In the browser, the editor adapter turns BlockNote changes into operations of our CRDT and applies them to the local replica first. Editing checks each operation, against the rules of the Page Block Tree and the local copy of the roles. It either sends a refused one back, with the later operations of its author that build on it, for the author to revert, or appends it to the durable session log. Only then does the pipeline fork: the ack goes back to the author, which stops the QA-01 timer and starts the QA-02 one, and the operation is relayed in page order to the other clients. Last, Editing applies it to the Page Block Tree, saves a snapshot of the tree from time to time, and publishes the domain events. The session log and the snapshots are in the one store of Editing. The view is not a pure pipe-and-filter: the filters of Editing share the state of the session (the tree for the check, the collaborators for the relay).
Repository. Every store has exactly one data accessor, the service that owns it: no service reads or migrates the store of another (Database-per-Service). A new block type therefore never touches the store of another service, and inside Editing it leaves the schema alone as long as the operations stay generic (ADR-01): together, the two give the “no change to the persistence schema” of QA-09. Each service also migrates only its own schema, so the automatic migrations of QA-08 need no step coordinated across services. The stores of Account, Membership, Discussion and Notification hold the current state of their aggregates. The store of Editing is event-sourced (ADR-02), all in one PostgreSQL server (ADR-06): next to Page, it keeps the session log, the operations of every page in the order Editing accepted them, snapshots of the Page Block Tree, the numbered replicas of each page with their users and the local copy of the roles (ADR-03); the tree is rebuilt from the last snapshot by replaying the operations that follow it. Prometheus is the only accessor of the metrics store, which Grafana reads through Prometheus.
Hexagonal Architecture
Every service follows the ports and adapters style. The inner hexagon is the application: the domain model of the Tactical Design and one application service for each command, query or policy. On its border are the ports, the interfaces the application declares for what it needs from outside, such as a repository, the outbox or AccessLookupService. The outer hexagon holds the adapters. An inbound adapter (REST, WebSocket, a Kafka consumer) calls a port; an outbound adapter (the database, the outbox table, a Kafka producer, an HTTP client) implements one.
A service has only the ports its work needs. Account and Membership answer queries of other services, so only they have a Query API. Notification publishes nothing and asks no other context, so it has neither an outbox nor an HTTP client. Editing also writes the session log of ADR-02 and sends the operations to the collaborators over the WebSocket. The timeout, retry and circuit breaker of Dependencies at run time live in the HTTP client, and the anticorruption layers of the context map in the Kafka consumers, so changing them leaves the domain model untouched. In the tests, in-memory adapters take the place of the database and the broker.
Microservices
Each bounded context of the strategic design runs as one microservice. This section says why the system is split that way, what each service offers and needs, how the services depend on each other at run time, how they keep their state and scale, and which contracts hold them together. The patterns the services rely on are in Patterns.
Decomposition
The system is decomposed by subdomain. Each subdomain belongs to one bounded context, and each bounded context is one service, with its own process, container image, database and deployment.
| Service | Subdomains | Type | User stories | Runtime |
|---|---|---|---|---|
| Account | Identity, Workspace organisation | Generic, supporting | US-01, US-02 | Go |
| Membership | Membership and roles | Supporting | US-03 | Go |
| Editing | Page content, Real-time collaboration | Core | US-04, US-05, US-06, US-07, US-08 | Node.js |
| Discussion | Discussion | Supporting | US-09 | Go |
| Notification | Notification | Generic | US-10 | Go |
The runtimes are settled by ADR-04.
With one service per bounded context, the boundary of a model is also the boundary of a deployment: a change to a model is a change to one service, which is built, tested, versioned and deployed alone. Three scenarios rely on it:
- QA-09. A new block type changes Editing and the client, and no other service.
- QA-08. Each service migrates its own schema, so no migration needs two services at once.
- QA-04. A crash of Editing stops the editing of pages, not signing in, inviting or commenting: no other service calls Editing while it runs a command.
Why not smaller services. A further split would put a network call inside a rule that one service now keeps on its own:
- Splitting page content from real-time collaboration would put a hop between the session and the Page Block Tree. The tree checks every operation before the ack, so the hop would be on the path of every keystroke, which QA-01 and QA-02 bound. The same holds for a service per aggregate of Editing.
- Splitting identity from workspace organisation would turn two steps of Account into calls between services: a workspace is created through
createWorkspaceon User, so that it always has a registered creator, and the main workspace, the last one the user opened, is kept on User. Identity is a generic subdomain, so if it is later covered by an existing component, Account is where that component plugs in, and the split can be made then.
Why not fewer services. Two merges were worth weighing:
- Account with Membership. They are the tightest pair of the context map: each publishes events the other consumes, and each queries the other while it runs a command (ADR-03). One service would drop both queries. They stay apart because Membership is the upstream of four contexts, all of them through the roles, while the identity in Account may be replaced by an existing component: together, replacing identity would touch the service that every other context asks for the roles. If the two keep changing together, the merge is the first decision to revisit.
- Notification inside Discussion, which raises the mentions. Notification also tells about invitations, which come from Membership, so inside Discussion it would make Discussion consume the events of Membership again, which ADR-03 removed. On its own, Notification only subscribes, and no service depends on it at run time.
Services
What each service offers and needs. The client API goes through the API gateway; the queries answered to other services, the events and the channels they travel on are its published language (context map). Every event is published on Kafka keyed by the identity of its aggregate. A service publishes only the events that another context subscribes to: the policies that react to events of the same service, such as the deletion cascade inside Editing, run inside it and are not part of its published language.
Account
| Aspect | Description |
|---|---|
| Responsibility | Users and workspaces (User, Workspace), US-01, US-02 |
| Client API | Register, Sign in, Create, Rename, Open and Delete workspace. Sign in sets the token the gateway checks, a JWT in an HttpOnly cookie that carries only the identity of the user (ADR-03, ADR-09), and is rate limited per account (QA-07) |
| Answers | The UserId registered with an email address, to Membership; the names of a batch of workspaces and the main workspace of a user, to the gateway for the Workspace directory |
| Asks | Membership: the role of the user in the workspace, which must be Admin before Rename and Delete workspace, and any role before Open workspace, which saves it as the main workspace |
| Publishes | Workspace Created, Workspace Deleted |
| Consumes | Member Removed, Member Left and Workspace Membership Deleted, as a conformist, to clear a main workspace the user has lost |
| Owns | The users and the workspaces, as current state; the store keeps the email address unique |
Membership
| Aspect | Description |
|---|---|
| Responsibility | Members, roles and invitations (Workspace Membership), US-03 |
| Client API | Invite member, Accept and Decline invitation, Change member role, Remove member, Leave workspace; the members and invitations of a workspace |
| Answers | The role of a user in a workspace, to Account and Editing; which of a set of users are members of a workspace, to Discussion; the workspaces of a user with the role in each, to the gateway for the Workspace directory. A workspace that does not exist is answered as one the user is not a member of (QA-06) |
| Asks | Account: the UserId of an email address, before Invite member |
| Publishes | Member Joined, Member Role Changed, Member Removed, Member Left, Workspace Membership Deleted, Member Invited |
| Consumes | Workspace Created and Workspace Deleted, as a conformist, to create and delete the membership of a workspace |
| Owns | One Workspace Membership per workspace, as current state |
Editing
| Aspect | Description |
|---|---|
| Responsibility | Pages and their content (Page, Page Block Tree, Real-time Editing Session), US-04 to US-08; the one relay of the operations of a page (ADR-01) |
| Client API | One WebSocket per open page: Join and Leave session, Submit edit, then the snapshot of the page in the answer to Join session, the ack or the refusal of each operation, the operations of the others, the presence and Session Closed. Over REST: Set title, icon, cover |
| Answers | Nothing: no service asks Editing, since every PageId holds the WorkspaceId of its page |
| Asks | Membership: the role of a user, only when the local copy of the roles has no row (ADR-03) |
| Publishes | Page Deleted, Block Deleted, for Discussion |
| Consumes | Workspace Created and Workspace Deleted, as a conformist, to create and delete the root page; Member Joined, Member Role Changed, Member Removed, Member Left and Workspace Membership Deleted, through an anticorruption layer that turns a role into read or change |
| Owns | Event-sourced (ADR-02): the session log of every page, snapshots of the Page Block Trees, the pages, the numbered replicas of each page with their users (CRDT package) and the local copy of the roles |
A page opens over its WebSocket, with the snapshot in the answer to Join session (Components and Connectors). Two things are still open, among the points under the same section: how Editing serves the root page and the list of sub-pages, and where the read model for page block metadata lives. The workspace directory a user switches workspace with, which needs the workspaces of Account and the memberships of Membership, is composed by the gateway (API Composition).
Discussion
| Aspect | Description |
|---|---|
| Responsibility | Comment threads on pages and blocks (Comment Thread), US-09 |
| Client API | Post comment, which opens a new thread with its first comment or adds one to an open thread, Resolve thread; the threads of a page |
| Answers | Nothing |
| Asks | Membership: whether the author, the users mentioned and whoever resolves are members, in one query per command |
| Publishes | Comment Posted, for Notification |
| Consumes | Page Deleted and Block Deleted, as a conformist, to delete the threads anchored to them |
| Owns | The comment threads, as current state |
Notification
| Aspect | Description |
|---|---|
| Responsibility | The in-app notifications of invitations and mentions (Notification), US-10 |
| Client API | The notifications of the user, Mark as read |
| Answers | Nothing |
| Asks | Nothing |
| Publishes | Nothing |
| Consumes | Member Invited and Comment Posted, through an anticorruption layer that turns them into its own Subject, an invitation or a mention |
| Owns | The notifications, as current state |
Dependencies at run time
A synchronous call couples the caller to the callee in time: the caller’s command can only complete while the callee is up, so the availability of the command is at most the product of the availabilities of the two services. An event couples them only eventually: the producer does not wait, and a consumer that is down reads the event from Kafka when it is back. Gotion keeps the synchronous calls between services to the four that check data owned by another context before a command:
| Caller | Callee | Query | Before | If the callee fails |
|---|---|---|---|---|
| Account | Membership | Role of a user | Rename, Open, Delete workspace | The command is refused; an unanswered Open leaves the main workspace as it was |
| Membership | Account | UserId of an email address |
Invite member | The command is refused |
| Editing | Membership | Role of a user, only without a row in the local copy | Join session, Submit edit, Set title, icon, cover | The command is denied |
| Discussion | Membership | Which users are members | Post comment, Resolve thread | The command is refused |
| API Gateway | Membership, then Account | The workspaces of a user with their roles; the names of those workspaces and the main workspace | Workspace directory | The request fails |
Membership is the one service asked by three others and by the gateway, and no service calls Editing, Discussion or Notification. A crash of Membership therefore stops renaming and deleting workspaces, inviting, commenting and listing the workspaces of a user, but not the editing of the pages whose roles Editing already holds. Account and Membership call each other, so each one’s availability depends on the other’s, as ADR-03 records.
Every call is made by the adapter of a port, before the command reaches the aggregate (see Building blocks), so the policy for a failure lives in that adapter, and the domain never waits on the network:
- Fail closed. A call that fails, times out or finds the circuit open ends in a refused command, never in an allowed one, as QA-06 requires.
- Timeout. Each call has a timeout well within the budget of the command that waits for it, so a slow callee never holds the caller’s requests until they pile up. The values are set once the services are measured on the reference deployment.
- One retry. The queries only read, so the adapter retries a failed one once, within the same timeout.
- Circuit breaker. After repeated failures the adapter stops calling the callee for a while and refuses at once, then lets one call through to check whether the callee is back. A callee that is down then costs its callers a quick refusal instead of a timeout on every command.
Account, Membership and Discussion do not wait for Kafka to run a command: they store outgoing events with the state in their own Transactional Outbox, and a Polling Publisher sends them when Kafka is available (ADR-05). A consumer that is down catches up later. A removed member keeps editing until Editing applies Member Removed; QA-06 bounds that delay in normal operation, including the wait in the outbox, not during an outage. Editing still publishes directly and can lose an outgoing event if it stops before Kafka acknowledges it; its readiness also requires Kafka. Event delivery describes that remaining limit.
API Composition
The API gateway builds the Workspace directory on demand, so the client gets the workspaces of the signed-in user in one request (US-02). The gateway takes the UserId from the verified sign-in token, never from a user identifier supplied by the client (QA-06), then:
- asks Membership for the
WorkspaceIdand role of each workspace the user belongs to; - asks Account for the names of those workspaces in one batch, and for the user’s main workspace;
- joins the answers by
WorkspaceIdand returns the directory, marking the main workspace only if it is among the user’s memberships.
The gateway keeps no copy of this view and reads each service through its API. It holds no business rule either: joining by WorkspaceId and leaving out a main workspace the user no longer belongs to only shape the answer, since Account itself clears a main workspace the user has lost when Member Removed, Member Left or Workspace Membership Deleted arrives, and every rule on workspaces and roles stays in Account and Membership. A workspace already deleted in Account is omitted while its membership is being removed by policy. If either service fails to answer, the directory request fails rather than returning an incomplete list. Account owns the workspace data and the main workspace, and Membership owns the memberships and roles.
State and scaling
Account, Membership, Discussion and Notification keep their durable state in their databases; the first three also keep their pending outgoing events there. Each one runs as a Kubernetes Deployment, whose replicas are interchangeable behind a Service; a caller finds a service by the DNS name of its Service, and Kubernetes picks the replica (server-side discovery); Editing is reached instead by the stable name of each instance, as below. The consumers of a service share its Kafka partitions as one consumer group. Since every event is keyed by its aggregate, the events of one aggregate still reach one replica in order. Each publishing Go service runs its polling task in the same process; a database lock permits only one active publisher across its replicas, preserving the order of each aggregate’s events (ADR-05). Notification publishes nothing and needs no outbox or publisher. The prototype runs one replica of each. Each service has one PostgreSQL server of its own, not replicated (ADR-06): the reference deployment is a single node, so replicating or partitioning the stores is out of scope.
Editing is different: it holds the session of every open page, with its collaborators and the replica of its tree, and it is the one relay of the operations of a page.
The CRDT needs every operation of a page to go through the same relay (ADR-01), so a page belongs to one instance of Editing, chosen by a fixed rule instead of an assignment kept somewhere: the instances form a Kubernetes StatefulSet, and page P belongs to the instance hash(P) mod N. The gateway reads P from the path of the WebSocket and forwards it to that instance by its stable DNS name (editing-k.editing), so no table of assignments and no service discovery are needed. When an instance crashes, Kubernetes replaces it with a new one under the same identity, which replays the session log of its pages from the last snapshot (ADR-02) while the clients reconnect: the pages stay with that identity, and nothing is rebalanced (QA-04). Two instances must never relay the same page at once, or the order of its operations splits. A StatefulSet starts the replacement only after the old instance has terminated, and, whatever the orchestrator does, each append to the session log carries the sequence number it expects for its page, so an instance that falls behind gets its append refused and acknowledges nothing. The prototype runs N = 1, which is enough for the five editors of a page in QA-02: while that instance restarts every page is read-only, for up to the 60 s of QA-04, not only the pages of one instance. With Compose (QA-08) the same rule is one container that restarts on failure. Changing N moves pages between instances, so it is done with Editing stopped.
Contracts
The services are deployed and versioned separately, so what one of them shows to the others is a contract: the client API, the queries it answers and the events it publishes. Inside a service the model can change freely, and only a change of the contract concerns another service.
- Each contract has a specification kept with its service. The REST APIs, the client API and the queries alike, are described in OpenAPI; the events and their channels in AsyncAPI. The schema of each message is the source from which Go and TypeScript generate their types, since an event of Editing is published in TypeScript and consumed in Go, and the reverse (ADR-04). The schemas are JSON Schema, with no schema registry (ADR-08).
- Every event has the same envelope, one JSON Schema for the whole system,
api/envelope.schema.jsonat the root of the repository:eventId, its own identifier;typeandversion, the name of the event and the version of the schema of its body;aggregateId, the identity of its aggregate, which is also its Kafka key;occurredAt, when it happened, in UTC; anddata, the body. The body carries the identities and values the consumers need, never an object of the producer’s model, and repeats the identity of the aggregate under its own name, such asworkspaceId, so that it reads on its own. Since the envelope is the same for every event, a consumer reads it first, skips an event it has already applied and picks the handler bytypeandversion, and only then reads the body. - A compatible change keeps the version. Adding an optional field is compatible: a consumer ignores a field it does not know. Removing or renaming a field, changing its type or its meaning is not: the producer publishes the new version next to the old one until every consumer has moved, then stops the old one. The queries follow the same rule, with the version in their path.
- Every consumer is idempotent. Kafka delivers an event at least once, so a consumer may read it twice, for instance after a restart of the consumer, or of a publisher that sent the event but had not marked it as sent (ADR-05). A consumer commits its offset only once the change the event causes is stored, and keeps the identifiers of the events it has applied, so a repeated one changes nothing. Many policies are idempotent anyway: deleting the threads of a page that has none changes nothing.
- A contract test guards each contract. The consumer states what it reads, and the test runs in the pipeline of the producer, so a change that breaks a consumer fails before it is merged. For the events, it checks that a consumer in one language reads what a producer in the other writes (ADR-04). Contract tests describes how.
Every service keeps its specifications in the api/ folder at its root, Account for instance:
api/
└── envelope.schema.json the envelope of every event
services/account/api/
├── openapi.yaml the client API and the queries
├── asyncapi.yaml the channel of Account and its events
├── events/
│ ├── workspace-created.v1.json the body of each version of an event
│ └── workspace-deleted.v1.json
└── contracts/<consumer>/ what each consumer reads
openapi.yamlis in OpenAPI 3.1. The client API is under/v1/, and the gateway forwards it with the identity of the signed-in user inX-User-Id(ADR-09). The queries for other services are under/internal/v1/and take the user as a parameter; the gateway never forwards them, so a client cannot ask, for instance, which user an email address belongs to. The version in the path is the major one, raised only by a change that is not compatible. Errors are answered asapplication/problem+json(RFC 9457), and a status code means the same in every service: 400, a request that does not match its schema; 403, a member whose role does not allow the command; 404, something that does not exist, and equally a workspace the user is not a member of, so that a non-member cannot tell the two apart (QA-06); 409, a command the rules of the aggregate refuse in its present state, such as removing the last Admin; 422, a well-formed request that names something another service does not know, such as an email address no user is registered with; 503, a service the command must ask did not answer, so the command is refused (fail closed).asyncapi.yamlis in AsyncAPI 3.0, with one channel: a Kafka topic named after the context (account,membership) that carries all its events. Kafka keeps the order only within a partition of one topic, so the events of one aggregate, of whatever type, stay in order only if they share the topic as well as the key: Member Joined and Member Removed for the same workspace, for instance. Each message is the envelope with itstypeandversionfixed and the schema of its body asdata.events/<event>.v<version>.jsonholds the JSON Schema of the body of one version of an event, the file from which Go and TypeScript generate their types. A new version is a new file next to the old one. The envelope has one type in each runtime, in its chassis.contracts/<consumer>/holds the examples of each consumer (Contract tests).
The protocol between the client and Editing is not one of these contracts: both import it from the same package as the CRDT, and they are upgraded together (ADR-01, ADR-04). The operations in the session log are the exception, because they outlive the version that wrote them: each one carries the version of the protocol, so that the older ones can still be replayed (ADR-02).
Patterns
The microservice patterns Gotion applies, gathered in one place. Most of them are described where the decision that needs them is taken; the table names the problem each one solves and links to that description. Observability has no other place in the design, so it is described below.
| Category | Pattern | Where | Problem it solves | Described in |
|---|---|---|---|---|
| Decomposition | Decompose by subdomain | Every service | A change to one model stays in one service (QA-09), each service migrates only its own schema (QA-08), a crash of Editing leaves the other services working (QA-04) | Decomposition |
| Data management | Database per Service | Every service | No store is shared, so no schema change concerns two services (QA-08, QA-09) | Repository view |
| Data management | Aggregate | Every bounded context | One command changes one aggregate in one transaction, so each invariant is checked in one place and no transaction spans two services | Tactical Design |
| Data management | Domain Event | Every upstream context | A context reacts to a change in another without the producer knowing who listens | Event-based view, Contracts |
| Data management | Event Sourcing | Editing | An edit is acknowledged after one durable append, within QA-01, and survives a crash (QA-04) | ADR-02 |
| Transactional messaging | Transactional Outbox | Account, Membership, Discussion | A committed change and its outgoing events survive a service restart together, including role revocations (QA-06) | ADR-05 |
| Transactional messaging | Polling Publisher | Account, Membership, Discussion | Pending events reach Kafka after an outage without adding a CDC connector | Event delivery, ADR-05 |
| Querying | CQRS | Editing, local copy of the roles | Editing checks the role of every edit without a call to Membership on the path of the ack (QA-01), and keeps working while Membership is down | ADR-03 |
| Querying | API Composition | API gateway, Workspace directory | The client gets the workspaces of a user, owned by Membership and Account, in one request, and no copy of them has to be kept in sync | API Composition |
| Communication | Messaging | Every upstream context, through Kafka | The domain events reach their consumers without the producer waiting for them | Event-based view, Event delivery |
| Communication | Remote Procedure Invocation | The four queries between services | A command checks data owned by another context before it runs | Dependencies at run time |
| Communication | Circuit Breaker | The adapters of those queries | A callee that is down costs a quick refusal instead of a timeout on every command, and a failure always refuses (QA-06) | Dependencies at run time |
| Communication | Idempotent Consumer | Every Kafka consumer | Kafka delivers an event at least once, and a repeated one must change nothing | Contracts |
| Communication | API Gateway | Entry point of the client | One place authenticates every request and routes it, the WebSocket of a page to the instance of Editing that owns it | Components and Connectors, State and scaling |
| Security | Access Token | Gateway, Account | The gateway checks the identity on every request without calling Account, from a JWT that Account signs and the browser sends in a cookie; the token carries no role, so a change of role needs no new token (QA-06) | ADR-03, ADR-09 |
| Testing | Consumer-driven contract test | The pipeline of each producer | A change that breaks a consumer, in the same language or the other one (ADR-04), fails before it is merged | Contracts, Contract tests |
| Cross-cutting concerns | Microservice Chassis | API gateway and every service, one chassis per runtime | Health checks, metrics, configuration, logs, messaging, the outbox and the calls to other services are built once for each runtime, not in every service | ADR-07 |
| Cross-cutting concerns | Externalized Configuration | Every service | The same image runs in every environment, configured by environment variables from a ConfigMap or a Secret in Kubernetes, and from Compose (QA-08) | ADR-07 |
| Cross-cutting concerns | Server-side discovery | Kubernetes Services | A caller reaches a service by the DNS name of its Service, and Kubernetes picks the replica, with no registry of our own | State and scaling |
| Deployment | Service per container | Every service | Each service is built, shipped and restarted on its own, whatever its runtime (ADR-04) | Deployment |
| Deployment | Service deployment platform | Kubernetes | The platform restarts, scales and routes the instances, with no script of our own (QA-04) | Deployment |
| Observability | Health Check API | Every service | Kubernetes restarts an instance that is stuck and sends traffic only to one that is ready (QA-04) | Observability |
| Observability | Application Metrics | Every service and the client | The runtime scenarios are measured while the system runs (QA-01 to QA-04, QA-06, QA-07) | Observability |
Observability
The quality attribute scenarios of Analysis set the targets; observability shows whether the running system meets them. Every service exposes a health check and its metrics next to its API, through adapters of the hexagon, so the domain knows neither Kubernetes nor Prometheus.
Health Check API. Each service answers two checks, which Kubernetes polls:
- Liveness,
/health/live, answers as long as the process can serve a request. It checks no dependency, since restarting a service does not bring its database back. A failed check makes Kubernetes restart the instance. - Readiness,
/health/ready, requires a reachable database. It does not require Kafka where a lost connection loses no event: Account, Membership and Discussion enqueue their events in the outbox during an outage (ADR-05), and every consumer, Notification included, resumes from its offset when Kafka returns. Only Editing requires Kafka, since it publishes directly; it also waits for the session logs of its pages to be replayed (ADR-02). Until ready, the instance gets no traffic. The time from a crash to readiness is the recovery time of QA-04.
Readiness leaves out the services a service queries: a Membership that is down is handled by the circuit breaker (Dependencies at run time), and must not make Editing unready, which ADR-03 avoids.
Application Metrics. Each service exposes its metrics on /metrics in the Prometheus format, and Prometheus pulls them. Next to the rate, errors and duration of the requests of each adapter, these metrics measure a scenario:
| Scenario | Metric | Measured in |
|---|---|---|
| QA-01 | Time from a keystroke to its render; time from an operation to its ack | The client; Editing |
| QA-02 | Time from the ack of an operation to its render in another client | The client |
| QA-03 | Time from opening a page to the page accepting input | The client |
| QA-04 | Restarts; time to replay the session logs; time from a crash to readiness | Every service; Editing |
| QA-06 | Lag from the change in Membership to its application in the local copy of the roles, including the wait in the outbox | Membership; Editing |
| QA-07 | Failed and throttled sign-ins | Account |
The client sends its measures to Editing through the gateway, off the WebSocket of the session, so they never delay the operations they measure. The dashboards and alerts are in Monitoring.
Account, Membership and Discussion also expose the number of pending outbox events and the age of the oldest one, so a stopped publisher or a Kafka outage is visible even when no event reaches a consumer.
Log aggregation, distributed tracing, exception tracking and audit logging are left out of the prototype, since no scenario depends on them; each service writes structured logs to its standard output.
Event delivery
A command changes the store of its service and publishes an event on Kafka. No transaction spans a database and Kafka, so each service keeps the two writes together in one of two ways.
Transactional Outbox and Polling Publisher (ADR-05). Account, Membership and Discussion store each outgoing event in their own database, in the same transaction as the change that raises it. A background publisher, the Forwarder of Watermill (ADR-07), polls pending rows, sends them to Kafka in order within each aggregate and marks them as sent only after acknowledgement. A restart resumes the pending work; a failure after publication can cause a duplicate, which the idempotent consumer ignores. The publisher coordination, cleanup and tests are specified in ADR-05. Notification publishes no events and needs no outbox.
Editing keeps direct publication after the operation is stored in its session log and applied to the tree. Its producer retries from memory, so Page Deleted or Block Deleted can still be lost if Editing stops before Kafka acknowledges them, leaving orphan threads in Discussion. This accepted limit does not affect the durability of acknowledged edits in ADR-02. The outboxes protect the other services’ events, including Member Removed, but do not guarantee delivery within QA-06’s bound during an outage.
Cascades without a saga. Workspace Created makes Membership create the membership and Editing the root page; Workspace Deleted makes both delete them, and the Page Deleted that Editing then publishes makes Discussion delete the threads. Each step is a local transaction started by the event of the step before, with no coordinator. No step can be refused by a rule of its context, so none has to undo the steps before it, and the cascade needs neither an orchestrator nor compensations. Kafka’s at-least-once delivery and the idempotent consumers make a published event’s step happen eventually once the services recover. An event lost before publication by Editing can still stop the cascade. A policy that could be refused would turn its cascade into a saga.
Architecture Decision Records
Each architecturally significant decision is recorded after Nygard and Richards: Title, Status, Context, Decision, Consequences and Compliance. A record stays Proposed until it is reviewed, and is never edited once Accepted: a later decision supersedes it.
ADR-01: Replicas merge concurrent edits with our own CRDT, Editing relays the operations
Status: Accepted.
Context. Pages are edited together in real time (US-08). Concurrent edits must converge without dropping an acknowledged one (QA-05), the local render must stay within 50 ms (QA-01), an acknowledged edit must reach the other collaborators within 300 ms (QA-02), and a new block type must not touch synchronization or persistence (QA-09). The merge of concurrent edits is a concern of the core subdomain, so it is worth owning. The decision answers PP-01: are concurrent edits ordered and merged by a central sequencer in Editing, or do replicas merge on their own? The alternatives were:
- operational transformation, with Editing as the central sequencer;
- Yjs, with any editor, including the collaboration built into BlockNote;
- a CRDT of ours that every replica runs, with Editing as the relay of the operations.
Operational transformation needs a transformation for every pair of kinds of operation: text against text, text against a block inserted, moved or deleted, a move against a move, and so on. Each new kind of operation adds a transformation against every existing one, and each pair must be proved correct on its own. A move in a tree is a known hard case for it. A CRDT instead defines each operation so that it commutes with the others, its convergence is tested on the module alone, and a move in a tree has a published algorithm (Kleppmann et al.).
Yjs works against the domain model. A Yjs update is an encoded change of its own types, XML elements and text, not an operation of the domain: to check a rule Editing would have to decode each update and apply it to a copy of the page, and the domain events would be derived from those low-level changes. Yjs has no move for an element, so a move is a deletion plus an insertion: two concurrent moves of the same block can leave two copies of it, and nesting a block is a move too, so what a collaborator types in it meanwhile goes with the deleted copy. Yjs does not define when an edit is acknowledged. And the merge, a concern of the core subdomain, would be left to a generic library.
Our CRDT also has to move text between blocks. Dividing a block in two (Enter) and joining a block to the one before (Backspace at its start) move characters from one block to another. With a sequence of characters for each block, the moved text would be deleted from one sequence and copied into the other as new characters, while an operation that a collaborator makes meanwhile on that text would still target the old ones: an insertion would end up in the block that keeps the first part, a deletion would be undone by the copy, two divisions of the same block at once would duplicate the text between them, and an edit in a block joined at the same time would be lost. Every replica would converge, but those edits would be discarded or misplaced without anyone being told, against QA-05.
Decision. We will synchronize the replicas with a CRDT of ours. This settles PP-01:
- every replica merges concurrent operations on its own, with our CRDT;
- Editing is the one relay of the operations of a page: it checks each operation, stores it, acknowledges it to its author and relays it to the other collaborators;
- the CRDT is a module with no dependency on any editor: one sequence of characters for the text of the whole page, with the styles as marks over its characters, and a tree of blocks with a move operation;
- every block has a marker in the sequence, and a character belongs to the block of the nearest marker before it. A marker only says which block its characters belong to: where a block is, and under which parent, is decided by the tree alone, so moving or nesting a block touches neither its marker nor its characters. Blocks inserted at the same place in the tree at the same time are ordered as their markers are in the sequence, so two divisions of the same block keep the order of its text;
- dividing a block (Enter) inserts the marker of a new block after the character where it is divided, and the new block in the tree right after the divided one. No character is copied: the second part keeps its own characters, and an edit made meanwhile on them stays with them. A line break inside a block (Shift+Enter) is a character, not a marker;
- joining a block to the one before removes its marker and takes the block out of the tree, so its characters belong to the block of the previous marker, again with no copy. That is the block before it as long as the two are neighbours in the sequence too (see the bad side below);
- deleting a block deletes its characters and takes it out of the tree, but keeps its marker, so a character typed in it meanwhile stays in the deleted block instead of moving to the one before;
- the editor of the client is only an adapter: it turns the changes of the editor into operations and applies the remote ones. The choice of the editor is a design choice behind the adapter, described in Editing client.
A prototype confirmed the approach. Ten clients typed in the same block, the cursor and the selection held under remote edits, every client converged, and the local render stayed well within QA-01. That prototype edited a single block. Three later ones, with BlockNote, Slate and plain ProseMirror behind the same operations, also kept two clients in step while blocks were divided, joined and nested, and while each client undid its own edits only. Those prototypes divided and joined blocks by copying their text; the markers of the sequence of the page are not prototyped yet.
Consequences. On the good side:
- The commands of the Page Block Tree stay commands. Editing refuses an operation that breaks a rule, for example a page block that changes type, together with the later operations of the same author that build on it, and the author reverts them before any other replica sees them. Block Inserted, Block Moved and Block Deleted come from the operations.
- The tree of blocks has its own move, so two concurrent moves can neither duplicate a block nor nest one under itself. Nesting a block moves it without touching its text, so what a collaborator types in it meanwhile stays.
- Dividing and joining a block copy no character, so an edit made meanwhile on its text keeps its effect, and two divisions of the same block at once leave every character in one block only (QA-05).
- Editing defines when an edit is acknowledged. It can append each operation to a durable log before acknowledging it, as QA-01 and QA-04 ask, and that log is the Event Sourcing of Editing. The log itself is settled in ADR-02.
- The merge of concurrent edits, part of the core subdomain, is our own code.
- There is no Yjs server to run, and nothing keeps editing while disconnected: the editor becomes read-only when the connection drops, as the scope requires.
On the bad side, each to be settled before or while Editing is built:
- More to build: the styles as marks, the markers of the blocks in the sequence of the page, the tree of blocks with its move, a snapshot for a collaborator who joins late, reconnection and the resending of unacknowledged operations.
- Presence (US-08) is part of our own protocol, with no Yjs awareness to rely on.
- Joining two blocks that are not neighbours in the sequence is still to be settled. Once a block has been moved or nested, the block before it in the tree may not own the marker before its own, and removing its marker would give its characters to that other block: such a join needs an operation of its own. What a join does to the blocks nested in the joined one, and to the comment threads anchored to it, is still to be settled too.
- One sequence holds the text of the whole page, so finding a character and the block it belongs to needs an index over the sequence, as a long page already does (Editing client).
- QA-09 holds only while the operations stay generic: insert a block of any type with its properties, set a property, edit text. A block type that needs an operation of its own breaks it.
- One instance of Editing relays a page at a time. Through a single relay every collaborator gets the operations of a page in an order that respects what each one builds on, as the CRDT needs. With several instances, every operation of a page must reach the same one, and the page moves to another when that instance fails (QA-04). How a page reaches its instance is still to be settled.
- The CRDT runs on both sides. Editing applies the operations to the Page Block Tree, so it runs the CRDT module as the client does: either Editing shares the runtime of the client, or the module is written twice and both versions pass the same tests. The runtimes are still to be settled.
- Coupling between client and Editing. Both share the protocol of the operations and the block schema, so they are upgraded together.
- The adapter is the fragile part. It derives the operations from the editor, which is described with its risks in Editing client.
Compliance.
- The test of QA-05, over 1 000 randomized interleavings, runs on the CRDT module alone. It includes concurrent moves of the same block, moves that would create a cycle, edits concurrent with a move, and blocks divided and joined while other edits insert, delete and style their text. Besides convergence, it checks that every character inserted, never deleted and not in a deleted block appears exactly once, and that no deleted character appears. Until the join of blocks that are not neighbours in the sequence is settled, the test joins only neighbours.
- A fitness function checks that only the adapter of the client imports the editor library or ProseMirror, and never the CRDT module or the domain of Editing.
Deterministic tests on the CRDT module check that an insertion, a deletion or a style concurrent with dividing or joining a block keeps its effect on the same characters, and pin down the outcomes below, which follow from the rules of the Decision. In each row Alice and Bob start from the blocks shown, act at the same time, and every replica ends with the last column. Blocks listed together are neighbours in the sequence, as after typing one after the other.
| Blocks | Alice | Bob | Every replica |
|---|---|---|---|
| “Hello world” | Divides it before “world” | Types “X” right before “world” | “X” at the end of the first block or at the start of the second, the same on every replica |
| “Hello world” | Divides it before “world” | Divides it before “world” too | “Hello “, an empty block and “world” |
| “one two three” | Divides it before “two” | Divides it before “three” | “one “, “two “ and “three” |
| “Hello”, “big world” | Joins “big world” to “Hello” | Divides “big world” before “world” | “Hellobig “ and “world” |
| “a”, “b”, “c” | Joins “b” to “a” | Joins “c” to “b” | “abc” |
| “Hello”, “world” | Joins “world” to “Hello” | Deletes the block “world” | “Hello” |
| “Hello”, “world” | Deletes the block “world” | Types “!” at the end of “world” | “Hello” |
ADR-02: Editing acknowledges an operation once it is in a durable log
Status: Proposed.
Context. ADR-01 makes Editing the one relay of the operations of a page, so Editing decides when an edit counts as acknowledged. Three scenarios depend on that moment: QA-01 times the server acknowledgement and asks for the character to be durably persisted, QA-04 asks that every acknowledged edit survives a crash of Editing, and QA-05 that none is silently discarded. The session takes an operation and hands it to the Page Block Tree, which checks it and applies it. The alternatives were:
- acknowledge after the merge, and apply the operation to the tree asynchronously;
- acknowledge after the operation is applied to the tree and the tree is saved;
- acknowledge after the operation is appended to a durable log of the session, then apply it to the tree.
Acknowledging after the merge breaks QA-04: a crash between the ack and the store loses an acknowledged edit, and the SLI of QA-01 would time less than the real path. Saving the tree before every ack is durable, but it puts a whole write of the tree on the path of every keystroke, against the 500 ms (p95) of QA-01.
Decision. We will acknowledge an operation only once it is appended to a durable log:
- Editing checks the operation, appends it to the log of the session of its page, acknowledges it to its author, relays it to the other collaborators and then applies it to the page block tree;
- the log is the Event Sourcing of Editing: after a restart Editing replays it onto the tree from the last snapshot;
- the ack is where the timer of the QA-01 SLI stops, and where the timer of QA-02 starts;
- the ack names the operation by its identity and gives its sequence number in the log. A replica that reconnects, after its connection drops or Editing crashes, submits again the operations it has no ack for, and Editing acknowledges again, without appending it twice, one that is already in the log, provided it is the same operation, and closes the connection as malformed otherwise (QA-04).
Consequences. On the good side:
- One append per operation is the cheapest durable write, so the ack stays within QA-01.
- No acknowledged edit is lost in a crash (QA-04): what the tree misses is still in the log.
- Replaying the same order of operations keeps every replica converging (QA-05).
- The log also feeds the snapshot for a collaborator who joins late, one of the bad sides of ADR-01.
On the bad side:
- The log grows with every keystroke: it needs snapshots of the tree and a compaction of the operations before them.
- The tree lags behind the log for a moment, so anything that reads the stored tree may miss the last operations. The page open of QA-03 does not read it: the answer to Join session carries a snapshot up to a sequence number of the log, and the operations after it follow in the order of the log (Components and Connectors).
- The store of the log must make an append durable before it returns, and refuse an append whose sequence number is not the next one of its page, so that two instances of Editing can never both extend the log of the same page. ADR-06 chooses it and meets both.
- The operations in the log outlive the version of the protocol that wrote them: a change to the operations needs a version on each one and a way to replay the older ones.
Compliance.
- The chaos test of QA-04 kills Editing under load and checks that every acknowledged operation is in the page after the restart.
- The SLI of QA-01 is measured from the submit to the ack, so an ack sent before the append shows up as a broken test, not as a better number.
ADR-03: Editing keeps a local copy of the roles, Account and Discussion ask Membership
Status: Proposed.
Context. Membership is the one writer of the roles and of who is a member, but three other contexts check them on their own commands, as the Roles table shows: Account lets only an Admin rename or delete a workspace and opens only workspaces the user belongs to, Editing lets a Viewer read but not change the content, and Discussion lets only members post, resolve and be mentioned. The Context Map says what each of them gets from Membership; this record settles how it reaches them, which is PP-04. Notification is not part of it: it reacts to Member Invited and never checks a role or a membership.
The three contexts differ in what is at stake. Editing checks the role on every edit, on the path that QA-01 bounds at 500 ms (p95) from the edit to the ack, and inside a session that stays open for as long as the page is edited. Account checks it on renaming and deleting a workspace, rare commands that cannot be undone, and on opening one, where it only decides whether to save it as the main workspace. Discussion checks it on a comment, where a few milliseconds more change nothing. QA-06 asks that every request of a non-member or a Viewer is denied. The alternatives were:
- a local copy of the roles, kept by each context from the events of Membership (Member Joined, Member Role Changed, Member Removed, Member Left, Workspace Membership Deleted): a CQRS view of Membership’s data inside the context that reads it, also called Event-Carried State Transfer;
- a synchronous query to Membership on every command that needs the role;
- the roles in a JWT issued at sign-in, which each service verifies on its own;
- the local copy, with a query to Membership when the copy has no row for the user and the workspace.
The local copy costs nothing on the path of an edit and keeps Editing working while Membership is down, but a removed member keeps acting until the event arrives, and a member who has just joined is refused until it arrives. The query is always up to date, but it puts a call to another service before every ack, and when Membership is down nothing can be checked, so nothing is allowed. A JWT is checked at no cost, but it cannot be revoked before it expires, it would carry a role for every workspace of the user, and whoever issues it at sign-in would have to know the roles of Membership, adding a dependency to Account and Membership, already the tightest pair of the map.
Decision. Each context reads the roles in the way that fits its commands:
- Editing keeps a local copy, and asks Membership only when the copy has no row. Its
AccessLookupServiceis an adapter over a table(UserId, WorkspaceId) → read | change, fed by the events of Membership: the anticorruption layer turns a role into what Editing cares about while it updates the table. When the table has no row, the adapter asks Membership once for that command. It does not write the answer into the table, so an answer that comes back after a later Member Removed cannot overwrite it: the event fills the table soon after anyway. If Membership does not answer, the command is denied. A short cache of the negative answers keeps a non-member who probes pages (the stimulus of QA-06) from turning every attempt into a call to Membership. - Editing removes a removed member from the open sessions. On Member Removed, Member Left and Workspace Membership Deleted a policy makes the user leave the sessions of the workspace, so they stop receiving the operations of its pages. A change to Viewer needs no policy: the next edit is checked against the table and refused.
- Account asks Membership whether the user is an Admin before renaming or deleting a workspace, and whether the user is a member before opening a workspace and saving it as main. If Membership does not answer, the command is refused and the saved main workspace stays unchanged. Account listens to Member Removed, Member Left and Workspace Membership Deleted to clear a main workspace the user has lost.
- Discussion asks Membership whether the author, every user mentioned and whoever resolves are members, in one query per command for all of them. If Membership does not answer, the command is refused. Discussion no longer listens to the events of Membership.
- For these command checks, Membership’s open-host service answers two queries, in the same published language as its events: the role of a user in a workspace, and which of a set of users are members of a workspace. For a workspace that does not exist it answers as for one the user is not a member of, so the query leaks nothing (QA-06).
- The sign-in token carries only the identity of the user, never a role.
This settles PP-04.
Consequences. On the good side:
- The check on an edit is a local read, so QA-01 keeps its whole budget for the append of ADR-02, and Editing keeps accepting edits while Membership is down.
- A member who has just joined is not refused by Editing, and a new instance of Editing answers while its table is still being rebuilt from the events.
- Renaming and deleting a workspace see the roles as they are now: a demoted Admin cannot delete it a moment later.
- Discussion has no copy to keep, no consumer and nothing to rebuild.
- The domain of Editing, Account and Discussion does not change:
AccessLookupServiceandMembershipLookupServiceare ports, and the choice is in their adapters.
On the bad side:
- Editing is eventually consistent with Membership. Between Member Removed and the moment Editing applies it, a removed member can still edit and still receives the operations of the session; between Member Role Changed and its event, a member demoted to Viewer can still edit. The window is the lag of the events, including their wait in the outbox of Membership (ADR-05), bounded by the response measure added to QA-06.
- Account and Discussion depend on Membership at run time. When it is down, no workspace can be renamed or deleted, opening one leaves the main workspace as it was, and no comment can be posted. Account and Membership already depend on each other through events; now each one also calls the other (Membership asks Account for the user registered with an email address), so each one’s availability depends on the other’s.
- Editing has two adapters behind one port, the table and the query, both to be tested.
- While a new instance of Editing rebuilds its table, every check falls back to Membership, so a restart under load moves that load onto Membership for a moment.
- Membership’s queries are part of its published language: changing them is a change of its contract, versioned like its events.
Compliance.
- An integration test of each adapter checks that a denied, an unreachable and a slow Membership all end in a refused command.
- The security test of QA-06 removes a member while they are editing, demotes another to Viewer, and checks that Editing refuses their edits and drops the removed one from the session within the bound of QA-06.
- The SLI of QA-01 is measured with the table of the roles in place, so a call to Membership on the path of an edit shows up as a slower ack.
- A fitness function checks that only the adapter of
AccessLookupServicein Editing consumes the events of Membership, and that Discussion consumes none of them.
ADR-04: Editing runs on Node.js with the CRDT of the client, the other services on Go
Status: Proposed.
Context. The backend services are written in Go, the client in TypeScript with React. ADR-01 runs our CRDT on both sides, in the client and in Editing, the real-time service of US-08, and leaves open whether Editing shares the runtime of the client or has a second implementation of the module that passes the same tests. With two implementations, QA-05 would rest on two pieces of code that must agree on every operation, and any difference between them would make the client and Editing diverge on the same page.
Decision. We will assign the runtimes as follows:
- Account, Membership, Discussion and Notification are written in Go.
- Editing is written in TypeScript and runs on Node.js. It holds the WebSocket of every open page and relays its operations (ADR-01).
- The CRDT is one TypeScript package, with no dependency on the browser, on Node.js or on any editor. The client and Editing both import it. The protocol of the operations and the block schema are shared the same way.
- The client is written in TypeScript with React.
- The API gateway is written in Go too, on the same chassis as the four Go services (ADR-07).
- Every service is built into its own container image, so the deployment handles a Go service and a Node.js one the same way.
This settles the runtimes left open by ADR-01.
Consequences. On the good side:
- The CRDT is written once. The convergence test of QA-05 runs on the package both sides import, so it covers Editing as well as the client.
- The client and Editing are upgraded together (ADR-01). With the protocol and the block schema as shared types, a change on one side that the other does not follow fails the type check.
- A Go service compiles to one static binary, so its image is small and carries no runtime.
On the bad side:
- Each language has its own build, tests, linter and image, so the CI has jobs for both, and the team works in two languages.
- The events cross languages: Editing publishes and consumes them in TypeScript, the other services in Go. Each published language needs a schema from which both sides generate their types, in the format of ADR-08. Without it, a field renamed on one side breaks the other only at run time.
- The skeleton of a service exists twice, in Go and in TypeScript: the hexagonal structure,
/healthand/metrics, the Kafka consumer that ignores a repeated event, the migrations of QA-08. ADR-07 reduces it to a thin chassis per runtime, assembled from libraries.
Compliance.
- A fitness function checks that the client and Editing import the CRDT only from the shared package.
- The CI builds, tests and packages each service in its own runtime, and
successcollects the jobs of both. - A contract test of each event checks that a consumer in one language reads what a producer in the other writes, against the shared schema.
- The SLI of QA-01 is also measured while Editing takes a snapshot, so a task that blocks the thread shows up as a slower ack.
ADR-05: Go publishers use a Transactional Outbox with polling
Status: Accepted.
Context. Account, Membership and Discussion are the Go services that both change their own state and publish events on Kafka (Decomposition, Contracts). The two writes are in separate systems, and a service can stop between them. A lost Member Removed leaves a removed member able to edit, against QA-06; a lost Workspace Deleted leaves the membership and the pages of the workspace in place; a lost Comment Posted never notifies the mentioned users (US-10). The alternatives were:
- publish before the commit;
- publish after the commit;
- a transaction across the database and Kafka;
- a Transactional Outbox: the event written into a table of the same database, in the same transaction as the state, and published by a process that polls the table;
- the same outbox, published by reading the transaction log of the database (change data capture), with a connector such as Debezium on Kafka Connect.
Publishing before the commit can announce a change that is rolled back. Publishing directly after the commit avoids that, but can lose the event if the service stops before Kafka acknowledges it. Kafka transactions alone do not make the database commit and the publication atomic. The outbox closes that gap by storing the event with the state. Polling uses the service’s database and Kafka client; change data capture would also add Kafka Connect and a connector to the deployment.
Decision. Account, Membership and Discussion will each use a Transactional Outbox with a Polling Publisher:
- The transaction that changes the aggregate also inserts its outgoing events, with their stable identifiers and payloads, into an outbox in the same database. This applies to client commands and to policies triggered by incoming events. For a consumed event, the record that it was applied is part of that transaction too; its Kafka offset is committed only afterwards.
- A background task in the service polls committed, pending rows, publishes them on Kafka and marks each one as sent only after Kafka acknowledges it. Pending rows survive restarts and Kafka outages; sent rows are cleaned up afterwards. The task is an infrastructure adapter, not another service.
- Changes to the same aggregate are serialized in their database transactions, including the insertion into the outbox. The publisher preserves that order and does not pass an unacknowledged event with a later one of the same aggregate. A database lock allows only one publisher per service to be active across its replicas; another replica takes over when the lock is released after a failure.
- An event can be published again if the publisher stops after Kafka acknowledges it but before the row is marked as sent. It keeps the same identifier, and the idempotent consumers of Contracts ignore the duplicate.
- Notification has no outbox because it publishes no events. Editing is excluded: it still publishes directly after the operation is in its session log (ADR-02) and applied to the Page Block Tree, retrying from memory until Kafka acknowledges it.
- The library that realizes the outbox and its publisher, the Forwarder of Watermill, is chosen in ADR-07.
Consequences. On the good side:
- A committed change in Account, Membership or Discussion cannot lose its outgoing event merely because the service restarts. A rolled-back change publishes nothing.
- Commands in those services do not wait for Kafka: an outage leaves events in the database until publication resumes.
- No new deployment component is needed, and the event contracts and idempotent consumers stay the same.
On the bad side:
- Each of the three services needs a table and migration, the publisher, its lock and cleanup. A long Kafka outage grows the pending rows; their count and oldest age must be monitored.
- Polling adds latency. Its interval and the backlog must fit the 5 s (p99) revocation bound of QA-06 in normal operation; durable publication alone cannot guarantee that bound during an outage.
- Editing can still lose Page Deleted or Block Deleted if it stops before Kafka acknowledges them. The session log protects acknowledged edits, not the delivery of those events: Discussion can retain orphan threads, including after the chaos test of QA-04. Cascades through Editing retain that limit.
Compliance.
- For each of the three services, a failed transaction leaves neither the state change nor an outbox row, and publishes no event.
- A test stops Kafka, commits a command, restarts the service and then Kafka, and checks that the pending event arrives.
- A test stops the publisher after Kafka acknowledges an event but before it is marked as sent; after restart, the duplicate changes nothing in the consumer.
- Concurrent commands and competing publishers are tested for publication in transaction order within each aggregate and takeover after the active publisher stops.
- A repeated incoming event changes the state and enqueues its outgoing events only once, including when the consumer restarts before committing its offset.
- The security test of QA-06 measures from the change in Membership to its application in Editing, including the wait in the outbox.
ADR-06: Each service keeps its data in a PostgreSQL server of its own
Status: Proposed.
Context. Every service owns its store, and no other service reads or migrates it (Database-per-Service, Repository view). Three records ask something of those stores. ADR-02 leaves the store of the session log of Editing to choose, with two requirements: an append is durable before it returns, and an append whose sequence number is not the next one of its page is refused. ADR-05 needs the change of an aggregate and its outbox row in one transaction in Account, Membership and Discussion. ADR-03 keeps a copy of the roles in Editing. Two scenarios bound the choice: QA-08 installs the whole system on a clean host, with the schema migrations run automatically and no manual database step, and QA-01 allows 500 ms (p95) from an edit to its ack, which includes the append. The alternatives were:
- a dedicated event store for the session log, such as EventStoreDB (now KurrentDB), next to the database of the other stores;
- Kafka as the session log;
- a database of a different technology for each service;
- PostgreSQL for every store, the session log included.
An event store has the append the log needs: it takes the version the stream is expected to have and refuses the append otherwise. But it is a second engine to install, configure, back up and migrate next to the one of the other services, for a single store. Kafka is already deployed, but it has no append conditional on the expected sequence number, so it cannot refuse the append of an instance that fell behind. A different database for each service adds technologies that QA-08 must install, migrate and back up.
Decision. We will keep every store in PostgreSQL, with one server for each service:
- Account, Membership, Editing, Discussion and Notification each have their own PostgreSQL server, holding the schema of that service only, with no replica. The API gateway has no database.
- The session log of Editing is a table with the primary key
(page_id, seq). An append is anINSERTin a transaction that commits before Editing acknowledges the operation; anINSERTwith aseqalready used violates the key, and that is the refused append of ADR-02 and of State and scaling. - The session log, the snapshots, the pages, the numbered replicas of each page with their users (CRDT package) and the copy of the roles are all in the one server of Editing. The Log store and Database adapters of Hexagonal Architecture implement two different ports on the same database.
- Each service migrates its own schema when it starts, under a PostgreSQL advisory lock, so that two instances starting together never run the same migration twice. The Go services use goose, with the migrations embedded in the binary; Editing uses node-pg-migrate.
This settles the store of the log that ADR-02 left open.
Consequences. On the good side:
- One database engine to install, configure and back up for all the services, and a fresh install creates every schema with no manual step (QA-08).
- The primary key alone meets both requirements of ADR-02: a committed insert is durable, and a repeated
seqis refused by the database, not by the code of Editing. - The change of an aggregate, its outbox row and the record of an applied event commit in one transaction, as ADR-05 needs.
On the bad side:
- Every operation of a page waits for a commit before its ack: one write to the database on the path that QA-01 bounds, to be measured.
- Five PostgreSQL servers run on the reference node of 8 GB, next to Kafka and the services, so their memory must be sized to fit.
- The log grows with every operation, and needs the snapshots and the compaction that ADR-02 already lists.
- An instance that starts with a new migration runs it before it becomes ready, so a long migration delays its readiness.
- Each server is a single point of failure of its service. The reference deployment is a single node, so replicating the stores is out of scope.
Compliance.
- A test appends two operations with the same
seqto the log of a page: the second is refused. - The fresh install test of QA-08 starts from empty databases and runs no manual step on them.
- The SLI of QA-01 is measured with the append on PostgreSQL.
ADR-07: Each runtime has its own microservice chassis, assembled from libraries
Status: Proposed.
Context. ADR-04 puts four services on Go and Editing on Node.js, and records among its bad sides that the skeleton of a service exists twice. Next to its domain, every service needs the same cross-cutting concerns: the health checks and the metrics of Observability, its configuration in each environment, the timeout, retry and circuit breaker of Dependencies at run time, the keyed publication and the idempotent consumers of Contracts, the outbox of ADR-05, the REST APIs of the OpenAPI specifications, the access to the data, the migrations of ADR-06 and the logs. The API gateway needs most of them too. Some concerns are already covered by the platform: Kubernetes finds a service by the DNS name of its Service, injects the configuration of a ConfigMap or a Secret as environment variables, which Compose sets the same way, and polls the health checks. The alternatives were:
- a framework for Go: go-kit, go-micro, or one that generates the code of a service, such as go-zero or Kratos;
- NestJS for Editing;
- Dapr, a sidecar that offers the same building blocks to both runtimes;
- one chassis per runtime, assembled from libraries that each cover one concern.
The last release of go-kit is v0.13.0, of August 2023, and its last commit is of March 2024; its packages for service discovery and tracing cover what Kubernetes already does or what the prototype leaves out. go-micro has a registry and a broker of its own, which overlap with Kubernetes and Kafka; its Kafka broker is in a separate repository of plugins and does not set the key of a message, which the order of the events of an aggregate needs. go-zero and Kratos impose a folder structure of their own on the code they generate. The Kafka transport of NestJS is built on KafkaJS, whose last release is of February 2023, and a NestJS application is built around its decorators. Dapr gives both runtimes one sidecar, but adds a control plane and a sidecar for every service to the deployment, in Kubernetes and in Compose.
Decision. Each runtime will have a thin chassis of its own, assembled from libraries:
- One shared Go module is the chassis of the API gateway and of Account, Membership, Discussion and Notification, on Go 1.25 or later. Fastify with its plugins is the chassis of Editing.
- Each concern is covered by these libraries:
| Concern | Go services and API gateway | Editing |
|---|---|---|
| HTTP server, REST APIs from the OpenAPI contracts | net/http, with the strict server of oapi-codegen |
fastify |
| WebSocket | The gateway forwards it with net/http/httputil.ReverseProxy |
@fastify/websocket |
| Kafka: keyed publisher, router of the consumers | ThreeDotsLabs/watermill with watermill-kafka |
@confluentinc/kafka-javascript |
| Transactional Outbox and Polling Publisher (ADR-05) | watermill-sql, with its standard PostgreSQL schema, and the Forwarder of Watermill |
None: Editing publishes directly |
| PostgreSQL driver and data access | jackc/pgx/v5, with the code generated by sqlc |
pg |
| Migrations (ADR-06) | pressly/goose |
node-pg-migrate |
| Metrics | prometheus/client_golang |
fastify-metrics, on prom-client |
| Timeout, retry, circuit breaker | context of the standard library, sony/gobreaker/v2 |
opossum |
| Types of the messages (ADR-08) | go-jsonschema |
json-schema-to-typescript, openapi-typescript |
| Logs | log/slog of the standard library, JSON on the standard output |
pino, part of Fastify |
| Health checks, configuration | Two handlers, environment variables read with os.Getenv |
Two routes, environment variables |
- The libraries appear only in
mainand in the adapters of Hexagonal Architecture, never in the domain model or in the application services. - No OpenTelemetry: distributed tracing is left out of the prototype (Observability), and Prometheus scrapes the metrics of each service directly.
Watermill realizes the outbox of ADR-05 as follows:
- The change of the aggregate, the outbox row and the record of an applied event share one
pgx.Tx, which the SQL publisher of Watermill writes into throughTxFromPgx. - The PostgreSQL schema orders the rows by the identifier of the transaction that wrote them (
xid8), and reads a row only once every transaction with a lower identifier has ended, so no row is passed while an earlier transaction is still open. The transactions of one aggregate are serialized, and each one locks its aggregate before any other write, so its events keep their order. - The row of the consumer group in the offsets table is locked with
FOR UPDATE, so only one replica at a time reads and publishes the pending rows: the lock between publishers of ADR-05. - Marked as sent is the offset committed for that consumer group: every row up to it has been sent.
- The standard schema keeps the sent rows, and a small periodic task of ours deletes the old ones.
- The
PollIntervalof the Forwarder is set well within the 5 s (p99) of QA-06. - The Kafka key of each event is the identity of its aggregate, set through
NewWithPartitioningMarshaler. - The consumers deduplicate on the identifier in the envelope of Contracts, never on the
UUIDof a Watermill message, which is empty for the events published by Editing. - The Go producer is synchronous, so the Forwarder confirms a row only after Kafka acknowledges it.
This narrows the skeleton that ADR-04 records twice to one thin chassis per runtime.
Consequences. On the good side:
- Two thin chassis, each a set of libraries that cover one concern each, while discovery, configuration and probes stay with the platform.
- The outbox of ADR-05 is not written by hand: the order, the lock between replicas and the offset of what is sent come from
watermill-sql. - The contracts generate code: the REST servers from OpenAPI, the access to the data from SQL, the types of the messages from JSON Schema.
On the bad side:
- More dependencies to keep up to date. Renovate finds them in
go.modandpackage.json. - The
Messagetype of Watermill must stay inside the adapters. - The Kafka client of Confluent for Node.js is a native binding, so the image of Editing is built from an official Node.js image.
- Every Go module needs Go 1.25 or later.
- The cleanup of the outbox and its metrics, the pending rows and the age of the oldest one promised in Observability, stay our code, which reads the tables of Watermill.
Compliance.
- A fitness function in the CI forbids importing these libraries from the domain and application packages: the depguard rules of golangci-lint for Go, dependency-cruiser for TypeScript.
- The Compliance tests of ADR-05 run against the publisher built on Watermill.
- A test checks that the Kafka key of every event is the identity of its aggregate.
ADR-08: Contracts are JSON Schema, with no schema registry
Status: Accepted.
Context. Contracts gives each contract a specification kept with its service, OpenAPI for the REST APIs and AsyncAPI for the events, and makes the schema of each message the source of the types of both languages. ADR-04 leaves the format of those schemas to choose: the events of Editing are produced in TypeScript and consumed in Go, and the reverse. It is also open whether a schema registry checks a new version before it is published. The alternatives were:
- JSON Schema, with JSON on the wire;
- Avro;
- Protocol Buffers.
Avro messages are binary, and are usually read through a schema registry, one more component to deploy. Protocol Buffers are binary too, with solid type generation in both languages, but they are less natural to describe in AsyncAPI, whose schemas are JSON Schema, as those of OpenAPI 3.1 are.
Decision. We will write the contracts in JSON Schema:
- The payload of every event and query is a JSON Schema, inside the AsyncAPI specification of the events and the OpenAPI 3.1 specification of the REST APIs. The messages travel as JSON on Kafka and over HTTP, events in the envelope of Contracts.
- Go generates its types with
go-jsonschemaand TypeScript withjson-schema-to-typescript; Editing generates the types of its calls to Membership withopenapi-typescript. The generated code is never edited by hand. - No schema registry. Every producer and consumer of an event lives in this repository, so the pipeline of a change sees the schema and all its consumers. The consumer-driven contract tests of Contracts, in the pipeline of each producer, refuse an incompatible version before it goes to production; a registry would refuse it only once a running producer publishes it.
This settles the format left open by ADR-04.
Consequences. On the good side:
- A message can be read as it is, in a Kafka tool or a log.
- One schema language for the REST APIs and the events, with generators in both languages.
- An incompatible schema is caught in the pull request, before a release.
- No registry to deploy (QA-08).
On the bad side:
- JSON messages are larger than binary ones.
- Without a registry, nothing at run time stops an incompatible message: only the tests in the pipeline do.
- The choice holds only while every consumer lives in this repository. A consumer outside it, such as a third-party integration, reopens it.
Compliance.
- The CI regenerates the types from the schemas and fails if they differ from the committed ones.
- The contract test of each event checks a producer in one language against a consumer in the other (ADR-04).
ADR-09: The sign-in token is a JWT signed with Ed25519, in an HttpOnly cookie
Status: Proposed.
Context. Sign in (US-01) gives the client a token, which the API gateway checks on every request without calling Account (Access Token, Patterns) and which carries only the identity of the user (ADR-03). The client sends it on its REST requests and on the WebSocket of each open page, both through the gateway. Still open were the format of the token, how it is signed, how long it lasts, how it travels and the library that handles it. The alternatives were:
- an opaque token, looked up in Account, or a token signed by Account that carries the identity itself (a JWT);
- for a signed token, a secret shared by Account and the gateway (HS256), or a key pair, RSA (RS256) or Ed25519 (EdDSA);
- the token in an
Authorizationheader, kept by the JavaScript of the client, or in anHttpOnlycookie; - a short access token renewed by a refresh token, or a single token that expires.
An opaque token puts Account on the path of every request. With a shared secret, whoever checks a token can also sign one, so the gateway could issue tokens; a key pair leaves signing to Account alone, and Ed25519 keys and signatures are much smaller than RSA ones. The WebSocket API of the browser cannot set a header, so the token would travel in the URL of the WebSocket, where the access logs of the Ingress and the gateway may record it, and a token kept by JavaScript can be read by any script injected into the page. A browser sends a cookie by itself, on the upgrade of a WebSocket too, and an HttpOnly cookie is out of reach of scripts. Being sent by itself, a cookie could ride on a request from another site, which SameSite prevents as long as the client and the API share one site, as the Ingress of Deployment already serves them. A refresh token needs an endpoint of its own, a store of the issued tokens and their rotation.
Decision. We will sign the identity of the user into a JWT with Ed25519 and carry it in a cookie:
- After a successful Sign in, the REST adapter of Account signs a JWT with
alg: EdDSAwhose claims are onlysub, theUserId,iatandexp, 8 hours later: no role (ADR-03) and no email address. The domain and the application services of Account do not know the token. - Account sets it in the cookie
__Host-gotion-token, withHttpOnly,Secure,SameSite=Strict,Path=/and aMax-Ageof 8 hours. - The gateway checks the cookie on every REST request but Register and Sign in, and on the upgrade of every WebSocket: the signature against the public key of Account,
EdDSAas the only algorithm accepted, andexp, which is required. A missing, invalid or expired token gets a 401, and the client shows the sign-in. The gateway also refuses the upgrade of a WebSocket whoseOriginis not the one of Gotion. - The gateway removes any
X-User-Idheader from the request of the client and sets it to thesubof the token. The services take the identity of the user only from that header: no client reaches them but through the gateway, since the Ingress routes only to the web client and to the gateway. - Only Account holds the private key, from a Secret; the gateway reads the public key from its configuration. The installation generates the key pair, which is never committed. The keys are not rotated.
- Both sides use
golang-jwt/jwt/v5withcrypto/ed25519, in atoken/package of the Go chassis (ADR-07) that only Account and the gateway import. Editing reads the header and has no JWT code. - No refresh token and no sign-out: US-01 asks for neither.
Consequences. On the good side:
- The gateway checks the identity of a request without calling Account, and a signed-in user still reaches the other services while Account is down.
- No script in the page can read the token, and one mechanism covers the REST requests and the WebSocket.
- Only Account can issue a token.
- Editing, on Node.js, needs no JWT library (ADR-04).
On the bad side:
- A token cannot be revoked before it expires: a stolen cookie works for up to 8 hours.
- An open WebSocket outlives the expiry of its token, which is checked only on the upgrade. The role is still checked on every edit (ADR-03), so a removed member stops editing anyway.
- The user signs in again every 8 hours.
- The client and the API must stay on one site. Serving them from different sites reopens this record.
- Changing the key pair signs every user out.
- The services trust
X-User-Id: whatever reaches a service without going through the gateway can act as any user. The choice holds only while the gateway is the one way in.
Compliance.
- The tests of
token/refuse a token signed with another algorithm,noneandHS256included, or with another key, and an expired token or one withoutexp. - A test of the gateway checks that an
X-User-Idsent by the client never reaches a service. - A test checks the attributes of the cookie in the response of Sign in.
- A test checks that the gateway refuses the upgrade of a WebSocket from a foreign
Origin.