Exercise 13 · ContractGenerationRequested → ContractGenerated → ContractSigned

Document Service: delivery order

  • out-of-order
  • corrSeq
  • resequencing
  • rebuild from the event store

Principle

A broker in a distributed system doesn't guarantee global ordering. The ContractSigned event may reach the projection before ContractGenerated.

A projection that applies events in delivery order shows the wrong state (the state “goes backwards”) or loses information.

Solution: events carry an order within the correlation (corrSeq). The projection holds early events in a buffer and discards duplicates. And above all: the truth is in the event store, the projection can always be rebuilt.

What to watch

  • The processing order in the broker timeline differs from the order in the event store.
  • The projection's final state vs. the Process Manager.
  • The “Rebuild projection from event store” button.

Experiment

What to do: Click “Run with shuffled order”. What to look at: The contract state in the view doesn't match the actual state.

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

Run with shuffled order

The projection receives events with a random delay of up to 5 s and applies them as they arrive.

How the run unfolds (newest on top)

  1. 11.45 sProjection (read model)processedContractGenerationRequestedcommand

  2. 11.18 sProjection (read model)picked upContractGenerationRequestedcommand

    attempt 1

  3. 10.8 sProjection (read model)processedContractSignedintegration

  4. 10.45 sProjection (read model)picked upContractSignedintegration

    attempt 1

  5. 10.45 sProjection (read model)processedContractGeneratedintegration

  6. 10.13 sProjection (read model)picked upContractGeneratedintegration

    attempt 1

  7. 9.7 sProjection (read model)processedMortgageAccountOpeningRequestedcommand

  8. 9.38 sProjection (read model)picked upMortgageAccountOpeningRequestedcommand

    attempt 1

  9. 9.25 sProcess Manager (Saga)processedContractSignedintegration

  10. 8.88 sProcess Manager (Saga)picked upContractSignedintegration

    attempt 1

  11. 8.78 sProjection (read model)processedMortgageAccountOpenedintegration

  12. 8.53 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  13. 8.5 sDocument Serviceappended and publishedContractSignedintegration

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

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

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

  14. 7.68 sProcess Manager (Saga)processedContractGeneratedintegration

  15. 7.35 sProcess Manager (Saga)picked upContractGeneratedintegration

    attempt 1

  16. 7.05 sProjection (read model)processedCustomerIdentityCreatedintegration

  17. 6.98 sDocument ServiceprocessedContractGenerationRequestedcommand

  18. 6.98 sDocument Serviceappended and publishedContractGeneratedintegration

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

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

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

  19. 6.73 sProjection (read model)picked upCustomerIdentityCreatedintegration

    attempt 1

  20. 6.73 sProjection (read model)processedCustomerIdentityCreationRequestedcommand

  21. 6.35 sProjection (read model)picked upCustomerIdentityCreationRequestedcommand

    attempt 1

  22. 6.33 sDocument Servicepicked upContractGenerationRequestedcommand

    attempt 1

  23. 5.95 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  24. 5.95 sProcess Manager (Saga)appended and publishedContractGenerationRequestedcommand

    for: Document ServiceProjection (read model)

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

    evt-0026 · correlationId calc-1 · causationId evt-0023

  25. 5.63 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  26. 5.35 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  27. 5.35 sMortgage Accountappended and publishedMortgageAccountOpenedintegration

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

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

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

  28. 4.83 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  29. 4.5 sProcess Manager (Saga)processedCustomerIdentityCreatedintegration

  30. 4.5 sProcess Manager (Saga)appended and publishedMortgageAccountOpeningRequestedcommand

    for: Mortgage AccountProjection (read model)

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

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

  31. 4.15 sProcess Manager (Saga)picked upCustomerIdentityCreatedintegration

    attempt 1

  32. 3.75 sCustomer IdentityprocessedCustomerIdentityCreationRequestedcommand

  33. 3.75 sCustomer Identityappended and publishedCustomerIdentityCreatedintegration

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

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

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

  34. 3.55 sProjection (read model)processedMortgageApprovedintegration

  35. 3.25 sProjection (read model)picked upMortgageApprovedintegration

    attempt 1

  36. 3.25 sProjection (read model)processedRiskAssessmentCompletedintegration

  37. 3.0 sProjection (read model)picked upRiskAssessmentCompletedintegration

    attempt 1

  38. 3.0 sProjection (read model)processedMortgageApplicationSubmittedintegration

  39. 3.0 sCustomer Identitypicked upCustomerIdentityCreationRequestedcommand

    attempt 1

  40. 2.68 sProjection (read model)picked upMortgageApplicationSubmittedintegration

    attempt 1

  41. 2.58 sProcess Manager (Saga)processedMortgageApprovedintegration

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

  43. 2.25 sProcess Manager (Saga)picked upMortgageApprovedintegration

    attempt 1

  44. 1.83 sApproval / ControllingprocessedRiskAssessmentCompletedintegration

  45. 1.83 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

  46. 1.28 sApproval / Controllingpicked upRiskAssessmentCompletedintegration

    attempt 1

  47. 0.9 sRisk ServiceprocessedMortgageApplicationSubmittedintegration

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

  49. 0.75 sProcess Manager (Saga)processedMortgageApplicationSubmittedintegration

  50. 0.4 sProcess Manager (Saga)picked upMortgageApplicationSubmittedintegration

    attempt 1

  51. 0.28 sRisk Servicepicked upMortgageApplicationSubmittedintegration

    attempt 1

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

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

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

  55. 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 corrSeq ordering

The projection waits for missing events and applies them in the correct order. The result is the same as in the Process Manager.

How the run unfolds (newest on top)

  1. 11.45 sProjection (read model)processedContractGenerationRequestedcommand

  2. 11.18 sProjection (read model)picked upContractGenerationRequestedcommand

    attempt 1

  3. 10.8 sProjection (read model)processedContractSignedintegration

  4. 10.8 sProjection (read model)bufferedContractSignedintegration

    waiting for corrSeq 8

  5. 10.45 sProjection (read model)picked upContractSignedintegration

    attempt 1

  6. 10.45 sProjection (read model)processedContractGeneratedintegration

  7. 10.45 sProjection (read model)bufferedContractGeneratedintegration

    waiting for corrSeq 8

  8. 10.13 sProjection (read model)picked upContractGeneratedintegration

    attempt 1

  9. 9.7 sProjection (read model)processedMortgageAccountOpeningRequestedcommand

  10. 9.38 sProjection (read model)picked upMortgageAccountOpeningRequestedcommand

    attempt 1

  11. 9.25 sProcess Manager (Saga)processedContractSignedintegration

  12. 8.88 sProcess Manager (Saga)picked upContractSignedintegration

    attempt 1

  13. 8.78 sProjection (read model)processedMortgageAccountOpenedintegration

  14. 8.78 sProjection (read model)bufferedMortgageAccountOpenedintegration

    waiting for corrSeq 6

  15. 8.53 sProjection (read model)picked upMortgageAccountOpenedintegration

    attempt 1

  16. 8.5 sDocument Serviceappended and publishedContractSignedintegration

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

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

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

  17. 7.68 sProcess Manager (Saga)processedContractGeneratedintegration

  18. 7.35 sProcess Manager (Saga)picked upContractGeneratedintegration

    attempt 1

  19. 7.05 sProjection (read model)processedCustomerIdentityCreatedintegration

  20. 6.98 sDocument ServiceprocessedContractGenerationRequestedcommand

  21. 6.98 sDocument Serviceappended and publishedContractGeneratedintegration

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

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

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

  22. 6.73 sProjection (read model)picked upCustomerIdentityCreatedintegration

    attempt 1

  23. 6.73 sProjection (read model)processedCustomerIdentityCreationRequestedcommand

  24. 6.35 sProjection (read model)picked upCustomerIdentityCreationRequestedcommand

    attempt 1

  25. 6.33 sDocument Servicepicked upContractGenerationRequestedcommand

    attempt 1

  26. 5.95 sProcess Manager (Saga)processedMortgageAccountOpenedintegration

  27. 5.95 sProcess Manager (Saga)appended and publishedContractGenerationRequestedcommand

    for: Document ServiceProjection (read model)

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

    evt-0026 · correlationId calc-1 · causationId evt-0023

  28. 5.63 sProcess Manager (Saga)picked upMortgageAccountOpenedintegration

    attempt 1

  29. 5.35 sMortgage AccountprocessedMortgageAccountOpeningRequestedcommand

  30. 5.35 sMortgage Accountappended and publishedMortgageAccountOpenedintegration

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

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

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

  31. 4.83 sMortgage Accountpicked upMortgageAccountOpeningRequestedcommand

    attempt 1

  32. 4.5 sProcess Manager (Saga)processedCustomerIdentityCreatedintegration

  33. 4.5 sProcess Manager (Saga)appended and publishedMortgageAccountOpeningRequestedcommand

    for: Mortgage AccountProjection (read model)

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

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

  34. 4.15 sProcess Manager (Saga)picked upCustomerIdentityCreatedintegration

    attempt 1

  35. 3.75 sCustomer IdentityprocessedCustomerIdentityCreationRequestedcommand

  36. 3.75 sCustomer Identityappended and publishedCustomerIdentityCreatedintegration

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

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

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

  37. 3.55 sProjection (read model)processedMortgageApprovedintegration

  38. 3.25 sProjection (read model)picked upMortgageApprovedintegration

    attempt 1

  39. 3.25 sProjection (read model)processedRiskAssessmentCompletedintegration

  40. 3.0 sProjection (read model)picked upRiskAssessmentCompletedintegration

    attempt 1

  41. 3.0 sProjection (read model)processedMortgageApplicationSubmittedintegration

  42. 3.0 sCustomer Identitypicked upCustomerIdentityCreationRequestedcommand

    attempt 1

  43. 2.68 sProjection (read model)picked upMortgageApplicationSubmittedintegration

    attempt 1

  44. 2.58 sProcess Manager (Saga)processedMortgageApprovedintegration

  45. 2.58 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

  46. 2.25 sProcess Manager (Saga)picked upMortgageApprovedintegration

    attempt 1

  47. 1.83 sApproval / ControllingprocessedRiskAssessmentCompletedintegration

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

  49. 1.28 sApproval / Controllingpicked upRiskAssessmentCompletedintegration

    attempt 1

  50. 0.9 sRisk ServiceprocessedMortgageApplicationSubmittedintegration

  51. 0.9 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

  52. 0.75 sProcess Manager (Saga)processedMortgageApplicationSubmittedintegration

  53. 0.4 sProcess Manager (Saga)picked upMortgageApplicationSubmittedintegration

    attempt 1

  54. 0.28 sRisk Servicepicked upMortgageApplicationSubmittedintegration

    attempt 1

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

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

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

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

13 events · 11.5 s of simulated time

13 events · 11.5 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.

Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

Language
Variant
# Task for a coding agent: Document Service: delivery order

Stack: Java. Mode: guided.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Specific task

Technical specifics (Java): Kafka: partition key = applicationId; elsewhere a buffer in the projection table.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where order really matters (per aggregate / correlation) and where it does not.
2. Add `sequence` (position in the application flow) to integration messages. If the contract must not get a new field, put it in the message header; process a message without it as before.
3. Projection and process alike: discard an event with a lower number than expected, defer a higher one, apply a matching one. A process with a side effect advances its state only after the effect succeeds; a rebuild does not repeat the effect.
4. Buffer timeout derived from the producer's retry window: after the deadline, raise an alarm and refill the message from the source; never skip the gap.
5. Test: every ordering of one application's messages (with duplicates, two applications interleaved) yields the same final state; at least one test fails without ordering.

Watch out for:
- A partition key keeps order only within a topic; a flow across several topics is ordered by the consumer.
- A consumer ordering by sequence subscribes to all topics of the flow, otherwise it waits forever.

## 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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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: Document Service: delivery order

Stack: Java. Mode: challenge.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Brief (Challenge)

Make sure the read model does not depend on the order in which events are delivered, and allow it to be rebuilt from the event store.

Technical specifics (Java): Kafka: partition key = applicationId; elsewhere a buffer in the projection table.

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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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: Document Service: delivery order

Stack: C#. Mode: guided.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Specific task

Technical specifics (C#): Service Bus sessions or partition key; elsewhere a buffer in the projection table.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where order really matters (per aggregate / correlation) and where it does not.
2. Add `sequence` (position in the application flow) to integration messages. If the contract must not get a new field, put it in the message header; process a message without it as before.
3. Projection and process alike: discard an event with a lower number than expected, defer a higher one, apply a matching one. A process with a side effect advances its state only after the effect succeeds; a rebuild does not repeat the effect.
4. Buffer timeout derived from the producer's retry window: after the deadline, raise an alarm and refill the message from the source; never skip the gap.
5. Test: every ordering of one application's messages (with duplicates, two applications interleaved) yields the same final state; at least one test fails without ordering.

Watch out for:
- A partition key keeps order only within a topic; a flow across several topics is ordered by the consumer.
- A consumer ordering by sequence subscribes to all topics of the flow, otherwise it waits forever.

## 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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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: Document Service: delivery order

Stack: C#. Mode: challenge.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Brief (Challenge)

Make sure the read model does not depend on the order in which events are delivered, and allow it to be rebuilt from the event store.

Technical specifics (C#): Service Bus sessions or partition key; elsewhere a buffer in the projection table.

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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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: Document Service: delivery order

Stack: Web (HTML/JS or the app's stack). Mode: guided.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Specific task

Technical specifics (Web (HTML/JS or the app's stack)): Buffer in memory/IndexedDB and a pure function `applyInOrder(events)` tested on permutations; the rebuild source is the broker log or the message store.

Proceed step by step. After point 1 (plan), write what you found and what you propose, and wait for confirmation:
1. Plan: where order really matters (per aggregate / correlation) and where it does not.
2. Add `sequence` (position in the application flow) to integration messages. If the contract must not get a new field, put it in the message header; process a message without it as before.
3. Projection and process alike: discard an event with a lower number than expected, defer a higher one, apply a matching one. A process with a side effect advances its state only after the effect succeeds; a rebuild does not repeat the effect.
4. Buffer timeout derived from the producer's retry window: after the deadline, raise an alarm and refill the message from the source; never skip the gap.
5. Test: every ordering of one application's messages (with duplicates, two applications interleaved) yields the same final state; at least one test fails without ordering.

Watch out for:
- A partition key keeps order only within a topic; a flow across several topics is ordered by the consumer.
- A consumer ordering by sequence subscribes to all topics of the flow, otherwise it waits forever.

## 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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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: Document Service: delivery order

Stack: Web (HTML/JS or the app's stack). Mode: challenge.
Goal: Handle out-of-order delivery in the application-state read model and in the Document Service process (loan contract) using a sequence number within the correlation.

## 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 an application message flow with `correlationId`. If not, first set up a minimal in-memory broker and the flow submission → risk → approval → account.

Read first, change nothing. Find and briefly summarise:
- Where a projection or handler assumes event ordering. If Document Service is missing as a consumer, design it: it creates the contract once it has the application submission, the approval and `MortgageAccountOpened`.
- Whether messages carry a stream sequence/version and a correlationId.
- Broker options: partition key / session to preserve ordering.
- 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 does not guarantee order: a projection that applies messages as they arrive “goes backwards” or loses data. A flow message carries a sequence within the correlation (first is 1, each follow-up 1 more than its cause); the consumer defers an early one and discards a duplicate. The truth lives in the message source, so the projection can be rebuilt. Example: approval (3) arrives before risk (2); without ordering the application state loses its score.

## Brief (Challenge)

Make sure the read model does not depend on the order in which events are delivered, and allow it to be rebuilt from the event store.

Technical specifics (Web (HTML/JS or the app's stack)): Buffer in memory/IndexedDB and a pure function `applyInOrder(events)` tested on permutations; the rebuild source is the broker log or the message store.

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 of all orderings (with duplicates) and a test that fails without ordering.
- Duplicates are not applied twice; the process side effect runs once.
- There is a command for rebuild (endpoint or CLI).
- 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