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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What is the Observer pattern and where have you used it?
- Side effects keep piling into placeOrder. What do you do?
- How do you make sure the SMS is sent only if the order really committed?
- What happens when a listener fails?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.