7
Back to Boss Battles

ObserverVSMediator

The Problem

Scenario A β€” Observer territory: You are building an order service. When an order is placed, several independent systems must react: inventory decrements stock, billing generates an invoice, notifications sends an email, and analytics logs the event. The order service should not know or care what happens downstream β€” it just broadcasts "order placed."

Scenario B β€” Mediator territory: You are building a chat room. When User A sends a message, the room must check if User B is online, format the message for User B's client type (web vs mobile), throttle if User A is spamming, and log the exchange. The interaction logic lives in the coordination, not in any single participant.


Why They Look Alike

Both patterns decouple objects that need to communicate. Neither sender nor receiver holds a direct reference to the other's concrete class.

Rendering diagram…

Both have a central object (Subject / Mediator) that knows about participants. Both let you add participants without modifying existing ones. The difference is in who holds the interaction logic.


The Core Difference

AspectObserverMediator
DirectionOne-to-many broadcastMany-to-many coordination
Logic locationEach observer decides what to doMediator contains the coordination logic
Subject awarenessSubject does not know what observers doMediator knows the protocol between colleagues
CouplingObservers are independent of each otherColleagues communicate only through mediator
AnalogyNewsletter β€” publisher sends, subscribers reactAir traffic control β€” planes talk through tower

Observer: The subject fires an event. Each observer independently decides how to react. The subject has zero knowledge of what happens next.

Mediator: The mediator receives a message from one colleague and decides what to do β€” routing, transforming, filtering, orchestrating responses across multiple colleagues. The logic is in the mediator.


Side-by-Side Code

Observer approach β€” Order events

typescript
1interface OrderObserver {
2 onOrderPlaced(order: Order): void;
3}
4
5class OrderService {
6 private observers: OrderObserver[] = [];
7
8 subscribe(observer: OrderObserver): void {
9 this.observers.push(observer);
10 }
11
12 placeOrder(order: Order): void {
13 // Core logic
14 this.save(order);
15 // Broadcast β€” we don't know or care what happens
16 for (const obs of this.observers) {
17 obs.onOrderPlaced(order);
18 }
19 }
20}
21
22// Each observer is independent
23class InventoryObserver implements OrderObserver {
24 onOrderPlaced(order: Order): void {
25 this.decrementStock(order.items);
26 }
27}
28
29class BillingObserver implements OrderObserver {
30 onOrderPlaced(order: Order): void {
31 this.generateInvoice(order);
32 }
33}
34
35class NotificationObserver implements OrderObserver {
36 onOrderPlaced(order: Order): void {
37 this.sendEmail(order.userId, 'Order confirmed');
38 }
39}

Mediator approach β€” Chat room coordination

typescript
1interface ChatColleague {
2 id: string;
3 clientType: 'web' | 'mobile';
4 receive(message: FormattedMessage): void;
5}
6
7class ChatRoomMediator {
8 private participants = new Map<string, ChatColleague>();
9 private rateLimiter = new RateLimiter();
10
11 register(colleague: ChatColleague): void {
12 this.participants.set(colleague.id, colleague);
13 }
14
15 send(senderId: string, text: string, targetId: string): void {
16 // Mediator contains ALL the coordination logic
17 if (this.rateLimiter.isThrottled(senderId)) {
18 const sender = this.participants.get(senderId);
19 sender?.receive({ text: 'Slow down!', type: 'system' });
20 return;
21 }
22
23 const target = this.participants.get(targetId);
24 if (!target) return;
25
26 // Format per client type β€” mediator decides
27 const formatted = target.clientType === 'mobile'
28 ? { text, type: 'push' as const }
29 : { text, type: 'ws' as const };
30
31 target.receive(formatted);
32 this.logger.log(senderId, targetId, text);
33 }
34}

The Observer version: OrderService broadcasts, each observer reacts independently. The Mediator version: ChatRoomMediator contains routing, rate limiting, formatting, and logging logic β€” colleagues just send and receive.


Decision Rules

SignalChooseWhy
One thing happens, many systems react independentlyObserverEach reaction is self-contained
Multiple objects need coordinated communicationMediatorLogic lives in the coordination
Adding a new listener should require zero changes elsewhereObserverJust implement the interface and subscribe
The interaction protocol is complex (routing, filtering, ordering)MediatorCentralize the protocol
Objects don't need to know about each other at allObserverFully decoupled
Objects communicate but shouldn't have direct referencesMediatorMediator brokers the communication
Event-driven architecture (pub/sub, webhooks, EventEmitter)ObserverOne-to-many is the essence of events
UI form with cross-field validation (field A disables field B)MediatorFields coordinate through a form mediator

The Trick Question

"Your API gateway receives a request and must coordinate: authentication, rate limiting, request transformation, and routing to the correct microservice. Each step depends on the outcome of the previous one. Which pattern?"

This looks like Observer (one event, multiple handlers) but is actually Mediator (or its close cousin Chain of Responsibility). The key tell: each step depends on the previous one. Observer handlers are independent β€” they don't care about each other's results. Here, the gateway orchestrates a sequence with conditional logic between steps.

If the steps were independent (log the request AND check analytics AND warm the cache), that would be Observer territory.


Interview Angles

Q: Can you use both Observer and Mediator together? Yes. A Mediator can use Observer internally. Example: a ChatRoom mediator that also broadcasts "user joined" events to analytics observers. The mediator handles coordination logic; the observer handles independent side effects.

Q: How does NestJS EventEmitter relate to these patterns? EventEmitter2 in NestJS is Observer. @OnEvent('order.created') handlers are independent observers. If you need coordinated multi-step workflows (saga), you need a mediator/orchestrator, not just events.

Q: What's the risk of a "God Mediator"? If the mediator grows to contain all business logic, it becomes a God Object. The fix: split into focused mediators (ChatMediator, NotificationMediator) or switch to Observer for the parts that are truly independent.

Q: Observer vs EventEmitter vs Pub-Sub β€” are they the same? Observer: subject knows its observers directly. EventEmitter: same thing, string-keyed. Pub-Sub: a broker sits between publisher and subscriber (neither knows the other). Pub-Sub is closer to Mediator because the broker can add routing logic.