Exercise 12 · MortgageAccountOpeningRequested → MortgageAccountOpened, Inbox

Mortgage Account: duplicates and idempotency

  • at-least-once
  • duplicity
  • idempotence
  • Inbox

Principle

The broker guarantees “at least once”, not “exactly once”. The same message may arrive twice (lost acknowledgement, redelivery, retry).

Without idempotency the service opens a second account. An idempotent receiver remembers the processed eventIds (Inbox) and, for the same request, creates no new effect but returns the original result.

The Inbox is written in the same transaction as the effect; otherwise a window for duplicates opens again.

What to watch

  • The number of accounts in the service's local database.
  • The “duplicate-ignored” trace in the broker timeline.

Experiment

What to do: Click “Run with duplicate delivery”. What to look at: Mortgage Account opens two accounts for one mortgage.

The simulation needs JavaScript. Below is a recording of both runs.

Run with duplicate delivery

The broker delivers each account-opening request 2×. The service has no Inbox.

How the run unfolds (newest on top)

  1. 6.33 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  2. 6.33 sProcess Manager (Saga)ignored-stateMortgageAccountOpenedintegration

    krok account is already done

  3. 6.25 sProjection (read model)processedMortgageAccountOpenedintegration

  4. 6.0 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  5. 5.98 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  6. 5.55 sProjection (read model)processedMortgageAccountOpenedintegration

  7. 5.55 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  8. 5.55 sMortgage Accountappended and publishedMortgageAccountOpenedintegration

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

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

    evt-0027 · correlationId calc-1 · causationId evt-0020

  9. 5.48 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  10. 5.23 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  11. 5.23 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  12. 4.8 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  13. 4.8 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  14. 4.8 sMortgage Accountappended and publishedMortgageAccountOpenedintegration

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

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

    evt-0024 · correlationId calc-1 · causationId evt-0020

  15. 4.33 sProjection (read model)processedMortgageAccountOpeningRequestedcommand

  16. 4.15 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  17. 4.05 sProjection (read model)picked upMortgageAccountOpeningRequestedcommand

    attempt 1

  18. 3.88 sProjection (read model)processedCustomerIdentityCreatedintegration

  19. 3.75 sProcess Manager (Saga)processedCustomerIdentityCreatedintegration

  20. 3.75 sProcess Manager (Saga)publishedMortgageAccountOpeningRequestedcommand

  21. 3.75 sMortgage Accountreceives the message twiceMortgageAccountOpeningRequestedcommand

    broker delivers the message 2×

  22. 3.75 sProcess Manager (Saga)appended to the event storeMortgageAccountOpeningRequestedcommand

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

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

  23. 3.58 sProjection (read model)picked upCustomerIdentityCreatedintegration

    attempt 1

  24. 3.45 sProcess Manager (Saga)picked upCustomerIdentityCreatedintegration

    attempt 1

  25. 3.18 sCustomer IdentityprocessedCustomerIdentityCreationRequestedcommand

  26. 3.18 sCustomer Identityappended and publishedCustomerIdentityCreatedintegration

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

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

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

  27. 3.03 sProjection (read model)processedCustomerIdentityCreationRequestedcommand

  28. 2.7 sCustomer Identitypicked upCustomerIdentityCreationRequestedcommand

    attempt 1

  29. 2.68 sProjection (read model)picked upCustomerIdentityCreationRequestedcommand

    attempt 1

  30. 2.3 sProcess Manager (Saga)processedMortgageApprovedintegration

  31. 2.3 sProcess Manager (Saga)appended and publishedCustomerIdentityCreationRequestedcommand

    for: Customer IdentityProjection (read model)

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

    evt-0014 · correlationId calc-1 · causationId evt-0011

  32. 2.23 sProjection (read model)processedMortgageApprovedintegration

  33. 1.98 sProjection (read model)picked upMortgageApprovedintegration

    attempt 1

  34. 1.95 sProcess Manager (Saga)picked upMortgageApprovedintegration

    attempt 1

  35. 1.65 sApproval / ControllingprocessedRiskAssessmentCompletedintegration

  36. 1.65 sApproval / Controllingappended and publishedMortgageApprovedintegration

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

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

    evt-0011 · correlationId calc-1 · causationId evt-0008

  37. 1.5 sProjection (read model)processedRiskAssessmentCompletedintegration

  38. 1.13 sProjection (read model)picked upRiskAssessmentCompletedintegration

    attempt 1

  39. 1.1 sApproval / Controllingpicked upRiskAssessmentCompletedintegration

    attempt 1

  40. 0.8 sRisk ServiceprocessedMortgageApplicationSubmittedintegration

  41. 0.8 sRisk Serviceappended and publishedRiskAssessmentCompletedintegration

    for: Approval / ControllingProjection (read model)

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

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

  42. 0.75 sProcess Manager (Saga)processedMortgageApplicationSubmittedintegration

  43. 0.68 sProjection (read model)processedMortgageApplicationSubmittedintegration

  44. 0.4 sProcess Manager (Saga)picked upMortgageApplicationSubmittedintegration

    attempt 1

  45. 0.35 sProjection (read model)picked upMortgageApplicationSubmittedintegration

    attempt 1

  46. 0.28 sRisk Servicepicked upMortgageApplicationSubmittedintegration

    attempt 1

  47. 0.0 sMortgage Calculator APIappended and publishedMortgageApplicationSubmittedintegration

    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

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

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

  50. 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 Inbox

The service recognises the second delivery by its eventId and ignores it. A single account is created.

How the run unfolds (newest on top)

  1. 5.55 sProjection (read model)processedMortgageAccountOpenedintegration

  2. 5.55 sMortgage Accountignored a duplicate (Inbox)MortgageAccountOpeningRequestedcommand

    Inbox: eventId already processed

  3. 5.48 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  4. 5.23 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  5. 5.23 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  6. 4.8 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  7. 4.8 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  8. 4.8 sMortgage Accountappended and publishedMortgageAccountOpenedintegration

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

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

    evt-0024 · correlationId calc-1 · causationId evt-0020

  9. 4.33 sProjection (read model)processedMortgageAccountOpeningRequestedcommand

  10. 4.15 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  11. 4.05 sProjection (read model)picked upMortgageAccountOpeningRequestedcommand

    attempt 1

  12. 3.88 sProjection (read model)processedCustomerIdentityCreatedintegration

  13. 3.75 sProcess Manager (Saga)processedCustomerIdentityCreatedintegration

  14. 3.75 sProcess Manager (Saga)publishedMortgageAccountOpeningRequestedcommand

  15. 3.75 sMortgage Accountreceives the message twiceMortgageAccountOpeningRequestedcommand

    broker delivers the message 2×

  16. 3.75 sProcess Manager (Saga)appended to the event storeMortgageAccountOpeningRequestedcommand

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

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

  17. 3.58 sProjection (read model)picked upCustomerIdentityCreatedintegration

    attempt 1

  18. 3.45 sProcess Manager (Saga)picked upCustomerIdentityCreatedintegration

    attempt 1

  19. 3.18 sCustomer IdentityprocessedCustomerIdentityCreationRequestedcommand

  20. 3.18 sCustomer Identityappended and publishedCustomerIdentityCreatedintegration

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

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

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

  21. 3.03 sProjection (read model)processedCustomerIdentityCreationRequestedcommand

  22. 2.7 sCustomer Identitypicked upCustomerIdentityCreationRequestedcommand

    attempt 1

  23. 2.68 sProjection (read model)picked upCustomerIdentityCreationRequestedcommand

    attempt 1

  24. 2.3 sProcess Manager (Saga)processedMortgageApprovedintegration

  25. 2.3 sProcess Manager (Saga)appended and publishedCustomerIdentityCreationRequestedcommand

    for: Customer IdentityProjection (read model)

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

    evt-0014 · correlationId calc-1 · causationId evt-0011

  26. 2.23 sProjection (read model)processedMortgageApprovedintegration

  27. 1.98 sProjection (read model)picked upMortgageApprovedintegration

    attempt 1

  28. 1.95 sProcess Manager (Saga)picked upMortgageApprovedintegration

    attempt 1

  29. 1.65 sApproval / ControllingprocessedRiskAssessmentCompletedintegration

  30. 1.65 sApproval / Controllingappended and publishedMortgageApprovedintegration

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

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

    evt-0011 · correlationId calc-1 · causationId evt-0008

  31. 1.5 sProjection (read model)processedRiskAssessmentCompletedintegration

  32. 1.13 sProjection (read model)picked upRiskAssessmentCompletedintegration

    attempt 1

  33. 1.1 sApproval / Controllingpicked upRiskAssessmentCompletedintegration

    attempt 1

  34. 0.8 sRisk ServiceprocessedMortgageApplicationSubmittedintegration

  35. 0.8 sRisk Serviceappended and publishedRiskAssessmentCompletedintegration

    for: Approval / ControllingProjection (read model)

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

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

  36. 0.75 sProcess Manager (Saga)processedMortgageApplicationSubmittedintegration

  37. 0.68 sProjection (read model)processedMortgageApplicationSubmittedintegration

  38. 0.4 sProcess Manager (Saga)picked upMortgageApplicationSubmittedintegration

    attempt 1

  39. 0.35 sProjection (read model)picked upMortgageApplicationSubmittedintegration

    attempt 1

  40. 0.28 sRisk Servicepicked upMortgageApplicationSubmittedintegration

    attempt 1

  41. 0.0 sMortgage Calculator APIappended and publishedMortgageApplicationSubmittedintegration

    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

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

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

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

11 events · 6.4 s of simulated time

Cause → effect

  • MortgageAccountOpeningRequested processed a second time without idempotency → Duplicate mortgage account 0800-100034/0800: the client has two accounts for one mortgage MortgageAccountOpeningRequested

10 events · 5.6 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.

Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

Language
Variant
# Task for a coding agent: Mortgage Account: duplicates and idempotency

Stack: Java. Mode: guided.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Specific task

Technical specifics (Java): `@Transactional` handler, unique index on `message_id` and `application_id`.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where the deduplication key (eventId) is and where the business key (applicationId) is.
2. An Inbox table (unique messageId) in the account service's database, written in the same transaction as the account creation. Over the network, send `eventId` as the idempotency key.
3. A duplicate returns the original result and republishes the reply event (example above).
4. A unique constraint on the business key as a second layer of defence. If the existing table can't take it, put it in a new table in the same transaction.
5. Test: the same message 2× → one account; two different requests for the same application → one account; a race that fails without the unique key (two database connections, or a double with a stale read).

Watch out for:
- “If exists” deduplication without a unique constraint has a race.
- The Inbox grows: a clean-up plan after retention; retention must outlast retries, the DLQ and manual redrive.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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: Mortgage Account: duplicates and idempotency

Stack: Java. Mode: challenge.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Brief (Challenge)

Guarantee that repeated delivery of MortgageAccountOpeningRequested never creates a second account, even with concurrent delivery.

Technical specifics (Java): `@Transactional` handler, unique index on `message_id` and `application_id`.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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: Mortgage Account: duplicates and idempotency

Stack: C#. Mode: guided.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Specific task

Technical specifics (C#): `DbContext` transaction, unique indexes; use the existing messaging library's inbox if it has one.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where the deduplication key (eventId) is and where the business key (applicationId) is.
2. An Inbox table (unique messageId) in the account service's database, written in the same transaction as the account creation. Over the network, send `eventId` as the idempotency key.
3. A duplicate returns the original result and republishes the reply event (example above).
4. A unique constraint on the business key as a second layer of defence. If the existing table can't take it, put it in a new table in the same transaction.
5. Test: the same message 2× → one account; two different requests for the same application → one account; a race that fails without the unique key (two database connections, or a double with a stale read).

Watch out for:
- “If exists” deduplication without a unique constraint has a race.
- The Inbox grows: a clean-up plan after retention; retention must outlast retries, the DLQ and manual redrive.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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: Mortgage Account: duplicates and idempotency

Stack: C#. Mode: challenge.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Brief (Challenge)

Guarantee that repeated delivery of MortgageAccountOpeningRequested never creates a second account, even with concurrent delivery.

Technical specifics (C#): `DbContext` transaction, unique indexes; use the existing messaging library's inbox if it has one.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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: Mortgage Account: duplicates and idempotency

Stack: Web (HTML/JS or the app's stack). Mode: guided.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Specific task

Technical specifics (Web (HTML/JS or the app's stack)): With a backend, a single account-service transaction across the inbox and the account; without a backend, a single IndexedDB transaction across the inbox and the data.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where the deduplication key (eventId) is and where the business key (applicationId) is.
2. An Inbox table (unique messageId) in the account service's database, written in the same transaction as the account creation. Over the network, send `eventId` as the idempotency key.
3. A duplicate returns the original result and republishes the reply event (example above).
4. A unique constraint on the business key as a second layer of defence. If the existing table can't take it, put it in a new table in the same transaction.
5. Test: the same message 2× → one account; two different requests for the same application → one account; a race that fails without the unique key (two database connections, or a double with a stale read).

Watch out for:
- “If exists” deduplication without a unique constraint has a race.
- The Inbox grows: a clean-up plan after retention; retention must outlast retries, the DLQ and manual redrive.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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: Mortgage Account: duplicates and idempotency

Stack: Web (HTML/JS or the app's stack). Mode: challenge.
Goal: Make the MortgageAccountOpeningRequested consumer idempotent via an Inbox table in the same transaction as the effect.

## 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 the `MortgageAccountOpeningRequested` message (`applicationId`, `identityCheckId`) from Customer Identity after identity verification. If not, first create a minimal producer and consumer.

Read first, change nothing. Find and briefly summarise:
- The handler that opens the account, and the transaction boundary.
- Whether an inbox/deduplication already exists in the messaging library (e.g. the inbox in MassTransit/Wolverine).
- The natural business key (applicationId).
- Which of these parts already exist in the project and which are missing. Before you write your own infrastructure (broker client, outbox, retry), check whether the project or organisation already has it as a ready-made library, and use it.

## Expected behaviour

The broker delivers “at least once”: the same message may arrive twice and without idempotency a second account is created. The idempotent receiver writes `eventId` to the Inbox in the same transaction as the account and ignores the second delivery. Example: a duplicate gets the original account (success, not 409) and the `MortgageAccountOpened` reply with the same `eventId`.

## Brief (Challenge)

Guarantee that repeated delivery of MortgageAccountOpeningRequested never creates a second account, even with concurrent delivery.

Technical specifics (Web (HTML/JS or the app's stack)): With a backend, a single account-service transaction across the inbox and the account; without a backend, a single IndexedDB transaction across the inbox and the data.

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

- A test for both duplicate and concurrent delivery.
- The Inbox and the effect are in one transaction (test: a failed write to the inbox leaves no account).
- An existing library is used if available.
- 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.

Further reading on the blog

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