Table of contents
Open Table of contents
- 0. Same “cancelled”, but the receiver wanted different events
- 1. The rules and constraints
- 2. Why only one place should decide
- 3. Three options and the one I chose
- 4. The classification rule
- 5. The trap: the earliest time in the processing batch
- 6. Verification scenarios
- 7. When to use this approach and when not to
- 8. Limits of this post
- 9. FAQ
- 10. Wrapping up
- References
0. Same “cancelled”, but the receiver wanted different events
Here is one flight booking in time order. The times are for illustration.
| Time | Event |
|---|---|
| 10:00 | A customer books in a sales channel’s app. Payment can come later. The payment deadline is 15:00 |
| 15:00 | The payment deadline. Payment is still accepted during this second |
| 15:00:01 | No payment has arrived. A batch job calls the cancel function, which cancels the booking at the airline and updates our database |
| Right after | Our service sends an event to the sales channel |
Before this change, the last row sent an “ordinary cancellation” event. That is the same event as when a customer cancels on purpose. The sales channel’s event spec asked us to mark this case as a payment-deadline expiry, so that the customer sees “expired because payment was not made in time” rather than “cancelled”.
This problem is not specific to flights. Changes that end in the same state but carry a different meaning for the receiver are common.
- A shop order became “cancelled”: did the customer ask, or did the payment window close?
- A subscription became “ended”: did the user cancel, or did payments keep failing?
- A booking “disappeared”: did we cancel it, or did an external system clean it up?
graph LR
A["Batch cancels after deadline"] --> X["Order status: cancelled"]
B["Support agent cancels"] --> X
C["Sales channel requests cancel"] --> X
D["Airline cleans up first"] --> X
X --> Q{"Which event to send?"}
Q --> E1["Expired"]
Q --> E2["Ordinary cancellation"]
As the diagram shows, there are many paths, but the order keeps only one state: “cancelled”. The resulting state alone cannot decide the event type. So who should decide it, and where?
0.1 Terms used in this post
| Term | Meaning |
|---|---|
| Producer | The side that changes state. Here, the cancel function and the features that call it |
| Outbox | A pattern where a state change also leaves a “process this order” record in the database, and the consumer reads that record to build events. If a signal is lost, a periodic job picks up the remaining records. The textbook outbox wraps the state change and the record in one transaction. This post’s cancel path does not (2.1) |
| Consumer | The program that receives signals, reads outbox records and the order’s current state, compares it with the previous state, and builds outgoing events |
| Snapshot | The “last announced state” the consumer stores per order, one row per version |
| State transition | The change between the snapshot and the current state. For example: “unpaid → cancelled” |
| Processing batch | The unprocessed outbox records for one order that the consumer reads together after one signal |
| Re-fetch | Asking the external system (the airline) for the current state and updating our database |
1. The rules and constraints
The receiver’s spec set three rules. A rule higher in the list wins.
- If the sales channel itself asked for the cancellation, send “ordinary cancellation”. The requester already knows.
- Otherwise, if an unpaid booking is cancelled or expires after its payment deadline, send “expired”. Who carried it out does not matter: the batch job, a support agent after the deadline, or the airline cleaning up first.
- Send exactly one of the two per cancellation. If both arrive, the receiver’s state changes twice.
Rule 2 shows that this work does not find out the cause of a cancellation. It classifies the event by conditions that the data can confirm: the previous state, the deadline, and whether there was an explicit request.
Two constraints came with it.
- Do not change the cancel function. The support agents’ screen, sales channel integrations, and internal automation all call it. Changing its parameters means reviewing and retesting every caller.
- Cancellations that never pass through our function must follow the same rule. If the airline cleans up a booking after the deadline, we learn about it during a re-fetch.
2. Why only one place should decide
2.1 How one cancellation becomes an event
- The cancel function changes the state, writes a cancellation record, and writes an outbox record.
- When a record commits, a “process this order” signal goes to Kafka.
- When the consumer receives a signal, it reads that order’s processing batch.
- The consumer rebuilds the order’s current state and compares it with the snapshot to find the state transition.
- The consumer first stores the new snapshot as “pending publish”, then sends the event, then marks it published.
graph LR
P["Producer<br/>(cancel function)"] -->|"state change, record<br/>(separate commits)"| DB[("Database<br/>order state, outbox records")]
P -->|"signal after commit"| K["Kafka"]
K -->|"process this order"| C["Consumer"]
C -->|"read processing batch"| DB
C -->|"compare"| S[("Snapshot")]
C -->|"event"| R["Receiver<br/>(sales channel)"]
This cancel path has one important property. The state change and the outbox records are not wrapped in one transaction. Each record commits on its own and sends its own signal. So records from the same cancellation can land in different processing batches. Which batch a record lands in depends on the timing of commits and reads.
2.2 What happens with two deciders
Suppose two places decide. The consumer classifies successful batch cancellations from the state transition. A detector at the end of the re-fetch writes an “expired” record directly when it finds the airline already cleaned up the booking. The re-fetch also changes the state to “cancelled”, so both places can see the same cancellation.
| Step | Detector (end of re-fetch) | Consumer |
|---|---|---|
| 1 | Commits the record that changes the state to “cancelled”, sends a signal | |
| 2 | Reads processing batch A. Sees the transition “unpaid → cancelled” | |
| 3 | Commits the “expired” record, sends a signal | Batch A has no “expired” record from the detector. Creates “expired” itself |
| 4 | Reads processing batch B, finds the detector’s “expired” record, and sends it too |
sequenceDiagram
participant D as Detector (end of re-fetch)
participant DB as Database / Kafka
participant C as Consumer
participant R as Receiver
D->>DB: commit state "cancelled", Kafka signal
C->>DB: read batch A
Note over C: sees "unpaid → cancelled"<br/>detector's record not there yet
D->>DB: commit "expired" record, Kafka signal
C->>R: "expired" (made by the consumer)
C->>DB: read batch B
C->>R: "expired" (left by the detector)
Note over R: [Problem] the same cancellation arrives twice
The same cancellation is announced twice. If the detector’s “expired” record had committed before batch A was read, it would have been in A, and the consumer would have preferred it and sent one event. The outcome depends on the timing of commits and reads. If the detector and the consumer classify differently, one “ordinary cancellation” and one “expired” can go out.
To prevent this with two deciders, they would have to share “someone already classified this transition”. With one decider, no such mechanism is needed.
3. Three options and the one I chose
| Place | What it does | Upside | Problem |
|---|---|---|---|
| A. The producer passes a reason | The batch job passes “deadline expired”, and the cancellation record keeps it | The side that acted announces it directly | Every caller of the shared function must be reviewed. Cleanups by an external system need another path |
| B. Add a second detector | When a re-fetch finds the booking gone, it writes an “expired” record directly | No change to the producer. Catches external cleanups | Misses our own batch cancellations, so two places decide (2.2) |
| C. The consumer classifies the state transition | Compares with the snapshot, finds “unpaid → cancelled or expired”, and checks the time and any explicit request | No change to the producer. One rule covers every path | A business rule lives in the consumer. Orders with no snapshot cannot be classified |
graph TB
subgraph A["A. Producer passes a reason"]
direction LR
A1["Cancel function + every caller<br/>[decides]"] --> A2["Consumer<br/>forwards only"]
A3["Airline cleanup"] -.->|"needs another path"| A2
end
subgraph B["B. Second detector"]
direction LR
B1["Re-fetch detector<br/>[decides 1]"] -->|"expired record"| B2["Consumer<br/>[decides 2]"]
B2 -->|"detector's + its own"| B3["Receiver"]
end
subgraph C["C. Consumer classifies (chosen)"]
direction LR
C1["Batch, agent,<br/>airline cleanup"] --> C2["Consumer<br/>[decides, one place]"] --> C3["Receiver"]
end
A ~~~ B ~~~ C
I dropped A at design time. I implemented B and then reverted it because of the race in 2.2.
I chose C because of a property of the state transition. “Unpaid → cancelled” happens only once per order. The consumer already kept a snapshot per order. If another signal arrives for the same order, the snapshot already says “cancelled”, so there is no transition. The integration check S5 confirmed that processing the same cancellation again creates no new event.
That is as far as one decider goes. It removes the race where two places create events independently. A gap remains even with one decider, though: the record of an explicit event can arrive later than the state change (section 8). Duplicates from retrying a send are prevented by other mechanisms that this consumer already had.
- Signals for one order are processed in order, in one partition.
- A snapshot version can be stored only once. The side that loses that write sends nothing.
- The snapshot is stored as “pending publish” before the send. If the consumer dies after sending but before marking it published, it sends the same event again. The event id is derived from the order and the version, so a resend carries the same id, and the next stage, which forwards events outside, filters duplicates by that id.
In short, delivery is at-least-once, and duplicates of the same event are filtered by a deterministic id. This change relies on those mechanisms. I did not verify them again.
4. The classification rule
For each processing batch, the consumer checks five conditions in order. If any condition fails, it does not create “expired”.
- The order status changed. If there is no state transition, stop.
- The state went from unpaid to cancelled or expired. A cancellation of a paid order is not an expiry. Some cancel responses come back as “expired”, so the expired state follows the same rule.
- Pick the time to compare. If the batch has cancellation records, use the time of the latest one. “Unpaid → cancelled” happens only once per order, so the cancellation records in the batch that reveals this transition are taken to belong to it. If no cancellation record is in the batch yet, or only re-fetch records are, use the latest record’s time as a fallback. The fallback is not the real cancellation time. It is at or after the time we found out, so the error only ever leans late, toward “expired”.
- That time is after the deadline. Both are stored in whole seconds, and the deadline second still accepts payment, so it counts as before the deadline.
- The batch has no explicit cancellation event. A cancellation the sales channel requested writes the event type into its cancellation record. In a batch that holds that record, the explicit event wins, and the consumer does not create “expired”.
When the consumer creates “expired”, it removes the “ordinary cancellation” that the state comparison made in the same batch. That keeps rule 3 from section 1.
Here is illustrative pseudocode. The names differ from the real code.
fun classifyExpiry(batch, transition, paymentDeadline, explicitEvents): Event? {
if (transition == null) return null
if (transition.from != UNPAID || transition.to !in setOf(CANCELLED, EXPIRED)) return null
// Without a cancellation record, fall back to when we found out. The error only leans late
val observedAt = batch.latestCancelRecord()?.createdAt ?: batch.latestRecord().createdAt
if (paymentDeadline >= observedAt) return null // the deadline second counts as before
if (explicitEvents.any { it.isCancellation() }) return null
return Event(PAYMENT_EXPIRED, observedAt)
}
Three principles generalize from this rule.
- If the business meaning is set by “what changed into what” and the conditions at that moment, the classification can be tied to the state transition in one consumer. If “who did it” changes the meaning, this principle does not apply.
- An explicit event for the same transition wins over a derived one.
- Take the time from the record that recorded the fact. If no such record exists and you use a fallback, know which way its error leans, and accept that direction as a business rule.
5. The trap: the earliest time in the processing batch
My first version used the earliest record time in the processing batch for step 3. An independent review gave this counterexample.
| Time | Event |
|---|---|
| 14:00 | An unrelated record is written for this order. It is not processed yet |
| 15:00 | The payment deadline |
| 15:10 | The batch job cancels and writes a cancellation record |
| Just after 15:10 | The consumer reads the 14:00 record and the 15:10 record as one batch |
graph LR
T1["14:00<br/>unrelated record"] --> T2["15:00<br/>payment deadline"] --> T3["15:10<br/>cancellation record"]
T1 -.->|"[Problem] earliest time<br/>reads as before the deadline"| W["Ordinary cancellation"]
T3 -.->|"[Fix] cancellation record's time<br/>is after the deadline"| OK["Expired"]
The earliest record is 14:00, which is before the 15:00 deadline. So the consumer classifies it as “cancelled before the deadline” and sends “ordinary cancellation”. The cancellation actually happened at 15:10.
A processing batch is only “the records read together after one signal”. Nothing guarantees they come from the same event. So the minimum over the whole batch may not be the time of the cancellation you are classifying.
Before fixing it, I wrote this counterexample as failing tests and confirmed they failed the way the review predicted. Then I switched to the cancellation record’s time. The opposite case is pinned by a test too: the cancellation is before the deadline and an unrelated record comes after it.
6. Verification scenarios
For the integration checks, I ran the consumer in a local integration environment, inserted outbox records by hand, and sent the signals. These checks cover the consumer’s behavior, not the whole path from the producer. S1 and S2 were also checked on a non-production server through the real cancel path.
| Scenario | Situation | Event sent |
|---|---|---|
| baseline (before) | The batch job cancels after the deadline | Ordinary cancellation |
| S1 | The batch job cancels after the deadline | One “expired”, no ordinary cancellation |
| S2 | A support agent cancels before the deadline | Ordinary cancellation |
| S3 | Only re-fetch records, no cancellation record. An external system cleaned up first | ”Expired” |
| S4 | The sales channel’s explicit cancellation record and an unrelated record in the same batch | One ordinary cancellation |
| S5 | The same cancellation processed again | No new event |
7. When to use this approach and when not to
7.1 Decision Matrix
Check two things first. Does the data the consumer reads contain everything the classification needs? And is the unit you judge (one order) the same unit the receiver wants events for? If either answer is no, the consumer cannot make this decision. If both are yes, compare the two approaches with the table below.
| Condition | Consumer classifies the transition | Producer passes a reason |
|---|---|---|
| The classification needs “who did it” | Not possible (the data cannot tell) | Required |
| The shared producer has many callers and a wide regression risk | Better | Worse |
| The same outcome also happens outside our code (an external system cleans up) | Better | Needs another path |
| Sub-units are cancelled separately and the receiver wants an event per unit | Must track each unit’s transition | Must pass a reason per unit |
| The consumer always has the previous state | Better | No difference |
The producer-side approach can also keep the one-decider principle: every producer path passes a reason, and the consumer only forwards it. What matters is not the location but that exactly one place decides.
7.2 Self-check list
- Every value the classification needs is already in the data the consumer reads
- You can state the rule as “what changed into what, under which conditions”, not “who did it”
- The consumer stores the previous state for each order
- It is decided whether an explicit event or a derived event wins
- Time comparisons use the time of the record that recorded the fact. If you use a fallback, you know which way its error leans
- A separate mechanism, such as a deterministic id, prevents duplicates from retried sends
8. Limits of this post
- There are no production numbers. Five integration checks and two non-production checks are all there is.
- Orders whose sub-units are cancelled separately are outside the verified range.
- When the state change and the record of an explicit event commit separately, the consumer can see the state transition before the explicit event. To use this approach, confirm that the state and its explicit context are observed together. I did not verify that case.
- This approach needs the previous state of whatever it classifies. Orders with no previous state are not classified.
- Changes made by an external system can be classified only after we observe them.
- This approach only names a change that already happened. It cannot stop a cancellation that should not have run. That has to be prevented on the producer side.
9. FAQ
Q. Should a business rule live in the consumer?
The consumer already decides what changed. This rule can also be stated as a state transition with conditions: an unpaid order disappeared after its deadline. That keeps it within the consumer’s job. Once who did it starts to change the meaning, this reasoning stops holding, and the producer should pass a reason.
Q. With a deduplication key, can’t two places decide?
If you define a key for the business transition, such as “this order: unpaid → cancelled”, and both places register it atomically, you can stop two events from being created even when their types differ. But the key does not tell you which type is right. Whoever registers first wins, so a wrong classification that arrives first is the one that stays. You still have to agree on a priority between the two deciders. With one decider, you need neither a key to coordinate deciders nor that agreement. You still need an id that filters duplicates from retried sends.
Q. What if the real cancellation time is unknown?
That is the case with only re-fetch records and no cancellation record. The consumer then uses a value at or after the time we found out. A booking cancelled just before the deadline but discovered after it can therefore be classified as “expired”. Before using a fallback like this, decide as a business rule whether that error is acceptable.
10. Wrapping up
When one outcome needs different names, the first question was not “where” but “in how many places”. With an outbox whose records commit one by one, two deciders made the result depend on timing. If the consumer already has the information the classification needs, classifying the state transition in that one consumer removes the race between independent deciders without touching the producer.
References
Design patterns
- Transactional outbox, microservices.io: storing a state change and its event record together. I used it to compare where this post’s cancel path departs from the pattern’s transaction condition.
- Idempotent Consumer, microservices.io: making repeated processing of the same message give the same result under at-least-once delivery. It connects to the deterministic id in section 3.
- What do you mean by “Event-Driven”?, Martin Fowler: the difference between events as notifications and events that carry state. It is background for a consumer that rebuilds state and compares it.