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.

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.

How the run unfolds (newest on top)

  1. 0.0 sMortgage Calculator APIcould not publish to the brokerMortgageApplicationSubmittedintegration

    publishing to the broker failed

    The event is stored, but nobody will learn about it: the process is stuck (dual write problem)

  2. 0.0 sMortgage Calculator APIappended to the event storeMortgageApplicationSubmittedintegration

    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
    }

    evt-0004 · correlationId calc-1 · causationId evt-0003

  3. 0.0 sMortgage Calculator APIappended to the event storeApplicationSubmitteddomain

    Event 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"
      }
    }

    evt-0003 · correlationId calc-1

  4. 0.0 sMortgage Calculator APIappended to the event storeCalculationCompleteddomain

    Event content
    {
      "algorithm": "v1",
      "result": {
        "loan": 5200000,
        "monthlyPayment": 29590,
        "dti": 0.34811764705882353,
        "ltv": 0.8,
        "algorithm": "v1"
      },
      "referenceNumber": "KALK-calc-1-2"
    }

    evt-0002 · correlationId calc-1

  5. 0.0 sMortgage Calculator APIappended to the event storeCalculationCreateddomain

    Event content
    {
      "calculationId": "calc-1",
      "monthlyIncome": 85000,
      "propertyPrice": 6500000,
      "downPaymentPct": 20,
      "ratePct": 5.49,
      "termYears": 30
    }

    evt-0001 · correlationId calc-1

Run with Outbox

The relay sends events from the outbox table until it succeeds. The process lags behind, but nothing is lost.

How the run unfolds (newest on top)

  1. 24.38 sProjection (read model)processedMortgageDisbursedintegration

  2. 24.38 sProcess Manager (Saga)processedMortgageDisbursedintegration

  3. 24.1 sProcess Manager (Saga)picked upMortgageDisbursedintegration

    attempt 1

  4. 24.05 sProjection (read model)picked upMortgageDisbursedintegration

    attempt 1

  5. 23.68 sDisbursementsent from the OutboxMortgageDisbursedintegration

    sent on attempt 3

  6. 23.18 sDisbursementfailed while processingMortgageDisbursedintegration

    relay: broker unavailable, attempt 2

  7. 22.68 sDisbursementfailed while processingMortgageDisbursedintegration

    relay: broker unavailable, attempt 1

  8. 22.38 sDisbursementprocessedMortgageDisbursementRequestedcommand

  9. 22.38 sDisbursementstored in the OutboxMortgageDisbursedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "amount": 5200000,
      "accountNumber": "0800-100017/0800"
    }

    evt-0049 · correlationId calc-1 · causationId evt-0045

  10. 22.0 sProjection (read model)processedMortgageDisbursementRequestedcommand

  11. 21.7 sDisbursementpicked upMortgageDisbursementRequestedcommand

    attempt 1

  12. 21.68 sProjection (read model)picked upMortgageDisbursementRequestedcommand

    attempt 1

  13. 21.28 sProcess Manager (Saga)sent from the OutboxMortgageDisbursementRequestedcommand

    sent on attempt 2

  14. 20.78 sProcess Manager (Saga)failed while processingMortgageDisbursementRequestedcommand

    relay: broker unavailable, attempt 1

  15. 20.48 sProcess Manager (Saga)processedContractSignedintegration

  16. 20.48 sProcess Manager (Saga)stored in the OutboxMortgageDisbursementRequestedcommand

    for: DisbursementProjection (read model)

    Event content
    {
      "applicationId": "calc-1",
      "amount": 5200000,
      "accountNumber": "0800-100017/0800",
      "customerId": "CUST-0001"
    }

    evt-0045 · correlationId calc-1 · causationId evt-0039

  17. 20.4 sProjection (read model)processedContractSignedintegration

  18. 20.15 sProcess Manager (Saga)picked upContractSignedintegration

    attempt 1

  19. 20.08 sProjection (read model)picked upContractSignedintegration

    attempt 1

  20. 19.78 sDocument Servicesent from the OutboxContractSignedintegration

    sent on attempt 3

  21. 19.55 sProcess Manager (Saga)processedContractGeneratedintegration

  22. 19.38 sProjection (read model)processedContractGeneratedintegration

  23. 19.28 sDocument Servicefailed while processingContractSignedintegration

    relay: broker unavailable, attempt 2

  24. 19.18 sProcess Manager (Saga)picked upContractGeneratedintegration

    attempt 1

  25. 19.03 sProjection (read model)picked upContractGeneratedintegration

    attempt 1

  26. 18.78 sDocument Servicefailed while processingContractSignedintegration

    relay: broker unavailable, attempt 1

  27. 18.75 sDocument Servicesent from the OutboxContractGeneratedintegration

    sent on attempt 4

  28. 18.48 sDocument Servicestored in the OutboxContractSignedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "contractId": "SML-0001",
      "signedBy": "klient"
    }

    evt-0039 · correlationId calc-1 · causationId evt-0037

  29. 18.25 sDocument Servicefailed while processingContractGeneratedintegration

    relay: broker unavailable, attempt 3

  30. 17.75 sDocument Servicefailed while processingContractGeneratedintegration

    relay: broker unavailable, attempt 2

  31. 17.25 sDocument Servicefailed while processingContractGeneratedintegration

    relay: broker unavailable, attempt 1

  32. 16.95 sDocument ServiceprocessedContractGenerationRequestedcommand

  33. 16.95 sDocument Servicestored in the OutboxContractGeneratedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "contractId": "SML-0001"
    }

    evt-0037 · correlationId calc-1 · causationId evt-0033

  34. 16.58 sProjection (read model)processedContractGenerationRequestedcommand

  35. 16.28 sDocument Servicepicked upContractGenerationRequestedcommand

    attempt 1

  36. 16.25 sProjection (read model)picked upContractGenerationRequestedcommand

    attempt 1

  37. 15.83 sProcess Manager (Saga)sent from the OutboxContractGenerationRequestedcommand

    sent on attempt 1

  38. 15.55 sProjection (read model)processedMortgageAccountOpenedintegration

  39. 15.53 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  40. 15.53 sProcess Manager (Saga)stored in the OutboxContractGenerationRequestedcommand

    for: Document ServiceProjection (read model)

    Event content
    {
      "applicationId": "calc-1",
      "amount": 5200000,
      "accountNumber": "0800-100017/0800",
      "customerId": "CUST-0001"
    }

    evt-0033 · correlationId calc-1 · causationId evt-0029

  41. 15.25 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  42. 15.23 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  43. 14.8 sMortgage Accountsent from the OutboxMortgageAccountOpenedintegration

    sent on attempt 2

  44. 14.3 sMortgage Accountfailed while processingMortgageAccountOpenedintegration

    relay: broker unavailable, attempt 1

  45. 14.0 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  46. 14.0 sMortgage Accountstored in the OutboxMortgageAccountOpenedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "accountNumber": "0800-100017/0800"
    }

    evt-0029 · correlationId calc-1 · causationId evt-0025

  47. 13.5 sProjection (read model)processedMortgageAccountOpeningRequestedcommand

  48. 13.28 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  49. 13.18 sProjection (read model)picked upMortgageAccountOpeningRequestedcommand

    attempt 1

  50. 12.88 sProcess Manager (Saga)sent from the OutboxMortgageAccountOpeningRequestedcommand

    sent on attempt 1

  51. 12.73 sProjection (read model)processedCustomerIdentityCreatedintegration

  52. 12.58 sProcess Manager (Saga)processedCustomerIdentityCreatedintegration

  53. 12.58 sProcess Manager (Saga)stored in the OutboxMortgageAccountOpeningRequestedcommand

    for: Mortgage AccountProjection (read model)

    Event content
    {
      "applicationId": "calc-1",
      "amount": 5200000,
      "customerId": "CUST-0001"
    }

    evt-0025 · correlationId calc-1 · causationId evt-0021

  54. 12.38 sProjection (read model)picked upCustomerIdentityCreatedintegration

    attempt 1

  55. 12.33 sProcess Manager (Saga)picked upCustomerIdentityCreatedintegration

    attempt 1

  56. 12.0 sCustomer Identitysent from the OutboxCustomerIdentityCreatedintegration

    sent on attempt 3

  57. 11.5 sCustomer Identityfailed while processingCustomerIdentityCreatedintegration

    relay: broker unavailable, attempt 2

  58. 11.0 sCustomer Identityfailed while processingCustomerIdentityCreatedintegration

    relay: broker unavailable, attempt 1

  59. 10.7 sCustomer IdentityprocessedCustomerIdentityCreationRequestedcommand

  60. 10.7 sCustomer Identitystored in the OutboxCustomerIdentityCreatedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "customerId": "CUST-0001"
    }

    evt-0021 · correlationId calc-1 · causationId evt-0017

  61. 10.38 sProjection (read model)processedCustomerIdentityCreationRequestedcommand

  62. 10.03 sProjection (read model)picked upCustomerIdentityCreationRequestedcommand

    attempt 1

  63. 10.03 sCustomer Identitypicked upCustomerIdentityCreationRequestedcommand

    attempt 1

  64. 9.68 sProcess Manager (Saga)sent from the OutboxCustomerIdentityCreationRequestedcommand

    sent on attempt 6

  65. 9.18 sProcess Manager (Saga)failed while processingCustomerIdentityCreationRequestedcommand

    relay: broker unavailable, attempt 5

  66. 8.68 sProcess Manager (Saga)failed while processingCustomerIdentityCreationRequestedcommand

    relay: broker unavailable, attempt 4

  67. 8.18 sProcess Manager (Saga)failed while processingCustomerIdentityCreationRequestedcommand

    relay: broker unavailable, attempt 3

  68. 7.68 sProcess Manager (Saga)failed while processingCustomerIdentityCreationRequestedcommand

    relay: broker unavailable, attempt 2

  69. 7.18 sProcess Manager (Saga)failed while processingCustomerIdentityCreationRequestedcommand

    relay: broker unavailable, attempt 1

  70. 6.95 sProjection (read model)processedMortgageApprovedintegration

  71. 6.88 sProcess Manager (Saga)processedMortgageApprovedintegration

  72. 6.88 sProcess Manager (Saga)stored in the OutboxCustomerIdentityCreationRequestedcommand

    for: Customer IdentityProjection (read model)

    Event content
    {
      "applicationId": "calc-1",
      "amount": 5200000
    }

    evt-0017 · correlationId calc-1 · causationId evt-0013

  73. 6.58 sProjection (read model)picked upMortgageApprovedintegration

    attempt 1

  74. 6.55 sProcess Manager (Saga)picked upMortgageApprovedintegration

    attempt 1

  75. 6.18 sApproval / Controllingsent from the OutboxMortgageApprovedintegration

    sent on attempt 2

  76. 5.68 sApproval / Controllingfailed while processingMortgageApprovedintegration

    relay: broker unavailable, attempt 1

  77. 5.38 sApproval / ControllingprocessedRiskAssessmentCompletedintegration

  78. 5.38 sApproval / Controllingstored in the OutboxMortgageApprovedintegration

    for: Process Manager (Saga)Projection (read model)

    Event content
    {
      "approvedAmount": 5200000,
      "score": 800
    }

    evt-0013 · correlationId calc-1 · causationId evt-0009

  79. 5.05 sProjection (read model)processedRiskAssessmentCompletedintegration

  80. 4.83 sApproval / Controllingpicked upRiskAssessmentCompletedintegration

    attempt 1

  81. 4.8 sProjection (read model)picked upRiskAssessmentCompletedintegration

    attempt 1

  82. 4.5 sRisk Servicesent from the OutboxRiskAssessmentCompletedintegration

    sent on attempt 5

  83. 4.0 sRisk Servicefailed while processingRiskAssessmentCompletedintegration

    relay: broker unavailable, attempt 4

  84. 3.5 sRisk Servicefailed while processingRiskAssessmentCompletedintegration

    relay: broker unavailable, attempt 3

  85. 3.0 sRisk Servicefailed while processingRiskAssessmentCompletedintegration

    relay: broker unavailable, attempt 2

  86. 2.5 sRisk Servicefailed while processingRiskAssessmentCompletedintegration

    relay: broker unavailable, attempt 1

  87. 2.2 sRisk ServiceprocessedMortgageApplicationSubmittedintegration

  88. 2.2 sRisk Servicestored in the OutboxRiskAssessmentCompletedintegration

    for: Approval / ControllingProjection (read model)

    Event content
    {
      "score": 800,
      "loanAmount": 5200000,
      "monthlyIncome": 85000,
      "dti": 0.34811764705882353,
      "ltv": 0.8
    }

    evt-0009 · correlationId calc-1 · causationId evt-0004

  89. 1.98 sProjection (read model)processedMortgageApplicationSubmittedintegration

  90. 1.93 sProcess Manager (Saga)processedMortgageApplicationSubmittedintegration

  91. 1.7 sRisk Servicepicked upMortgageApplicationSubmittedintegration

    attempt 1

  92. 1.65 sProcess Manager (Saga)picked upMortgageApplicationSubmittedintegration

    attempt 1

  93. 1.63 sProjection (read model)picked upMortgageApplicationSubmittedintegration

    attempt 1

  94. 1.3 sMortgage Calculator APIsent from the OutboxMortgageApplicationSubmittedintegration

    sent on attempt 3

  95. 0.8 sMortgage Calculator APIfailed while processingMortgageApplicationSubmittedintegration

    relay: broker unavailable, attempt 2

  96. 0.3 sMortgage Calculator APIfailed while processingMortgageApplicationSubmittedintegration

    relay: broker unavailable, attempt 1

  97. 0.0 sMortgage Calculator APIstored in the OutboxMortgageApplicationSubmittedintegration

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

    evt-0004 · correlationId calc-1 · causationId evt-0003

  98. 0.0 sMortgage Calculator APIappended to the event storeApplicationSubmitteddomain

    Event 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"
      }
    }

    evt-0003 · correlationId calc-1

  99. 0.0 sMortgage Calculator APIappended to the event storeCalculationCompleteddomain

    Event content
    {
      "algorithm": "v1",
      "result": {
        "loan": 5200000,
        "monthlyPayment": 29590,
        "dti": 0.34811764705882353,
        "ltv": 0.8,
        "algorithm": "v1"
      },
      "referenceNumber": "KALK-calc-1-2"
    }

    evt-0002 · correlationId calc-1

  100. 0.0 sMortgage Calculator APIappended to the event storeCalculationCreateddomain

    Event content
    {
      "calculationId": "calc-1",
      "monthlyIncome": 85000,
      "propertyPrice": 6500000,
      "downPaymentPct": 20,
      "ratePct": 5.49,
      "termYears": 30
    }

    evt-0001 · correlationId calc-1

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.

Language
Variant
# 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.

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