Exercise 15 · Write and publish are not one transaction (dual write)
Transactional Outbox
- dual write
- Outbox
- relay
- Inbox + Outbox
Principle
The service writes the event to the event store and then publishes it to the broker. These are two operations on two systems and cannot be done atomically. In between, the service may crash or the broker may fail.
Result: the event is stored, but nobody learns about it and the process stalls.
Transactional Outbox: the event and a “to send” record are written in one transaction. A separate relay then delivers them to the broker and retries until it succeeds. Together with an Inbox at the receiver this gives effectively “exactly once”.
What to watch
- The “publish failed” effect and the “process stuck” state.
- With Outbox: rows waiting for the relay and their attempts.
- The “Rebuild projection” button shows that the event store had the truth.
Experiment
What to do: Click “Run with 70% publish loss”. What to look at: The event is stored, but the process never completes.
Publishing to the broker fails (70 %). Events are written to the event store, but some of them are never delivered.
The relay sends events from the outbox table until it succeeds. The process lags behind, but nothing is lost.
Step by step (newest on top)
Event Store: append-only history (newest on top)
Message Broker: delivery (newest on top)
Projection (current state)
The simulation needs JavaScript. Below is a recording of both runs.
Run with 70% publish loss
Publishing to the broker fails (70 %). Events are written to the event store, but some of them are never delivered.
0.0 sMortgage Calculator APIcould not publish to the broker
MortgageApplicationSubmittedintegrationpublishing to the broker failed
The event is stored, but nobody will learn about it: the process is stuck (dual write problem)
0.0 sMortgage Calculator APIappended to the event store
MortgageApplicationSubmittedintegrationEvent content
{ "applicationId": "calc-1", "referenceNumber": "KALK-calc-1-2", "loanAmount": 5200000, "monthlyPayment": 29590, "monthlyIncome": 85000, "termYears": 30, "ratePct": 5.49, "dti": 0.34811764705882353, "ltv": 0.8 }0.0 sMortgage Calculator APIappended to the event store
ApplicationSubmitteddomainEvent content
{ "calculationId": "calc-1", "referenceNumber": "KALK-calc-1-2", "inputs": { "monthlyIncome": 85000, "propertyPrice": 6500000, "downPaymentPct": 20, "ratePct": 5.49, "termYears": 30 }, "result": { "loan": 5200000, "monthlyPayment": 29590, "dti": 0.34811764705882353, "ltv": 0.8, "algorithm": "v1" } }0.0 sMortgage Calculator APIappended to the event store
CalculationCompleteddomainEvent content
{ "algorithm": "v1", "result": { "loan": 5200000, "monthlyPayment": 29590, "dti": 0.34811764705882353, "ltv": 0.8, "algorithm": "v1" }, "referenceNumber": "KALK-calc-1-2" }0.0 sMortgage Calculator APIappended to the event store
CalculationCreateddomainEvent content
{ "calculationId": "calc-1", "monthlyIncome": 85000, "propertyPrice": 6500000, "downPaymentPct": 20, "ratePct": 5.49, "termYears": 30 }
Run with Outbox
The relay sends events from the outbox table until it succeeds. The process lags behind, but nothing is lost.
24.38 sProjection (read model)processed
MortgageDisbursedintegration24.38 sProcess Manager (Saga)processed
MortgageDisbursedintegration24.1 sProcess Manager (Saga)picked up
MortgageDisbursedintegrationattempt 1
24.05 sProjection (read model)picked up
MortgageDisbursedintegrationattempt 1
23.68 sDisbursementsent from the Outbox
MortgageDisbursedintegrationsent on attempt 3
23.18 sDisbursementfailed while processing
MortgageDisbursedintegrationrelay: broker unavailable, attempt 2
22.68 sDisbursementfailed while processing
MortgageDisbursedintegrationrelay: broker unavailable, attempt 1
22.38 sDisbursementprocessed
MortgageDisbursementRequestedcommand22.38 sDisbursementstored in the Outbox
MortgageDisbursedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "amount": 5200000, "accountNumber": "0800-100017/0800" }22.0 sProjection (read model)processed
MortgageDisbursementRequestedcommand21.7 sDisbursementpicked up
MortgageDisbursementRequestedcommandattempt 1
21.68 sProjection (read model)picked up
MortgageDisbursementRequestedcommandattempt 1
21.28 sProcess Manager (Saga)sent from the Outbox
MortgageDisbursementRequestedcommandsent on attempt 2
20.78 sProcess Manager (Saga)failed while processing
MortgageDisbursementRequestedcommandrelay: broker unavailable, attempt 1
20.48 sProcess Manager (Saga)processed
ContractSignedintegration20.48 sProcess Manager (Saga)stored in the Outbox
MortgageDisbursementRequestedcommandfor: DisbursementProjection (read model)
Event content
{ "applicationId": "calc-1", "amount": 5200000, "accountNumber": "0800-100017/0800", "customerId": "CUST-0001" }20.4 sProjection (read model)processed
ContractSignedintegration20.15 sProcess Manager (Saga)picked up
ContractSignedintegrationattempt 1
20.08 sProjection (read model)picked up
ContractSignedintegrationattempt 1
19.78 sDocument Servicesent from the Outbox
ContractSignedintegrationsent on attempt 3
19.55 sProcess Manager (Saga)processed
ContractGeneratedintegration19.38 sProjection (read model)processed
ContractGeneratedintegration19.28 sDocument Servicefailed while processing
ContractSignedintegrationrelay: broker unavailable, attempt 2
19.18 sProcess Manager (Saga)picked up
ContractGeneratedintegrationattempt 1
19.03 sProjection (read model)picked up
ContractGeneratedintegrationattempt 1
18.78 sDocument Servicefailed while processing
ContractSignedintegrationrelay: broker unavailable, attempt 1
18.75 sDocument Servicesent from the Outbox
ContractGeneratedintegrationsent on attempt 4
18.48 sDocument Servicestored in the Outbox
ContractSignedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "contractId": "SML-0001", "signedBy": "klient" }18.25 sDocument Servicefailed while processing
ContractGeneratedintegrationrelay: broker unavailable, attempt 3
17.75 sDocument Servicefailed while processing
ContractGeneratedintegrationrelay: broker unavailable, attempt 2
17.25 sDocument Servicefailed while processing
ContractGeneratedintegrationrelay: broker unavailable, attempt 1
16.95 sDocument Serviceprocessed
ContractGenerationRequestedcommand16.95 sDocument Servicestored in the Outbox
ContractGeneratedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "contractId": "SML-0001" }16.58 sProjection (read model)processed
ContractGenerationRequestedcommand16.28 sDocument Servicepicked up
ContractGenerationRequestedcommandattempt 1
16.25 sProjection (read model)picked up
ContractGenerationRequestedcommandattempt 1
15.83 sProcess Manager (Saga)sent from the Outbox
ContractGenerationRequestedcommandsent on attempt 1
15.55 sProjection (read model)processed
MortgageAccountOpenedintegration15.53 sProcess Manager (Saga)processed
MortgageAccountOpenedintegration15.53 sProcess Manager (Saga)stored in the Outbox
ContractGenerationRequestedcommandfor: Document ServiceProjection (read model)
Event content
{ "applicationId": "calc-1", "amount": 5200000, "accountNumber": "0800-100017/0800", "customerId": "CUST-0001" }15.25 sProcess Manager (Saga)picked up
MortgageAccountOpenedintegrationattempt 1
15.23 sProjection (read model)picked up
MortgageAccountOpenedintegrationattempt 1
14.8 sMortgage Accountsent from the Outbox
MortgageAccountOpenedintegrationsent on attempt 2
14.3 sMortgage Accountfailed while processing
MortgageAccountOpenedintegrationrelay: broker unavailable, attempt 1
14.0 sMortgage Accountprocessed
MortgageAccountOpeningRequestedcommand14.0 sMortgage Accountstored in the Outbox
MortgageAccountOpenedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "accountNumber": "0800-100017/0800" }13.5 sProjection (read model)processed
MortgageAccountOpeningRequestedcommand13.28 sMortgage Accountpicked up
MortgageAccountOpeningRequestedcommandattempt 1
13.18 sProjection (read model)picked up
MortgageAccountOpeningRequestedcommandattempt 1
12.88 sProcess Manager (Saga)sent from the Outbox
MortgageAccountOpeningRequestedcommandsent on attempt 1
12.73 sProjection (read model)processed
CustomerIdentityCreatedintegration12.58 sProcess Manager (Saga)processed
CustomerIdentityCreatedintegration12.58 sProcess Manager (Saga)stored in the Outbox
MortgageAccountOpeningRequestedcommandfor: Mortgage AccountProjection (read model)
Event content
{ "applicationId": "calc-1", "amount": 5200000, "customerId": "CUST-0001" }12.38 sProjection (read model)picked up
CustomerIdentityCreatedintegrationattempt 1
12.33 sProcess Manager (Saga)picked up
CustomerIdentityCreatedintegrationattempt 1
12.0 sCustomer Identitysent from the Outbox
CustomerIdentityCreatedintegrationsent on attempt 3
11.5 sCustomer Identityfailed while processing
CustomerIdentityCreatedintegrationrelay: broker unavailable, attempt 2
11.0 sCustomer Identityfailed while processing
CustomerIdentityCreatedintegrationrelay: broker unavailable, attempt 1
10.7 sCustomer Identityprocessed
CustomerIdentityCreationRequestedcommand10.7 sCustomer Identitystored in the Outbox
CustomerIdentityCreatedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "customerId": "CUST-0001" }10.38 sProjection (read model)processed
CustomerIdentityCreationRequestedcommand10.03 sProjection (read model)picked up
CustomerIdentityCreationRequestedcommandattempt 1
10.03 sCustomer Identitypicked up
CustomerIdentityCreationRequestedcommandattempt 1
9.68 sProcess Manager (Saga)sent from the Outbox
CustomerIdentityCreationRequestedcommandsent on attempt 6
9.18 sProcess Manager (Saga)failed while processing
CustomerIdentityCreationRequestedcommandrelay: broker unavailable, attempt 5
8.68 sProcess Manager (Saga)failed while processing
CustomerIdentityCreationRequestedcommandrelay: broker unavailable, attempt 4
8.18 sProcess Manager (Saga)failed while processing
CustomerIdentityCreationRequestedcommandrelay: broker unavailable, attempt 3
7.68 sProcess Manager (Saga)failed while processing
CustomerIdentityCreationRequestedcommandrelay: broker unavailable, attempt 2
7.18 sProcess Manager (Saga)failed while processing
CustomerIdentityCreationRequestedcommandrelay: broker unavailable, attempt 1
6.95 sProjection (read model)processed
MortgageApprovedintegration6.88 sProcess Manager (Saga)processed
MortgageApprovedintegration6.88 sProcess Manager (Saga)stored in the Outbox
CustomerIdentityCreationRequestedcommandfor: Customer IdentityProjection (read model)
Event content
{ "applicationId": "calc-1", "amount": 5200000 }6.58 sProjection (read model)picked up
MortgageApprovedintegrationattempt 1
6.55 sProcess Manager (Saga)picked up
MortgageApprovedintegrationattempt 1
6.18 sApproval / Controllingsent from the Outbox
MortgageApprovedintegrationsent on attempt 2
5.68 sApproval / Controllingfailed while processing
MortgageApprovedintegrationrelay: broker unavailable, attempt 1
5.38 sApproval / Controllingprocessed
RiskAssessmentCompletedintegration5.38 sApproval / Controllingstored in the Outbox
MortgageApprovedintegrationfor: Process Manager (Saga)Projection (read model)
Event content
{ "approvedAmount": 5200000, "score": 800 }5.05 sProjection (read model)processed
RiskAssessmentCompletedintegration4.83 sApproval / Controllingpicked up
RiskAssessmentCompletedintegrationattempt 1
4.8 sProjection (read model)picked up
RiskAssessmentCompletedintegrationattempt 1
4.5 sRisk Servicesent from the Outbox
RiskAssessmentCompletedintegrationsent on attempt 5
4.0 sRisk Servicefailed while processing
RiskAssessmentCompletedintegrationrelay: broker unavailable, attempt 4
3.5 sRisk Servicefailed while processing
RiskAssessmentCompletedintegrationrelay: broker unavailable, attempt 3
3.0 sRisk Servicefailed while processing
RiskAssessmentCompletedintegrationrelay: broker unavailable, attempt 2
2.5 sRisk Servicefailed while processing
RiskAssessmentCompletedintegrationrelay: broker unavailable, attempt 1
2.2 sRisk Serviceprocessed
MortgageApplicationSubmittedintegration2.2 sRisk Servicestored in the Outbox
RiskAssessmentCompletedintegrationfor: Approval / ControllingProjection (read model)
Event content
{ "score": 800, "loanAmount": 5200000, "monthlyIncome": 85000, "dti": 0.34811764705882353, "ltv": 0.8 }1.98 sProjection (read model)processed
MortgageApplicationSubmittedintegration1.93 sProcess Manager (Saga)processed
MortgageApplicationSubmittedintegration1.7 sRisk Servicepicked up
MortgageApplicationSubmittedintegrationattempt 1
1.65 sProcess Manager (Saga)picked up
MortgageApplicationSubmittedintegrationattempt 1
1.63 sProjection (read model)picked up
MortgageApplicationSubmittedintegrationattempt 1
1.3 sMortgage Calculator APIsent from the Outbox
MortgageApplicationSubmittedintegrationsent on attempt 3
0.8 sMortgage Calculator APIfailed while processing
MortgageApplicationSubmittedintegrationrelay: broker unavailable, attempt 2
0.3 sMortgage Calculator APIfailed while processing
MortgageApplicationSubmittedintegrationrelay: broker unavailable, attempt 1
0.0 sMortgage Calculator APIstored in the Outbox
MortgageApplicationSubmittedintegrationfor: Risk ServiceProcess Manager (Saga)Projection (read model)
Event content
{ "applicationId": "calc-1", "referenceNumber": "KALK-calc-1-2", "loanAmount": 5200000, "monthlyPayment": 29590, "monthlyIncome": 85000, "termYears": 30, "ratePct": 5.49, "dti": 0.34811764705882353, "ltv": 0.8 }0.0 sMortgage Calculator APIappended to the event store
ApplicationSubmitteddomainEvent content
{ "calculationId": "calc-1", "referenceNumber": "KALK-calc-1-2", "inputs": { "monthlyIncome": 85000, "propertyPrice": 6500000, "downPaymentPct": 20, "ratePct": 5.49, "termYears": 30 }, "result": { "loan": 5200000, "monthlyPayment": 29590, "dti": 0.34811764705882353, "ltv": 0.8, "algorithm": "v1" } }0.0 sMortgage Calculator APIappended to the event store
CalculationCompleteddomainEvent content
{ "algorithm": "v1", "result": { "loan": 5200000, "monthlyPayment": 29590, "dti": 0.34811764705882353, "ltv": 0.8, "algorithm": "v1" }, "referenceNumber": "KALK-calc-1-2" }0.0 sMortgage Calculator APIappended to the event store
CalculationCreateddomainEvent content
{ "calculationId": "calc-1", "monthlyIncome": 85000, "propertyPrice": 6500000, "downPaymentPct": 20, "ratePct": 5.49, "termYears": 30 }
What happens in the simulator
A summary of the same scenario you run in the lab. The individual steps are shown with the runs above.
4 events · 0.3 s of simulated time
Cause → effect
- Publishing MortgageApplicationSubmitted to the broker failed after writing to the event store → The event is stored, but nobody will learn about it: the process is stuck (dual write problem) MortgageApplicationSubmitted
15 events · 24.4 s of simulated time
Try it in your own project
Copy the prompt into your coding agent (Claude Code, Copilot, Codex…) and run it in your project's repository.
Replace direct publishing after a write with a transactional Outbox and a relay process.
# Task for a coding agent: Transactional Outbox Stack: Java. Mode: guided. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (Java backend (typically Java 21, Spring Boot, JPA or JDBC). Use the build tool and style the project already has (Maven/Gradle, JUnit 5).). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Specific task Technical specifics (Java): `@Transactional` write, relay as `@Scheduled` or Debezium CDC, if the organisation has it. Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation: 1. Plan: the outbox table schema (id, type, topic, payload, headers, aggregate_key, position, created_at, sent_at, attempts, next_attempt_at, locked_until) and where it lives when the state is in another service. 2. Write the state and the outbox row in one transaction; a producer without its own write writes only the outbox row. 3. Relay (background worker) after a write and on a timer: loads unsent rows, sends them in order, marks them; failure = `attempts + 1` and the next attempt after backoff. 4. Subscribers are idempotent (Inbox, unique business key, idempotency key), the relay delivers “at least once”; where this does not hold, state it in the conclusion. 5. Test through a faulty broker: (a) broker down → after recovery all messages in order; (b) crash between write and publish; (c) lost acknowledgement → duplicate, effect once. Control: without the outbox, (b) fails. Watch out for: - Multiple relay instances: `SKIP LOCKED` only on the aggregate's first unsent row and a lock with a lease, otherwise the second instance overtakes the first; or a single instance. - A message the broker permanently rejects blocks its aggregate: alarm on outbox age. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - JUnit 5 tests in the existing `src/test/java` structure pass with the project's build tool. - In the summary, state: what you changed, what you assumed, what remains.
# Task for a coding agent: Transactional Outbox Stack: Java. Mode: challenge. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (Java backend (typically Java 21, Spring Boot, JPA or JDBC). Use the build tool and style the project already has (Maven/Gradle, JUnit 5).). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Brief (Challenge) Guarantee that every stored event is sooner or later published, even if the broker or the service fails in the meantime. Technical specifics (Java): `@Transactional` write, relay as `@Scheduled` or Debezium CDC, if the organisation has it. Choose your own approach. The pitfalls in this topic are not listed: find them (concurrency, redelivery, ordering, failure midway) and for each write a test that would expose it. At the end, list which pitfalls you found and which you deliberately left open. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - JUnit 5 tests in the existing `src/test/java` structure pass with the project's build tool. - In the summary, state: what you changed, what you assumed, what remains.
# Task for a coding agent: Transactional Outbox Stack: C#. Mode: guided. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (C# backend (.NET, ASP.NET Core, EF Core or Dapper). Use the solution, style and DI conventions the project already has (xUnit/NUnit).). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Specific task Technical specifics (C#): `DbContext` transaction, relay as a `BackgroundService`; first check the outbox in the project's messaging library. Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation: 1. Plan: the outbox table schema (id, type, topic, payload, headers, aggregate_key, position, created_at, sent_at, attempts, next_attempt_at, locked_until) and where it lives when the state is in another service. 2. Write the state and the outbox row in one transaction; a producer without its own write writes only the outbox row. 3. Relay (background worker) after a write and on a timer: loads unsent rows, sends them in order, marks them; failure = `attempts + 1` and the next attempt after backoff. 4. Subscribers are idempotent (Inbox, unique business key, idempotency key), the relay delivers “at least once”; where this does not hold, state it in the conclusion. 5. Test through a faulty broker: (a) broker down → after recovery all messages in order; (b) crash between write and publish; (c) lost acknowledgement → duplicate, effect once. Control: without the outbox, (b) fails. Watch out for: - Multiple relay instances: `SKIP LOCKED` only on the aggregate's first unsent row and a lock with a lease, otherwise the second instance overtakes the first; or a single instance. - A message the broker permanently rejects blocks its aggregate: alarm on outbox age. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - Tests in the existing test project pass (`dotnet test`). - In the summary, state: what you changed, what you assumed, what remains.
# Task for a coding agent: Transactional Outbox Stack: C#. Mode: challenge. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (C# backend (.NET, ASP.NET Core, EF Core or Dapper). Use the solution, style and DI conventions the project already has (xUnit/NUnit).). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Brief (Challenge) Guarantee that every stored event is sooner or later published, even if the broker or the service fails in the meantime. Technical specifics (C#): `DbContext` transaction, relay as a `BackgroundService`; first check the outbox in the project's messaging library. Choose your own approach. The pitfalls in this topic are not listed: find them (concurrency, redelivery, ordering, failure midway) and for each write a test that would expose it. At the end, list which pitfalls you found and which you deliberately left open. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - Tests in the existing test project pass (`dotnet test`). - In the summary, state: what you changed, what you assumed, what remains.
# Task for a coding agent: Transactional Outbox Stack: Web (HTML/JS or the app's stack). Mode: guided. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (web application: a browser frontend, possibly with its own backend. If the project has a backend, the event store, broker and services belong on the backend, and the points about endpoints and tables refer to it. If it has no backend, use IndexedDB in the browser and `fake-indexeddb` in tests. Keep the project's framework and test runner; add new dependencies only with a justification.). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Specific task Technical specifics (Web (HTML/JS or the app's stack)): Outbox on the backend; in the frontend, optionally store in an IndexedDB “outbox” only safely repeatable commands (same `X-Correlation-Id`) and send them on `online`. Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation: 1. Plan: the outbox table schema (id, type, topic, payload, headers, aggregate_key, position, created_at, sent_at, attempts, next_attempt_at, locked_until) and where it lives when the state is in another service. 2. Write the state and the outbox row in one transaction; a producer without its own write writes only the outbox row. 3. Relay (background worker) after a write and on a timer: loads unsent rows, sends them in order, marks them; failure = `attempts + 1` and the next attempt after backoff. 4. Subscribers are idempotent (Inbox, unique business key, idempotency key), the relay delivers “at least once”; where this does not hold, state it in the conclusion. 5. Test through a faulty broker: (a) broker down → after recovery all messages in order; (b) crash between write and publish; (c) lost acknowledgement → duplicate, effect once. Control: without the outbox, (b) fails. Watch out for: - Multiple relay instances: `SKIP LOCKED` only on the aggregate's first unsent row and a lock with a lease, otherwise the second instance overtakes the first; or a single instance. - A message the broker permanently rejects blocks its aggregate: alarm on outbox age. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - Tests pass with the existing test runner; lint and build pass if the project has them. - In the summary, state: what you changed, what you assumed, what remains.
# Task for a coding agent: Transactional Outbox Stack: Web (HTML/JS or the app's stack). Mode: challenge. Goal: Replace direct publishing after a write with a transactional Outbox and a relay process. ## Context of the existing code You are working in an existing project (web application: a browser frontend, possibly with its own backend. If the project has a backend, the event store, broker and services belong on the backend, and the points about endpoints and tables refer to it. If it has no backend, use IndexedDB in the browser and `fake-indexeddb` in tests. Keep the project's framework and test runner; add new dependencies only with a justification.). Domain: a mortgage calculator that is gradually turning into an event-driven system (calculator, risk, approval, identity, account, documents, payout). Prerequisite: the project has a broker and producers that publish after a write. If not, first set up a minimal producer: a state write and `publish` to an in-memory broker. Read first, change nothing. Find and briefly summarise: - Every place where `publish`/`send` is called after `save` (dual write), consumers included, and for each one where the state is written (same database, another service, none). - Whether the project's broker library already offers an Outbox (an event store with a relay from the feed already is an outbox). - The transaction boundary (one DB transaction). - Which of these parts already exist in the project and which are missing. Before writing your own infrastructure (outbox, relay), check whether the project or organisation already has it as a ready-made library, and use it. If it is missing, propose it in the plan. ## Expected behaviour Writing state and publishing are two operations on two systems: if the service or broker fails between them, the state is stored but nobody learns about it and the process stalls. The Outbox writes a “to send” row in the same transaction as the state and the relay delivers it until it succeeds. It delivers “at least once”; with an Inbox at the receiver you get effectively “exactly once”. Example: the broker rejects 70 % of publishes; the process lags behind, but nothing is lost. ## Brief (Challenge) Guarantee that every stored event is sooner or later published, even if the broker or the service fails in the meantime. Technical specifics (Web (HTML/JS or the app's stack)): Outbox on the backend; in the frontend, optionally store in an IndexedDB “outbox” only safely repeatable commands (same `X-Correlation-Id`) and send them on `online`. Choose your own approach. The pitfalls in this topic are not listed: find them (concurrency, redelivery, ordering, failure midway) and for each write a test that would expose it. At the end, list which pitfalls you found and which you deliberately left open. ## What you must not change - The existing public API and the behaviour of the calculator endpoints that currently work. - The database schema of existing tables (new tables/migrations are fine; renaming and deleting are not). - Other people's tests, seed data and existing values. If a change is necessary, put it in a separate commit and state it. If a change to an event's shape or a new consumer necessarily changes an existing test, update it in a separate commit and explain why in the summary. - Public contracts (APIs, event schemas) without backward compatibility. ## Done when - Broker outage tests (a) to (c) and the control without the outbox. - Writing the state and the outbox is atomic (test with an error inside the transaction). - Relay in multiple instances without double publishing and with per-aggregate order (test), or a documented single instance. - Tests pass with the existing test runner; lint and build pass if the project has them. - In the summary, state: what you changed, what you assumed, what remains.
Related parts of the presentation
Training for your team
Would you like this training for your team?
We run the training on your code and your domain problem. We agree the scope, dates and format with you.
Discuss the training