Published
- 6 min read
Observer Pattern in Java: Should the Order Call Email Itself?
Announce once and let anyone listen: by hand, with Spring events, and the default that still fails your payment.
Your interviewer asks: an order just got paid, and email, inventory and analytics all need to know. Should the order call all of them and notify?
If you said yes, that’s the trap. The order shouldn’t even know they exist. It announces that it got paid, and whoever cares listens. That is the Observer pattern, and it is the question the State pattern post ended on.
The version that calls everyone
Most of us start like this. The pay method calls email, inventory and analytics, one after another:
void pay(Order order) {
order.markPaid();
email.send(order);
inventory.reserve(order);
analytics.track(order);
}
That’s fine until marketing wants loyalty points, and you are editing this method again:
void pay(Order order) {
order.markPaid();
email.send(order);
inventory.reserve(order);
analytics.track(order);
loyalty.addPoints(order);
}
Two things are wrong here. Every team that wants to hear about a payment means another edit to the payment code,
and another reason to retest it. And if the email service is down, the payment fails with it: one send that
throws takes pay down too.
The Observer pattern
With the Observer pattern, the order stops calling them by name. Each team signs up as a listener, behind one interface:
interface OrderListener {
void onPaid(Order order);
}
The order keeps a list of listeners and tells everyone on it:
class Orders {
List<OrderListener> listeners =
new ArrayList<>();
void pay(Order order) {
order.markPaid();
for (var l : listeners) {
l.onPaid(order);
}
}
}
Orders mentions one type, OrderListener. It doesn’t know how many listeners there are or what they do. Loyalty
points? One more listener, and Orders isn’t touched:
/CodeVxDev
observer
java Observer.java
10:22:28
The textbook names are subject (the order, which announces) and observers (the listeners). You have used the
pattern for years under other names: a click handler on a button, a PropertyChangeListener, a webhook.
In Spring, you don’t even keep that list
Spring has the pattern built in. The order publishes an event, and Spring delivers it:
@Service
@RequiredArgsConstructor
class Orders {
private final
ApplicationEventPublisher pub;
void pay(Order order) {
order.markPaid();
pub.publishEvent(
new OrderPaid(order.id()));
}
}
OrderPaid is a plain record, and Lombok’s @RequiredArgsConstructor writes the constructor Spring injects
through. Any method marked @EventListener that takes an OrderPaid gets it:
@Component
class EmailListener {
@EventListener
void on(OrderPaid event) {
email.send(event.orderId());
}
}
There is no interface to implement and no list to register with. The new team adds one class of its own:
@Component
class LoyaltyListener {
@EventListener
void on(OrderPaid event) {
points.add(event.orderId());
}
}
What catches people in production
Here is the part that the class diagram hides. By default, Spring runs every listener in the same thread and
the same transaction as the payment. publishEvent returns only when the last listener has finished.
So the order no longer knows its listeners, but it still waits for them. If email is down, the payment still fails, just like before. The hand-written version behaves the same way, because its loop runs in the caller’s thread too:
/CodeVxDev
observer
java StillFails.java
10:22:28
The email listener threw, the stock listener after it never ran, and pay never reached its last line. In Spring,
that exception also rolls the payment’s transaction back.
The fix is two annotations on the listener that shouldn’t be able to hurt the payment:
@Async
@TransactionalEventListener
void on(OrderPaid event) {
email.send(event.orderId());
}
@Asyncruns the listener on another thread, so a slow or broken email can’t slow or failpay. It needs@EnableAsynconce in the application.@TransactionalEventListenerwaits for the commit (that is its default phase), so no email goes out for a payment that was rolled back.
Before you ship it
A few things the short version leaves out:
- Not every listener should be async. If the payment must not succeed unless stock was reserved, that listener belongs in the same transaction, and its failure should fail the payment. Decide per listener.
- No transaction, no event. A
@TransactionalEventListeneris skipped when nothing is in a transaction, unless you setfallbackExecution = true. It is the usual reason “my listener never fires” in a test. - Writing after the commit. The payment’s transaction is over by then, so a listener that saves something needs
one of its own:
@Transactional(propagation = Propagation.REQUIRES_NEW). - An async failure is silent. Its exception no longer reaches
pay, so nobody sees it unless you log it, retry it, or handle it in anAsyncUncaughtExceptionHandler. - Order isn’t promised. Listeners run in no particular order unless you add
@Order. If the order matters, you may not want listeners at all (see the trap below). - Events in memory can be lost. If the application stops between the commit and the listener, the event is gone. When that isn’t acceptable, save the event in the same transaction as the payment and publish it from there: the outbox pattern.
The code from this post runs in the companion repo on GitHub, with a real transaction behind
the Spring version. Most of these pitfalls are tests there that show the failure and then the fix: the rollback,
the listener that runs before the commit, the silent async failure and the skipped event. Clone it and run
./mvnw -pl behavioral/observer test.
Between services, it’s a Kafka topic
Inside one application the event travels through Spring. Between services the same idea becomes a topic: the order
service publishes order-paid, and the email, inventory and analytics services each subscribe with their own
consumer group. The order service still has no idea who’s listening.
What changes is everything around the call. Delivery is at least once, so a listener can see the same event twice and has to be safe to run twice. A listener that is down catches up later instead of failing the payment. And “saved the order but lost the event” is a real failure, which is again what the outbox pattern is for.
Spot it in LLD interviews
When one thing changes and many others need to react, and the thing that changed shouldn’t know who they are, think Observer:
| LLD question | What changes | Who listens |
|---|---|---|
| Order management | An order gets paid | Email, inventory, analytics |
| Notification service | A topic gets a post | Email, SMS and push senders |
| Stock ticker | A price moves | Alerts, charts, portfolios |
| Auction | A new highest bid | The other bidders |
| News feed / YouTube | A channel uploads | Its subscribers |
| Chat presence | A user comes online | The friends who have a chat open |
| Config / feature flag | A value changes | Every service holding a copy |
In the interview, name the event first (“order paid”, “price changed”), then show the listener interface and the loop, and say how a new listener gets added: one new class, and the publisher doesn’t change.
When not to use it
Observer is for telling, not for asking. If the caller needs an answer back, call the thing directly. And if the steps must run in a fixed order, or any of them must be able to stop the request, listeners are the wrong tool.
/CodeVxDev
observer
cat observer.md
10:22:28
The interview trap
Before an order is paid, it has to pass three checks, fraud, stock and coupon, and any of them can stop it. Is that Observer again?
A. Yes, Observer   B. No
Think about what a listener is allowed to do with an event. Leave A or B as a comment on the video; the next episode in this series answers it.