Skip to the page

Design patterns · mid

Observer and domain events

Observer lets one action tell many listeners without knowing them. When placeOrder keeps growing side effects, publish an OrderPlaced event and let listeners react after the commit.

The notes

What you must know

  • placeOrder saves the order and publishes OrderPlaced. An SmsListener, a LoyaltyListener and a RestaurantListener subscribe. The order code does not know them, and adding one does not touch it.
  • Split by need: things that must succeed with the order (stock reservation) stay in the transaction. Side effects (SMS, loyalty) run after commit and asynchronously, for example Spring TransactionalEventListener with AFTER_COMMIT.
  • Failure isolation: a failure in one listener is logged and retried and never rolls back the order.
  • Crash safety: use the outbox pattern (write the event in the same transaction, publish from the outbox) when the side effect must not be lost or crosses services.
  • Listeners must be idempotent, because events can be delivered twice.
  • Add the event id and order id to logs per listener, and add metrics on failures.
  • Library Observers: a Library returning a book notifies the next member in the reservation queue.

The red pen

Common traps: mistake → fix

  • Mistake: A synchronous event bus inside the transaction decouples the code

    Fix: it has the same coupling and hides it more.

  • Mistake: Fire-and-forget threads are fine

    Fix: events are lost on restart.

  • Mistake: Listeners can rely on each other order

    Fix: not unless that order is written down.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the Observer pattern and where have you used it?
  2. Side effects keep piling into placeOrder. What do you do?
  3. How do you make sure the SMS is sent only if the order really committed?
  4. What happens when a listener fails?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview