Video in progress

How do you design event ordering for a bank ledger: is global ordering needed, or is per-entity enough? How do you choose the key?

Global ordering in Kafka is possible only with a single partition, and that kills scale; in fact it's rarely needed. Ordering per account is usually enough, with the key = accountId. For transfers that span two accounts, what you need isn't ordering but the transfer's own state machine and idempotent steps.

📖 Answer

I turn the "everything must be in order" requirement into a question: which invariant breaks if two events are processed in reverse order?

  • A debit and a credit on one account: order matters, because the balance can go negative or the overdraft rule can misfire. So you need ordering by accountId.
  • Operations on two different accounts: they don't depend on each other and can run in parallel.

The key = accountId. The partition count is chosen by throughput.

The tricky case is a transfer from A to B. It touches two partitions and has to be atomic across both. The solution is in the process, not in ordering:

  1. TransferRequested (key: transferId).
  2. A debit in account A's partition: AccountDebited(transferId), in order by A, after checking there are enough funds.
  3. A credit on account B: AccountCredited(transferId).
  4. If the credit fails, a compensation to A.

Every step is idempotent by transferId. This is a distributed version of "two-phase" double-entry.

The hot account problem: one big merchant account receiving thousands of credits per second. It chokes a single partition. The fix is sub-accounts (split the merchant account into 16 internal "buckets", with the balance being their sum) or applying credits in batches.

One more important point: ordering in Kafka is delivery order, not business time. If an event has a sequence (a monotonic number per account), the consumer can detect gaps and repeats itself. In systems like a ledger I trust this more than Kafka's guarantees, because it survives replication, an MM2 copy or a replay.