Skip to content
Forward Engineering
Go back

Same cancellation, different events: why I put event classification in one place with an outbox

- views

Table of contents

Open Table of contents

0. Same “cancelled”, but the receiver wanted different events

Here is one flight booking in time order. The times are for illustration.

TimeEvent
10:00A customer books in a sales channel’s app. Payment can come later. The payment deadline is 15:00
15:00The payment deadline. Payment is still accepted during this second
15:00:01No payment has arrived. A batch job calls the cancel function, which cancels the booking at the airline and updates our database
Right afterOur 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.

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

TermMeaning
ProducerThe side that changes state. Here, the cancel function and the features that call it
OutboxA 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)
ConsumerThe program that receives signals, reads outbox records and the order’s current state, compares it with the previous state, and builds outgoing events
SnapshotThe “last announced state” the consumer stores per order, one row per version
State transitionThe change between the snapshot and the current state. For example: “unpaid → cancelled”
Processing batchThe unprocessed outbox records for one order that the consumer reads together after one signal
Re-fetchAsking 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.

  1. If the sales channel itself asked for the cancellation, send “ordinary cancellation”. The requester already knows.
  2. 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.
  3. 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.

2. Why only one place should decide

2.1 How one cancellation becomes an event

  1. The cancel function changes the state, writes a cancellation record, and writes an outbox record.
  2. When a record commits, a “process this order” signal goes to Kafka.
  3. When the consumer receives a signal, it reads that order’s processing batch.
  4. The consumer rebuilds the order’s current state and compares it with the snapshot to find the state transition.
  5. 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.

StepDetector (end of re-fetch)Consumer
1Commits the record that changes the state to “cancelled”, sends a signal
2Reads processing batch A. Sees the transition “unpaid → cancelled”
3Commits the “expired” record, sends a signalBatch A has no “expired” record from the detector. Creates “expired” itself
4Reads 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

PlaceWhat it doesUpsideProblem
A. The producer passes a reasonThe batch job passes “deadline expired”, and the cancellation record keeps itThe side that acted announces it directlyEvery caller of the shared function must be reviewed. Cleanups by an external system need another path
B. Add a second detectorWhen a re-fetch finds the booking gone, it writes an “expired” record directlyNo change to the producer. Catches external cleanupsMisses our own batch cancellations, so two places decide (2.2)
C. The consumer classifies the state transitionCompares with the snapshot, finds “unpaid → cancelled or expired”, and checks the time and any explicit requestNo change to the producer. One rule covers every pathA 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.

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

  1. The order status changed. If there is no state transition, stop.
  2. 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.
  3. 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”.
  4. 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.
  5. 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.

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.

TimeEvent
14:00An unrelated record is written for this order. It is not processed yet
15:00The payment deadline
15:10The batch job cancels and writes a cancellation record
Just after 15:10The 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.

ScenarioSituationEvent sent
baseline (before)The batch job cancels after the deadlineOrdinary cancellation
S1The batch job cancels after the deadlineOne “expired”, no ordinary cancellation
S2A support agent cancels before the deadlineOrdinary cancellation
S3Only re-fetch records, no cancellation record. An external system cleaned up first”Expired”
S4The sales channel’s explicit cancellation record and an unrelated record in the same batchOne ordinary cancellation
S5The same cancellation processed againNo 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.

ConditionConsumer classifies the transitionProducer 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 riskBetterWorse
The same outcome also happens outside our code (an external system cleans up)BetterNeeds another path
Sub-units are cancelled separately and the receiver wants an event per unitMust track each unit’s transitionMust pass a reason per unit
The consumer always has the previous stateBetterNo 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

8. Limits of this post

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

Same series


Share this post on:

Next Post
Payment deadlines that keep moving: why I kept the timers in a MySQL ledger