Fix a projector on the message broker Kafka that applies balance events out of order and twice
The projector reads BalanceChanged events from a Kafka topic keyed by account_id (kafka-go) and updates balances in Postgres. Balances drift: events apply out of order, some are lost after restarts, an event published twice is applied twice. Constraints: keep per-account order, lose nothing on a crash, make repeats harmless; EventID is unique.
func (p *Projector) Run(ctx context.Context) error {
for {
m, err := p.reader.FetchMessage(ctx)
if err != nil {
return err
}
go func(m kafka.Message) {
var ev BalanceChanged
if json.Unmarshal(m.Value, &ev) != nil {
return
}
p.db.ExecContext(ctx, `UPDATE balances
SET amount = amount + $1 WHERE account_id = $2`,
ev.Delta, ev.AccountID)
}(m)
if err := p.reader.CommitMessages(ctx, m); err != nil {
return err
}
}
}Find and fix the bugs.
A goroutine per message breaks partition order, so one account's events race. The offset is committed before the update, so a crash or a failed update loses the event, and a duplicate reapplies the increment. Apply messages one by one, record the event id in an inbox inside the update's transaction, and commit the offset only after the DB commit.
- Adding a mutex around the update, which removes the data race but neither the reordering nor the duplicates
- Assuming Kafka never redelivers after a commit and ignoring duplicate publishes by the outbox relay
- Committing the offset before the database write commits
- How would you regain parallelism without losing per-account order?
- Where should a message that fails to decode go instead of stopping the projector?
Solution
The code has three bugs, and each breaks one requirement.
- A goroutine per message. All of one account's events sit in one partition in order, but the spawned goroutines run in arbitrary order. Two
UPDATEs for one account can swap. For a sum this is invisible, but for any event that depends on the previous state (a limit, a status, "last operation") it is not. A mutex does not help: it removes the data race but imposes no order. - Committing the offset before applying.
CommitMessagesis called right after the goroutine starts — before theUPDATEhas run. If the process crashes or theUPDATEfails (the error is silently ignored), the offset is already committed and the event never comes again. That is at-most-once, i.e. data loss. - A non-idempotent increment. The outbox relay publishes at least once, and Kafka can also redeliver after a rebalance.
amount = amount + $1adds the amount a second time on a repeat.
The fix: process messages sequentially in the loop, apply the effect in a transaction together with an inbox row, and commit the offset only after the database commit.
func (p *Projector) Run(ctx context.Context) error {
for {
m, err := p.reader.FetchMessage(ctx)
if err != nil {
return fmt.Errorf("fetch: %w", err)
}
// ✅ one message at a time: order within the partition is kept
if err := p.apply(ctx, m); err != nil {
// ✅ no offset commit — the message comes again after a restart
return fmt.Errorf("apply offset %d: %w", m.Offset, err)
}
// ✅ commit the offset only after the DB transaction commits
if err := p.reader.CommitMessages(ctx, m); err != nil {
return fmt.Errorf("commit offset %d: %w", m.Offset, err)
}
}
}
func (p *Projector) apply(ctx context.Context, m kafka.Message) error {
var ev BalanceChanged
if err := json.Unmarshal(m.Value, &ev); err != nil {
return fmt.Errorf("decode: %w", err) // in production — to a DLQ, not a stop
}
tx, err := p.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
`INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING`, ev.EventID)
if err != nil {
return fmt.Errorf("inbox: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("inbox rows: %w", err)
}
if n == 0 {
return nil // ✅ duplicate: the effect is already there, just commit the offset
}
if _, err := tx.ExecContext(ctx,
`UPDATE balances SET amount = amount + $1 WHERE account_id = $2`,
ev.Delta, ev.AccountID); err != nil {
return fmt.Errorf("apply balance: %w", err)
}
return tx.Commit()
}Throughput comes back through partitions, not goroutines per message: more partitions and more projector instances in the consumer group — each partition is still processed in order. Inside one process you can hand messages to workers by a hash of account_id, but then offsets may be committed only up to the lowest fully processed message. A message that fails to decode goes to a dead-letter queue and is committed; otherwise one "poison" message stops the partition forever.