Skip to Content
Mengty Learns
Design

Observer Pattern

Notify multiple subscribers automatically when a subject's state changes, without coupling the subject to concrete listeners.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

1. Intent

TL;DR

Define a one-to-many subscription mechanism so a Subject (publisher) can notify an arbitrary, runtime-configurable list of Observers (subscribers) whenever an event occurs, without knowing their concrete types.

2. Problem

Imagine you run a CI build pipeline. When a build finishes or fails, you want to write a structured log line, increment Prometheus metrics, and send a Slack alert on failure.

If BuildPipeline imports LogWriter, MetricsClient, and SlackWebhook directly and calls each one inside finishBuild(), your core runner becomes coupled to every reporting tool. Adding a PagerDuty alert or disabling Slack in local dev requires editing BuildPipeline itself.

Without Observer, BuildPipeline hardcodes every downstream consumer.

3. Solution

Give BuildPipeline a subscription list (subscribe, unsubscribe, notify) that only knows about a tiny BuildObserver interface (onBuildEvent(event)).

Each consumer (LogSubscriber, MetricsSink, SlackNotifier) implements BuildObserver and registers itself at startup—or detaches when no longer needed. When a stage completes, BuildPipeline simply loops over its active subscribers and calls onBuildEvent(event).

Observer vs Pub/Sub via a broker

People often use "Observer" and "Pub/Sub" interchangeably, but they operate at different boundaries:

AspectObserver patternPub/Sub (via broker)
CouplingSubject holds direct references to Observer interfacesPublisher and Subscriber never reference each other
DeliveryUsually synchronous, in-process method callsAsynchronous over a broker (Redis, Kafka, RabbitMQ)
Failure isolationA slow or throwing observer can block the subjectBroker buffers retries and dead-letter queues

4. Real-world analogy

5. Flow: watch it work

Observer Pattern: Subject → Notify → Observers

Overview of Observer Pattern: Subject → Notify → Observers. 6 steps.
Overview6 steps in this flow

Press Start or tap any step dot to trace the path.

▸All steps (6)

6. Structure

Subject depends only on the BuildObserver interface; concrete subscribers register at runtime.

7. Code

type BuildStatus = 'started' | 'succeeded' | 'failed';

interface BuildEvent {
  pipelineId: string;
  status: BuildStatus;
  durationMs: number;
}

// Observer interface
interface BuildObserver {
  onBuildEvent(event: BuildEvent): void;
}

// Subject (Publisher)
class PipelineRunner {
  private readonly observers = new Set<BuildObserver>();

  subscribe(observer: BuildObserver): () => void {
    this.observers.add(observer);
    return () => {
      this.observers.delete(observer);
    };
  }

  run(pipelineId: string, shouldFail = false): void {
    this.notify({ pipelineId, status: 'started', durationMs: 0 });
    const status: BuildStatus = shouldFail ? 'failed' : 'succeeded';
    this.notify({ pipelineId, status, durationMs: 1420 });
  }

  private notify(event: BuildEvent): void {
    for (const observer of this.observers) {
      observer.onBuildEvent(event);
    }
  }
}

// Concrete Observers
class LogSubscriber implements BuildObserver {
  onBuildEvent(event: BuildEvent): void {
    console.log(`[log] ${event.pipelineId}: ${event.status} (${event.durationMs}ms)`);
  }
}

class MetricsSink implements BuildObserver {
  onBuildEvent(event: BuildEvent): void {
    if (event.status !== 'started') {
      console.log(`[metric] build_duration_ms{status="${event.status}"} ${event.durationMs}`);
    }
  }
}

class SlackNotifier implements BuildObserver {
  onBuildEvent(event: BuildEvent): void {
    if (event.status === 'failed') {
      console.log(`[slack] ALERT: ${event.pipelineId} failed`);
    }
  }
}

// Usage
const runner = new PipelineRunner();
runner.subscribe(new LogSubscriber());
runner.subscribe(new MetricsSink());
const unsubscribeSlack = runner.subscribe(new SlackNotifier());

runner.run('web-app-main', true);
unsubscribeSlack(); // clean detach when no longer needed

8. When to use / when to avoid

When to use
  • A state change in one object must trigger updates in an unknown or dynamic set of other objects.
  • Subscribers need to attach and detach at runtime (e.g. temporary debug loggers, UI components).
  • You want core domain logic to emit facts without importing logging, metrics, or webhook clients.
When to avoid
  • There is only one fixed consumer—a direct function call or injected callback is simpler and easier to trace.
  • Subscriber execution order or transactional rollback is critical—Observer notifies in registration/arbitrary order.
  • You need cross-service durability, retries, or backpressure—use a message broker (Pub/Sub) instead.

When NOT to use it

Overengineering happens when you wire an event emitter between two modules that always have a 1:1 relationship. Replacing a direct metrics.record(duration) call with an event bus makes stack traces harder to follow and hides which code actually runs when a method is called.

Real-world example in this stack

In this site's diagram and flow components (components/flow/ and components/diagram/), the browser's IntersectionObserver and ResizeObserver APIs notify the component when a <Flow> scrolls into view (triggering lazy-loading of React Flow) or when its container resizes (re-running fitView).

9. How to implement

Separate core state from side effects

Identify the Subject (PipelineRunner) whose state changes other modules care about.

Define the Observer interface

Declare a minimal notification method (onBuildEvent(event)) carrying the event payload.

Add subscription management to the Subject

Store observers in a Set and return an unsubscribe() cleanup closure from subscribe().

Register concrete observers at composition time

Wire LogSubscriber, MetricsSink, and SlackNotifier at app startup rather than inside the Subject.

10. Pros / Cons

Pros
  • Open/Closed Principle: add new subscribers without modifying the Subject.
  • Establish and tear down relationships dynamically at runtime.
  • Keeps core business logic clean of cross-cutting side effects.
Cons
  • Notification order is not guaranteed and cascading events can be hard to debug.
  • Forgotten unsubscriptions cause memory leaks in long-lived processes.
  • A synchronous throwing observer can interrupt remaining subscribers unless isolated.

11. Relations

Observer vs Mediator

Observer distributes notifications one-to-many from a Subject; Mediator centralizes many-to-many coordination between peer components.

Observer vs Chain of Responsibility

Observer broadcasts to all subscribers simultaneously; Chain of Responsibility passes a request sequentially until one handler processes or stops it.

Observer vs Strategy

Strategy swaps a single algorithm that returns a result; Observer broadcasts state changes to zero or more independent listeners.

12. Check yourself

Check Yourself

1. How does the classic Observer pattern differ from Pub/Sub with a message broker?

2. Why is returning an unsubscribe function from subscribe() a good practice in TypeScript?

Sources