7
Back to Boss Battles

ObserverVSPub-Sub

The Problem

Scenario A β€” Observer territory: Your OrderService needs to notify InventoryService and BillingService when an order is placed. There are only 3 services, they live in the same process, and you want type-safe event handling with compile-time checks.

Scenario B β€” Pub-Sub territory: Your order microservice publishes events that 12 different services across 4 teams consume β€” analytics, fraud detection, shipping, loyalty points, etc. Services deploy independently. Some consumers don't exist yet.


Why They Look Alike

Both decouple the producer of an event from its consumers. Both let you add new consumers without modifying the producer. The flow looks the same: something happens β†’ interested parties react.

Rendering diagram…

The Core Difference

AspectObserverPub-Sub
CouplingSubject holds direct references to observersPublisher and subscriber don't know each other
BrokerNone β€” subject IS the dispatcherA message broker/bus sits between them
TypingStrong β€” observer interface enforced at compile timeLoose β€” messages are often serialized (JSON)
Process boundarySame processCan cross process/network boundaries
DeliverySynchronous (typically)Asynchronous (typically)
FilteringObserver gets all events from subjectSubscriber filters by topic/channel
Real-worldEventEmitter, RxJS Subject, DOM eventsRedis Pub/Sub, RabbitMQ, Kafka, SNS/SQS

One sentence: Observer is direct notification within a process; Pub-Sub adds a broker that decouples across boundaries.


Side-by-Side Code

Observer β€” NestJS EventEmitter (in-process)

typescript
1// Subject holds observers directly
2class OrderService {
3 private observers: OrderObserver[] = [];
4
5 subscribe(observer: OrderObserver): void {
6 this.observers.push(observer);
7 }
8
9 async placeOrder(order: Order): Promise<void> {
10 await this.orderRepo.save(order);
11 // Direct, synchronous notification
12 for (const obs of this.observers) {
13 obs.onOrderPlaced(order); // Subject knows each observer
14 }
15 }
16}
17
18interface OrderObserver {
19 onOrderPlaced(order: Order): void;
20}
21
22class InventoryObserver implements OrderObserver {
23 onOrderPlaced(order: Order): void {
24 this.decrementStock(order.items);
25 }
26}

Pub-Sub β€” Redis / Message Broker

typescript
1// Publisher knows nothing about subscribers
2class OrderService {
3 constructor(private messageBus: MessageBus) {}
4
5 async placeOrder(order: Order): Promise<void> {
6 await this.orderRepo.save(order);
7 // Fire and forget β€” no idea who listens
8 await this.messageBus.publish('order.placed', {
9 orderId: order.id,
10 items: order.items,
11 userId: order.userId,
12 });
13 }
14}
15
16// Subscriber registers independently, possibly in another service
17class InventorySubscriber {
18 constructor(private messageBus: MessageBus) {
19 this.messageBus.subscribe('order.placed', (event) => {
20 this.decrementStock(event.items);
21 });
22 }
23}
24
25// The bus is the broker β€” neither side references the other
26interface MessageBus {
27 publish(topic: string, payload: unknown): Promise<void>;
28 subscribe(topic: string, handler: (payload: unknown) => void): void;
29}

Decision Rules

SignalChooseWhy
Same process, few known consumersObserverSimpler, type-safe, no broker overhead
Cross-service or cross-process communicationPub-SubNeed network transport and decoupling
Consumers deploy independentlyPub-SubCan't hold direct references across deploys
Need guaranteed delivery / replayPub-SubBrokers offer persistence and retry
Type-safe compile-time contract between producer and consumerObserverDirect interface enforcement
Unknown or growing number of consumersPub-SubPublisher doesn't need to change
Simple in-app event (component A tells component B)ObserverNo reason to add a broker

The Trick Question

"Your NestJS app uses @OnEvent('order.created') with EventEmitter2. Is this Observer or Pub-Sub?"

It's Observer with Pub-Sub syntax. EventEmitter2 uses topic strings (pub-sub-like), but it's still in-process with direct function calls β€” no broker, no serialization, no network. It's Observer wearing a pub-sub costume. True Pub-Sub would involve Redis, RabbitMQ, or similar.


Interview Angles

Q: When would you migrate from Observer to Pub-Sub? When you extract a service into its own process (microservices). The observer pattern breaks across network boundaries because you can't hold a reference to a remote object. Add a message broker and switch to pub-sub.

Q: Can Pub-Sub guarantee ordering? Depends on the broker. Kafka guarantees ordering within a partition. RabbitMQ with a single consumer queue preserves order. Redis Pub-Sub does not guarantee delivery if a subscriber is offline. Observer in-process is naturally ordered (synchronous loop).

Q: What's the downside of Pub-Sub? Debugging is harder β€” you can't trace the call stack from publisher to subscriber. Messages can be lost, duplicated, or arrive out of order. Schema evolution is tricky (what if the publisher changes the payload shape?). Observer is simpler when you don't need the decoupling.

Q: How does NestJS handle both? EventEmitter2 for in-process observer. @nestjs/microservices with Redis/NATS/RabbitMQ transport for true pub-sub across services. The handler code looks similar, but the delivery mechanism is fundamentally different.