Skip to content
Exercise · Delivery guarantees · lesson 7 of 9

Exercise: an idempotent consumer

A payments consumer receives a message and adds its amount to a balance. With at-least-once delivery the same message can arrive again, and then the money is added twice. The broker in this exercise is a model in the tests file, not a real RabbitMQ: the same queue as in the previous exercise, plus the consumer loop consume, which acknowledges a message after calling Handle.

Fill in the Dedup type, the function NewDedup() *Dedup and the method func (d *Dedup) Handle(m Message, apply func(Message) error) error. The function apply performs the message's effect; in the tests, it adds the money.

Dedup follows three rules:

  • Handle passes a message with a new ID to apply, and skips a message whose ID was already applied: it does not call apply and returns nil;
  • if apply returns an error, Handle returns that error and does not remember the ID, so the message is applied when it is redelivered;
  • each Dedup remembers only its own messages.

Example:

  • the queue holds pay-1 for 100 and pay-2 for 50, and the balance is 0;
  • the consumer applies pay-1 and crashes before Ack, with the balance already at 100;
  • after q.Crash(), the message pay-1 arrives again, and Handle skips it;
  • pay-2 is applied, and the balance becomes 150.

In a real service the set of processed IDs is stored in the database and written in the same transaction as the effect itself: the lesson on exactly-once explains how.

Do not add extra imports unless the task says so explicitly.

dedup.go — go
go · 13 lines
Ctrl+Enter run · Esc leave editor