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).

Context map of Gotion

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.

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:

  1. 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.
  2. 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.
  3. 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).

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.

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.

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).

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:

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:

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.

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.

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).

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).

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:

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).

Components and connectors of Gotion

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).

Event-based view of Gotion

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).

Data-flow view of one edit operation

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.

Repository view of Gotion

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.

Hexagonal architecture of each service

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:

Why not smaller services. A further split would put a network call inside a rule that one service now keeps on its own:

Why not fewer services. Two merges were worth weighing:

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:

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:

  1. asks Membership for the WorkspaceId and role of each workspace the user belongs to;
  2. asks Account for the names of those workspaces in one batch, and for the user’s main workspace;
  3. joins the answers by WorkspaceId and 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.

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

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:

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 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:

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:

On the bad side, each to be settled before or while Editing is built:

Compliance.

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:

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:

Consequences. On the good side:

On the bad side:

Compliance.

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:

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:

This settles PP-04.

Consequences. On the good side:

On the bad side:

Compliance.

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:

This settles the runtimes left open by ADR-01.

Consequences. On the good side:

On the bad side:

Compliance.

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:

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:

Consequences. On the good side:

On the bad side:

Compliance.

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:

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:

This settles the store of the log that ADR-02 left open.

Consequences. On the good side:

On the bad side:

Compliance.

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:

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:

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

Watermill realizes the outbox of ADR-05 as follows:

This narrows the skeleton that ADR-04 records twice to one thin chassis per runtime.

Consequences. On the good side:

On the bad side:

Compliance.

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:

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:

This settles the format left open by ADR-04.

Consequences. On the good side:

On the bad side:

Compliance.

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 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:

Consequences. On the good side:

On the bad side:

Compliance.