Event sourcing for billing systems, and how to do it right

2022-02-05 · 4 min read

a balance is a number someone will eventually ask you to explain. why does this bill say $12.40? who applied that refund? what did we know last tuesday?

billing is the textbook case for event sourcing. Fowler's definition is to capture every change to application state as a sequence of events, so the log tells you how you got to the current state, not only where you are. for money, thats the audit trail you need anyway.

this is the shape i landed on for a billing service. python, django, postgres, but nothing here depends on those.

The shape

Events are facts

an event is something that already happened, so it's immutable and named in the past tense. BillCreated, PaymentApplied, RefundApplied.

class DomainEvent(BaseModel):
    event_id: UUID = Field(default_factory=uuid4)
    timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    version: int = 1

    class Config:
        frozen = True

the version field matters more than it looks. i'll come back to it.

State is a replay

an aggregate is a pure state machine. it takes events and nothing else. no database, no clock, no network calls.

class Bill:
    def __init__(self, bill_id):
        self.bill_id = bill_id
        self.payments = 0
        self.balance = 0  # cents, signed. positive = customer owes us
        self.cancelled = False

    @property
    def status(self):
        if self.cancelled:
            return "paid" if self.payments else "unbillable"
        if self.balance <= 0 and self.payments > 0:
            return "paid"
        return "partially_paid" if self.payments else "unpaid"

    @singledispatchmethod
    def apply(self, event):
        raise NotImplementedError(type(event))

    @apply.register
    def _(self, event: PaymentApplied):
        self.payments += event.amount
        self.balance -= event.amount

two things i'd keep every time. status is derived, never stored, so it can't drift from the facts behind it. and money is integer cents with a signed balance, so overpaying is just a negative number instead of a special case.

a payment event records the result of the gateway call. replay never calls the gateway. Fowler makes the same point about external side effects, and it's the easiest way to get burned.

One transaction

the write path is the whole design in ten lines.

def apply_event(self, event, aggregate_id):
    with transaction.atomic():
        store.save(aggregate_id, event.event_name, json.loads(event.json()))
        aggregate = self.load(aggregate_id)      # replay from the store
        view = self.repository.upsert_view(aggregate)
        return aggregate, view

append the event, rebuild the aggregate, update the read view. all or nothing. i rebuild from the store instead of applying the new event in memory because it round-trips the event through serialization every time. a payload that wont deserialize fails right there, not three weeks later.

Reads come from views

the view is a plain table holding the aggregate's current state. queries hit that, not the event store. it's CQRS in Fowler's sense, a separate model for reading than for updating. he also warns it often adds risk, and i think thats fair. what kept it cheap for me is that the projection is synchronous. no queue, no eventual consistency, and a read right after a write sees it.

Events change shape

this is where event sourcing hurts if you skip it. you cant rewrite history, but the code that reads it keeps changing. so every event has a version, and old payloads get upgraded when they're read.

class PaymentApplied(DomainEvent):
    VERSION = 3

    @staticmethod
    def upcast_v1_v2(state):
        # renamed a field
        if "method_id" in state:
            state["payment_method_id"] = state.pop("method_id")

    @staticmethod
    def upcast_v2_v3(state):
        # added a field, old payments get a default
        state.setdefault("payment_identifier", None)

the part i like most: a check runs when the class is defined. bump VERSION without writing the matching upcaster and the app wont import. you find out at startup, not in the middle of a replay.

Doing it twice

billing gets redelivered messages and retried jobs. a payment must apply once. in farsi we say:

کار از محکم‌کاری عیب نمی‌کند

kar az mohkam-kari eyb nemikonad

literally: being thorough never hurt.

so the guard is deliberately redundant. inside the transaction, the domain rebuilds the aggregate and checks. if the bill is already paid it raises an idempotent error instead of appending a second payment. the message consumer treats that error as success and acks the message, so redelivery just ends quietly.

What i'd change

i'd be lying if i said it was finished.

  • concurrency leans on a row lock on the view, taken by the caller. the guard above is check-then-act, so it only holds because the caller remembered the lock. the stronger version is an expected-version check on append, so a stale writer fails at the store itself.
  • event identity is the class name. rename a class and every stored row of that type is orphaned. an explicit name and an alias map is cheap insurance.
  • every write replays the full stream. fine for a bill, which has a handful of events. wont be fine for everything, so snapshots are on the list.
  • docs drift. mine described columns the table doesn't have. i'd rather generate the docs from the model.

TLDR

store facts, derive state, write the event and the view in one transaction, and version every event from day one. then fix concurrency at the store, not by hoping every caller takes a lock.

Sources

  • Martin Fowler, Event Sourcing, martinfowler.com, December 2005
  • Martin Fowler, CQRS, martinfowler.com, July 2011
Written by a human, grammar checked by an agent.