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.
The Core Difference
| Aspect | Observer | Pub-Sub |
|---|---|---|
| Coupling | Subject holds direct references to observers | Publisher and subscriber don't know each other |
| Broker | None β subject IS the dispatcher | A message broker/bus sits between them |
| Typing | Strong β observer interface enforced at compile time | Loose β messages are often serialized (JSON) |
| Process boundary | Same process | Can cross process/network boundaries |
| Delivery | Synchronous (typically) | Asynchronous (typically) |
| Filtering | Observer gets all events from subject | Subscriber filters by topic/channel |
| Real-world | EventEmitter, RxJS Subject, DOM events | Redis 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)
| 1 | // Subject holds observers directly |
| 2 | class 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 | |
| 18 | interface OrderObserver { |
| 19 | onOrderPlaced(order: Order): void; |
| 20 | } |
| 21 | |
| 22 | class InventoryObserver implements OrderObserver { |
| 23 | onOrderPlaced(order: Order): void { |
| 24 | this.decrementStock(order.items); |
| 25 | } |
| 26 | } |
Pub-Sub β Redis / Message Broker
| 1 | // Publisher knows nothing about subscribers |
| 2 | class 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 |
| 17 | class 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 |
| 26 | interface MessageBus { |
| 27 | publish(topic: string, payload: unknown): Promise<void>; |
| 28 | subscribe(topic: string, handler: (payload: unknown) => void): void; |
| 29 | } |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| Same process, few known consumers | Observer | Simpler, type-safe, no broker overhead |
| Cross-service or cross-process communication | Pub-Sub | Need network transport and decoupling |
| Consumers deploy independently | Pub-Sub | Can't hold direct references across deploys |
| Need guaranteed delivery / replay | Pub-Sub | Brokers offer persistence and retry |
| Type-safe compile-time contract between producer and consumer | Observer | Direct interface enforcement |
| Unknown or growing number of consumers | Pub-Sub | Publisher doesn't need to change |
| Simple in-app event (component A tells component B) | Observer | No 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.