An event-sourced account resends its welcome email on every command — find and fix the bug
Customers complain that they get the welcome email again every time they deposit or withdraw money. Nobody re-sends it on purpose. The aggregate is loaded from its event stream before each command, as below.
Constraints: the email must go out once per opened account; delivery of events to subscribers is at-least-once.
type Account struct {
ID string
Email string
Balance int64
mailer Mailer
}
func (a *Account) Apply(e Event) {
switch e := e.(type) {
case Opened:
a.ID, a.Email = e.ID, e.Email
// greet the new customer
_ = a.mailer.Send(context.Background(), e.Email, "Welcome!")
case Deposited:
a.Balance += e.Amount
case Withdrawn:
a.Balance -= e.Amount
}
}
func (r *Repo) Load(ctx context.Context, id string) (*Account, error) {
history, err := r.store.ReadStream(ctx, id)
if err != nil {
return nil, fmt.Errorf("read stream %s: %w", id, err)
}
a := &Account{mailer: r.mailer}
for _, e := range history {
a.Apply(e)
}
return a, nil
}Find and fix the bug.
Apply runs on every load and replay, so Opened triggers the email each time the account is rebuilt. Keep Apply pure: Handle decides by emitting Opened, and a separate subscriber sends the email once per event, deduplicating by event id.
- Guarding the effect with an in-memory flag that resets on the next load
- Making the effect asynchronous instead of moving it out of
Apply - Sending from a subscriber without deduplication under at-least-once delivery
- Why must the subscriber deduplicate even though each event is stored only once?
- Where would a payment-provider call go if its result must become an event?
Solution
The cause. Apply is not an "event handler" but a step of the fold. It runs on every load of the aggregate, i.e. before every command, as well as on rebuilds and in tests. Every account's stream starts with Opened, so each deposit replays Opened again and sends the email again.
The fix separates three duties: Handle makes the decision and emits the event, Apply only changes state, and the external effect is performed by a subscriber to the log.
// The aggregate: no dependencies on the outside world
type Account struct {
ID string
Email string
Balance int64
}
func (a *Account) Apply(e Event) {
switch e := e.(type) {
case Opened:
a.ID, a.Email = e.ID, e.Email // ✅ state only
case Deposited:
a.Balance += e.Amount
case Withdrawn:
a.Balance -= e.Amount
}
}
// The subscriber: receives every new event at least once
type WelcomeMailer struct {
db *sql.DB
mailer Mailer
}
func (w *WelcomeMailer) On(ctx context.Context, eventID string, e Event) error {
opened, ok := e.(Opened)
if !ok {
return nil
}
// Deduplication: the event may have been redelivered
res, err := w.db.ExecContext(ctx,
`INSERT INTO sent_welcome (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID)
if err != nil {
return fmt.Errorf("mark welcome %s: %w", eventID, err)
}
if n, _ := res.RowsAffected(); n == 0 {
return nil // already sent
}
if err := w.mailer.Send(ctx, opened.Email, "Welcome!"); err != nil {
// remove the mark so a redelivery tries again
if _, delErr := w.db.ExecContext(ctx, `DELETE FROM sent_welcome WHERE event_id = $1`, eventID); delErr != nil {
return errors.Join(fmt.Errorf("send welcome: %w", err), delErr)
}
return fmt.Errorf("send welcome: %w", err)
}
return nil
}Why not a flag on the aggregate. An emailSent field lives only in memory: on the next load the aggregate is created anew, the flag is false again, and Apply(Opened) sends the email again. Making the flag an event (WelcomeEmailSent) is possible, but the decision to send must still be made outside Apply.
Why deduplication. The subscriber receives events at-least-once: a crash after Send but before the acknowledgement causes a redelivery. A mark keyed by event_id makes processing idempotent. A narrow window remains — a crash between Send and committing the mark yields a second email; for an email that is acceptable, while for money the effect is made idempotent on the receiver's side by the same key.