On this page

Observer Pattern

Every event listener, UI binding, reactive stream and webhook is a descendant of Observer. It's simple to sketch (a list of callbacks and a loop) and surprisingly easy to get wrong: listeners that are never removed, a slow subscriber that stalls the publisher, an exception in one handler that silently skips the rest, a notification that fires before the data it describes is saved. The behavioral patterns overview introduces the idea with a typed event emitter. This page goes further: a full implementation in Java, Python and TypeScript, then the design decisions interviewers actually probe.

Intent

Let an object (the subject) notify a changing set of dependents (observers) when something happens to it, without the subject depending on who they are or what they do.

The key word is without depending. The subject knows only that observers exist and share one small interface. It doesn't import the email service, the analytics client or the inventory module. Those depend on the subject instead. This inverts the direction of the dependency arrow, which is why Observer shows up whenever people talk about the dependency inversion principle or about keeping a core domain free of side concerns.

The problem

An order service starts simple: save the order. Then product asks for a confirmation email. Then inventory wants stock reserved. Then marketing wants loyalty points, and data wants an analytics event. Each request adds one more line to the end of the same method:

import java.util.*;

class EmailService { void sendConfirmation(String to, String orderId) { } }
class InventoryService { void reserve(List<String> skus) { } }
class LoyaltyService { void addPoints(String email, long points) { } }
class AnalyticsClient { void track(String name, Map<String, Object> props) { } }

class OrderService {
    private final Map<String, Long> orders = new HashMap<>();
    private final EmailService email;
    private final InventoryService inventory;
    private final LoyaltyService loyalty;
    private final AnalyticsClient analytics;

    OrderService(EmailService e, InventoryService i, LoyaltyService l, AnalyticsClient a) {
        email = e; inventory = i; loyalty = l; analytics = a;
    }

    void placeOrder(String orderId, String customerEmail, long totalCents, List<String> skus) {
        orders.put(orderId, totalCents);
        email.sendConfirmation(customerEmail, orderId);            // if this throws...
        inventory.reserve(skus);                                   // ...stock is never reserved
        loyalty.addPoints(customerEmail, totalCents / 100);
        analytics.track("order_placed", Map.of("id", orderId, "total", totalCents));
    }
}

What's wrong with it:

  • The order service knows everyone. Its constructor lists four collaborators that have nothing to do with placing an order. A fifth reaction means editing, retesting and redeploying the core class.
  • Failures cascade. If the email provider is down, sendConfirmation throws and the inventory is never reserved, even though the order was saved. One side concern breaks another.
  • Testing is noisy. Every test of order placement has to build or mock four unrelated services.
  • The dependency points the wrong way. The core domain (orders) depends on peripheral features (marketing, analytics). Peripheral features change far more often than the core.
  • Nothing can opt in or out at runtime. A feature flag to switch loyalty off for a region needs an if inside placeOrder.

The fix is to turn the four calls into four subscribers to an "order placed" event. The order service announces what happened; whoever cares reacts.

Structure

classDiagram
    class OrderEvents {
        -listeners: List~OrderListener~
        +subscribe(listener): Subscription
        +publish(event): List~Exception~
    }
    class OrderListener {
        <<interface>>
        +onOrderPlaced(event)
    }
    class Subscription {
        <<interface>>
        +close()
    }
    class OrderPlaced {
        <<record>>
        +orderId: String
        +customerEmail: String
        +totalCents: long
        +skus: List~String~
    }
    class OrderService {
        +placeOrder(...)
    }
    class EmailNotifier {
        +onOrderPlaced(event)
    }
    class InventoryReserver {
        +onOrderPlaced(event)
    }
    class LoyaltyPoints {
        +onOrderPlaced(event)
    }
    OrderService --> OrderEvents : publishes to
    OrderEvents o-- OrderListener : notifies 0..*
    OrderEvents ..> Subscription : returns
    OrderEvents ..> OrderPlaced : sends
    OrderListener <|.. EmailNotifier
    OrderListener <|.. InventoryReserver
    OrderListener <|.. LoyaltyPoints

The classic textbook version merges OrderEvents into the subject itself (OrderService.addListener(...)). Splitting it out, as here, keeps the subscription bookkeeping in one reusable place and keeps the domain class focused on orders. Either is a correct Observer.

Participants

ParticipantIn this exampleResponsibilities
Subject (publisher, observable)OrderEvents, used by OrderServiceKeeps the list of observers, adds and removes them, and notifies each one when something happens. Knows nothing about what they do.
Observer (listener, subscriber) interfaceOrderListenerThe one callback every observer implements. Its signature decides push vs pull (see below).
Concrete observerEmailNotifier, InventoryReserver, LoyaltyPointsReacts to the notification. Owns its own state and failure handling.
Event (optional but recommended)OrderPlacedAn immutable description of what happened, named in the past tense.
Subscription (optional but recommended)SubscriptionA handle that removes the observer. Makes cleanup hard to forget.

Implementation

The three versions share the same design decisions:

  • Subscribing returns a handle that unsubscribes. That handle is the main defence against leaks.
  • Notification iterates over a snapshot, so an observer can unsubscribe itself (or add another) during a notification without corrupting the loop.
  • One failing observer doesn't stop the others. Failures are collected and returned so the publisher can log them, rather than being swallowed or allowed to abort the loop.
  • The state change happens before the notification. Observers are told about something that has already happened.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

record OrderPlaced(String orderId, String customerEmail, long totalCents, List<String> skus) {
    OrderPlaced { skus = List.copyOf(skus); }
}

@FunctionalInterface
interface OrderListener {
    void onOrderPlaced(OrderPlaced event);
}

interface Subscription extends AutoCloseable {
    @Override void close();   // no checked exception, so try-with-resources is painless
}

final class OrderEvents {
    // Copy-on-write: iteration sees a snapshot, so listeners may (un)subscribe while being notified.
    private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();

    Subscription subscribe(OrderListener listener) {
        Objects.requireNonNull(listener);
        listeners.add(listener);
        return () -> listeners.remove(listener);
    }

    Subscription once(OrderListener listener) {
        Subscription[] handle = new Subscription[1];
        handle[0] = subscribe(e -> { handle[0].close(); listener.onOrderPlaced(e); });
        return handle[0];
    }

    /** Notifies every listener in subscription order. One failure does not stop the rest. */
    List<RuntimeException> publish(OrderPlaced event) {
        List<RuntimeException> failures = new ArrayList<>();
        for (OrderListener l : listeners) {
            try { l.onOrderPlaced(event); }
            catch (RuntimeException ex) { failures.add(ex); }
        }
        return failures;
    }

    int listenerCount() { return listeners.size(); }
}

final class OrderService {
    private final OrderEvents events;
    private final Map<String, OrderPlaced> orders = new HashMap<>();
    private final List<RuntimeException> failedReactions = new ArrayList<>();

    OrderService(OrderEvents events) { this.events = events; }

    void placeOrder(String orderId, String email, long totalCents, List<String> skus) {
        if (orders.containsKey(orderId)) throw new IllegalArgumentException("duplicate order " + orderId);
        OrderPlaced event = new OrderPlaced(orderId, email, totalCents, skus);
        orders.put(orderId, event);                     // 1. change state
        failedReactions.addAll(events.publish(event));  // 2. then announce it
    }

    List<RuntimeException> failedReactions() { return List.copyOf(failedReactions); }
}

// ---------- concrete observers: each owns its own state ----------
final class EmailNotifier implements OrderListener {
    final List<String> sent = new ArrayList<>();
    public void onOrderPlaced(OrderPlaced e) { sent.add(e.customerEmail() + ":" + e.orderId()); }
}

final class InventoryReserver implements OrderListener {
    final Map<String, Integer> reserved = new HashMap<>();
    public void onOrderPlaced(OrderPlaced e) { e.skus().forEach(s -> reserved.merge(s, 1, Integer::sum)); }
}

final class LoyaltyPoints implements OrderListener {
    final Map<String, Long> points = new HashMap<>();
    public void onOrderPlaced(OrderPlaced e) { points.merge(e.customerEmail(), e.totalCents() / 100, Long::sum); }
}

class Demo {
    public static void main(String[] args) {
        OrderEvents events = new OrderEvents();
        OrderService orders = new OrderService(events);
        EmailNotifier email = new EmailNotifier();
        InventoryReserver inventory = new InventoryReserver();
        LoyaltyPoints loyalty = new LoyaltyPoints();
        List<String> welcome = new ArrayList<>();

        events.subscribe(e -> { throw new IllegalStateException("analytics down"); }); // a broken observer
        events.subscribe(email);
        events.subscribe(inventory);
        Subscription loyaltySub = events.subscribe(loyalty);
        events.once(e -> welcome.add(e.customerEmail()));       // unsubscribes itself mid-notification

        orders.placeOrder("A1", "asha@example.com", 12_500, List.of("tee", "cap"));
        assert email.sent.equals(List.of("asha@example.com:A1"));
        assert inventory.reserved.equals(Map.of("tee", 1, "cap", 1));
        assert loyalty.points.get("asha@example.com") == 125;
        assert welcome.equals(List.of("asha@example.com"));
        assert orders.failedReactions().size() == 1;            // broken observer did not block the others

        loyaltySub.close();
        orders.placeOrder("A2", "asha@example.com", 4_000, List.of("tee"));
        assert loyalty.points.get("asha@example.com") == 125;   // no longer listening
        assert welcome.size() == 1;                             // once() fired once
        assert inventory.reserved.get("tee") == 2;

        int before = events.listenerCount();
        try (Subscription temp = events.subscribe(e -> { })) {
            assert events.listenerCount() == before + 1;
        }
        assert events.listenerCount() == before;                // scoped subscription cleaned up
        System.out.println("observer demo ok");
    }
}
from collections.abc import Callable
from dataclasses import dataclass
from typing import Protocol


@dataclass(frozen=True)
class OrderPlaced:
    order_id: str
    customer_email: str
    total_cents: int
    skus: tuple[str, ...]


class OrderListener(Protocol):
    def __call__(self, event: OrderPlaced) -> None: ...


Unsubscribe = Callable[[], None]


class OrderEvents:
    def __init__(self) -> None:
        self._listeners: list[OrderListener] = []

    def subscribe(self, listener: OrderListener) -> Unsubscribe:
        self._listeners.append(listener)

        def unsubscribe() -> None:
            if listener in self._listeners:
                self._listeners.remove(listener)

        return unsubscribe

    def once(self, listener: OrderListener) -> Unsubscribe:
        def wrapper(event: OrderPlaced) -> None:
            unsubscribe()
            listener(event)

        unsubscribe = self.subscribe(wrapper)
        return unsubscribe

    def publish(self, event: OrderPlaced) -> list[Exception]:
        failures: list[Exception] = []
        for listener in list(self._listeners):   # snapshot: safe to (un)subscribe during the loop
            try:
                listener(event)
            except Exception as exc:              # one broken observer must not stop the rest
                failures.append(exc)
        return failures

    def __len__(self) -> int:
        return len(self._listeners)


class OrderService:
    def __init__(self, events: OrderEvents) -> None:
        self._events = events
        self._orders: dict[str, OrderPlaced] = {}
        self.failed_reactions: list[Exception] = []

    def place_order(self, order_id: str, email: str, total_cents: int, skus: list[str]) -> None:
        if order_id in self._orders:
            raise ValueError(f"duplicate order {order_id}")
        event = OrderPlaced(order_id, email, total_cents, tuple(skus))
        self._orders[order_id] = event                     # 1. change state
        self.failed_reactions += self._events.publish(event)  # 2. then announce it


class EmailNotifier:
    def __init__(self) -> None:
        self.sent: list[str] = []

    def __call__(self, event: OrderPlaced) -> None:
        self.sent.append(f"{event.customer_email}:{event.order_id}")


class InventoryReserver:
    def __init__(self) -> None:
        self.reserved: dict[str, int] = {}

    def __call__(self, event: OrderPlaced) -> None:
        for sku in event.skus:
            self.reserved[sku] = self.reserved.get(sku, 0) + 1


class LoyaltyPoints:
    def __init__(self) -> None:
        self.points: dict[str, int] = {}

    def __call__(self, event: OrderPlaced) -> None:
        email = event.customer_email
        self.points[email] = self.points.get(email, 0) + event.total_cents // 100


def broken_analytics(event: OrderPlaced) -> None:
    raise RuntimeError("analytics down")


if __name__ == "__main__":
    events = OrderEvents()
    orders = OrderService(events)
    email, inventory, loyalty = EmailNotifier(), InventoryReserver(), LoyaltyPoints()
    welcome: list[str] = []

    events.subscribe(broken_analytics)
    events.subscribe(email)
    events.subscribe(inventory)
    stop_loyalty = events.subscribe(loyalty)
    events.once(lambda e: welcome.append(e.customer_email))

    orders.place_order("A1", "asha@example.com", 12_500, ["tee", "cap"])
    assert email.sent == ["asha@example.com:A1"]
    assert inventory.reserved == {"tee": 1, "cap": 1}
    assert loyalty.points["asha@example.com"] == 125
    assert welcome == ["asha@example.com"]
    assert len(orders.failed_reactions) == 1

    stop_loyalty()
    orders.place_order("A2", "asha@example.com", 4_000, ["tee"])
    assert loyalty.points["asha@example.com"] == 125
    assert welcome == ["asha@example.com"]
    assert inventory.reserved["tee"] == 2
    assert len(events) == 3
    print("observer demo ok")
function assert(cond: boolean, msg = "assertion failed"): asserts cond {
  if (!cond) throw new Error(msg);
}

interface OrderPlaced {
  readonly orderId: string;
  readonly customerEmail: string;
  readonly totalCents: number;
  readonly skus: readonly string[];
}

type Listener<E> = (event: E) => void;
type Unsubscribe = () => void;

class EventSource<E> {
  private listeners: Listener<E>[] = [];

  subscribe(listener: Listener<E>): Unsubscribe {
    this.listeners.push(listener);
    return () => { this.listeners = this.listeners.filter((l) => l !== listener); };
  }

  once(listener: Listener<E>): Unsubscribe {
    const unsubscribe = this.subscribe((e) => { unsubscribe(); listener(e); });
    return unsubscribe;
  }

  publish(event: E): unknown[] {
    const failures: unknown[] = [];
    for (const listener of [...this.listeners]) { // snapshot
      try { listener(event); } catch (err) { failures.push(err); }
    }
    return failures;
  }

  get size(): number { return this.listeners.length; }
}

class OrderService {
  private readonly orders = new Map<string, OrderPlaced>();
  readonly failedReactions: unknown[] = [];

  constructor(private readonly events: EventSource<OrderPlaced>) {}

  placeOrder(orderId: string, customerEmail: string, totalCents: number, skus: string[]): void {
    if (this.orders.has(orderId)) throw new Error(`duplicate order ${orderId}`);
    const event: OrderPlaced = { orderId, customerEmail, totalCents, skus: [...skus] };
    this.orders.set(orderId, event);                              // 1. change state
    this.failedReactions.push(...this.events.publish(event));     // 2. then announce it
  }
}

class EmailNotifier {
  readonly sent: string[] = [];
  readonly onOrderPlaced = (e: OrderPlaced): void => { this.sent.push(`${e.customerEmail}:${e.orderId}`); };
}

class InventoryReserver {
  readonly reserved = new Map<string, number>();
  readonly onOrderPlaced = (e: OrderPlaced): void => {
    for (const sku of e.skus) this.reserved.set(sku, (this.reserved.get(sku) ?? 0) + 1);
  };
}

class LoyaltyPoints {
  readonly points = new Map<string, number>();
  readonly onOrderPlaced = (e: OrderPlaced): void => {
    this.points.set(e.customerEmail, (this.points.get(e.customerEmail) ?? 0) + Math.floor(e.totalCents / 100));
  };
}

const events = new EventSource<OrderPlaced>();
const orders = new OrderService(events);
const email = new EmailNotifier();
const inventory = new InventoryReserver();
const loyalty = new LoyaltyPoints();
const welcome: string[] = [];

events.subscribe(() => { throw new Error("analytics down"); });
events.subscribe(email.onOrderPlaced);          // arrow-function fields keep `this` bound
events.subscribe(inventory.onOrderPlaced);
const stopLoyalty = events.subscribe(loyalty.onOrderPlaced);
events.once((e) => welcome.push(e.customerEmail));

orders.placeOrder("A1", "asha@example.com", 12_500, ["tee", "cap"]);
assert(email.sent.join() === "asha@example.com:A1");
assert(inventory.reserved.get("tee") === 1 && inventory.reserved.get("cap") === 1);
assert(loyalty.points.get("asha@example.com") === 125);
assert(welcome.length === 1);
assert(orders.failedReactions.length === 1);

stopLoyalty();
orders.placeOrder("A2", "asha@example.com", 4_000, ["tee"]);
assert(loyalty.points.get("asha@example.com") === 125);
assert(welcome.length === 1);
assert(inventory.reserved.get("tee") === 2);
assert(events.size === 3);
console.log("observer demo ok");

The TypeScript observers expose onOrderPlaced as an arrow-function field, so passing email.onOrderPlaced keeps this bound and gives a stable function identity for unsubscribing.

Push vs pull

The observer callback's signature decides how data reaches the observer.

  • Push. The subject sends everything the observer might need in the notification: onOrderPlaced(OrderPlaced event). The implementation above is push.
  • Pull. The subject sends only "I changed" (often with a reference to itself), and the observer calls getters to fetch what it wants: onChanged(Thermostat source).
PushPull
Observer needs a reference to the subjectNoYes
Data sentEverything, even fields this observer ignoresOnly what each observer asks for
CouplingTo the event's shapeTo the subject's getters
ConsistencyThe event is a snapshot of the moment it happenedThe observer reads current state, which may have moved on
Good forDomain events, anything async or cross-processCheap, frequent "something changed" UI refreshes

The consistency row is the one people forget. With pull, if an earlier observer changes the subject during notification, later observers read the newer value and never see the one that triggered their callback:

import java.util.*;

interface PullListener { void changed(Thermostat source); }
interface PushListener { void changed(int oldTenths, int newTenths); }

final class Thermostat {
    private int tenths;                                  // 21.5 C is stored as 215
    private final List<PullListener> pull = new ArrayList<>();
    private final List<PushListener> push = new ArrayList<>();

    void onPull(PullListener l) { pull.add(l); }
    void onPush(PushListener l) { push.add(l); }
    int tenths() { return tenths; }

    void set(int newTenths) {
        int old = tenths;
        if (old == newTenths) return;                    // no change, no notification
        tenths = newTenths;
        for (PushListener l : List.copyOf(push)) l.changed(old, newTenths);   // snapshot sent with the call
        for (PullListener l : List.copyOf(pull)) l.changed(this);             // observers read current state
    }
}

class Demo {
    public static void main(String[] args) {
        Thermostat t = new Thermostat();
        List<String> seen = new ArrayList<>();

        t.onPush((o, n) -> seen.add("push " + o + "->" + n));
        t.onPull(src -> { if (src.tenths() > 300) src.set(300); });          // a safety clamp that writes back
        t.onPull(src -> seen.add("pull " + src.tenths()));

        t.set(215);
        t.set(350);
        // The second pull observer never saw 350: the clamp changed state first.
        assert seen.equals(List.of("push 0->215", "pull 215", "push 215->350", "push 350->300", "pull 300", "pull 300"))
                : seen.toString();
        System.out.println("push vs pull ok");
    }
}

The final "pull 300" appears twice because the clamp's nested set(300) notified everyone, and then the outer loop carried on and notified the last observer again. Re-entrant notification like this is legal but confusing. Most production designs either forbid observers from modifying the subject during a notification, or queue changes and deliver them after the current round finishes.

The practical default is a hybrid: push an immutable event with the identifying fields and the values that changed (orderId, old status, new status), and let observers that need more look it up. java.beans.PropertyChangeEvent follows this shape: it carries the source, the property name and the old and new values.

Memory leaks from listeners

The most common Observer bug in long-running programs is the lapsed listener: an observer that is no longer wanted but is still subscribed. The subject's list holds a strong reference to the observer, and through it, to everything the observer references. A screen that was closed, a request handler that finished or a per-user widget can't be garbage-collected while a long-lived subject (an application-wide event source, a singleton store, a global window or process) still holds its callback. Each time the screen opens, another copy piles up, and each one keeps doing work on every event.

Symptoms: memory that climbs with usage and never falls back, handlers that run several times per event, or "ghost" updates to UI that no longer exists. Node's EventEmitter prints a MaxListenersExceededWarning when more than 10 listeners are added for one event by default, precisely because this is usually a leak.

The defences, roughly in order of preference:

  1. Tie the subscription to a lifetime and close it. Return a handle from subscribe and make closing it part of the owner's teardown: try-with-resources in Java, useEffect's cleanup function in React, a component's destroy hook, context manager exit in Python. The DOM's addEventListener accepts an { signal } option so that aborting one AbortController removes every listener registered with it.
  2. Use once for one-shot reactions so they remove themselves.
  3. Hold observers weakly when the subject genuinely can't know observers' lifetimes. The subject then doesn't keep observers alive by itself.
  4. Audit listener counts in tests: subscribe, tear down, assert the count is back where it started, as the Java demo above does.

Weak references deserve a closer look, because they help but have sharp edges. Here is the difference in Python, where weakref.WeakMethod refers to a bound method without keeping its object alive:

import gc
import weakref
from collections.abc import Callable


class StrongSubject:
    def __init__(self) -> None:
        self.listeners: list[Callable[[int], None]] = []

    def subscribe(self, fn: Callable[[int], None]) -> None:
        self.listeners.append(fn)

    def publish(self, value: int) -> None:
        for fn in list(self.listeners):
            fn(value)


class WeakSubject:
    def __init__(self) -> None:
        self.listeners: list[weakref.WeakMethod[Callable[[int], None]]] = []

    def subscribe(self, method: Callable[[int], None]) -> None:
        self.listeners.append(weakref.WeakMethod(method))  # bound methods only

    def publish(self, value: int) -> None:
        alive = []
        for ref in self.listeners:
            fn = ref()
            if fn is not None:
                fn(value)
                alive.append(ref)
        self.listeners = alive                              # prune dead observers lazily


class PriceWidget:
    def __init__(self) -> None:
        self.seen: list[int] = []

    def on_price(self, value: int) -> None:
        self.seen.append(value)


strong, weak = StrongSubject(), WeakSubject()

w1 = PriceWidget()
strong.subscribe(w1.on_price)
probe1 = weakref.ref(w1)
del w1
gc.collect()
assert probe1() is not None           # leaked: the subject keeps the widget alive

w2 = PriceWidget()
weak.subscribe(w2.on_price)
probe2 = weakref.ref(w2)
weak.publish(100)
assert probe2() is not None and probe2().seen == [100]   # type: ignore[union-attr]
del w2
gc.collect()
assert probe2() is None               # collected: the subject did not hold it
weak.publish(101)
assert weak.listeners == []           # dead reference pruned
print("weak listeners ok")

The sharp edges: a weakly held lambda that nobody else references is collected immediately, so the subscription silently vanishes (that's why the sample accepts bound methods only). Collection timing is up to the runtime, so a "dead" observer may still be called for a while in Java or JavaScript. JavaScript's WeakRef and FinalizationRegistry exist, but the language specification makes no promise about when or whether cleanup happens, so they're a safety net, not a substitute for unsubscribing. Weak references are a fallback for frameworks that can't know lifetimes; in application code, explicit unsubscription is clearer.

Synchronous vs asynchronous delivery

In the implementations above, publish calls each observer synchronously: placeOrder doesn't return until every reaction has run. That has real consequences, good and bad.

SynchronousAsynchronous (queued)
Publisher latencySum of all observers' timeJust the enqueue
Observer exceptionsReach the publisher (unless caught)Must be handled by the dispatcher, or they're lost
OrderingSubscription order, deterministicNot guaranteed unless the dispatcher preserves it
What observers seeThe world exactly as the publisher left itThe world some time later
Same transactionYes, so an observer's failure can roll the publisher backNo
DebuggingFull stack trace from publisher to observerStack starts at the dispatcher

A small TypeScript comparison makes the ordering difference concrete:

function assert(cond: boolean, msg = "assertion failed"): asserts cond {
  if (!cond) throw new Error(msg);
}

type Listener<E> = (event: E) => void;

class SyncEmitter<E> {
  private readonly listeners: Listener<E>[] = [];
  on(l: Listener<E>): void { this.listeners.push(l); }
  emit(e: E): void { for (const l of [...this.listeners]) l(e); }
}

class AsyncEmitter<E> {
  private readonly listeners: Listener<E>[] = [];
  constructor(private readonly onError: (err: unknown) => void) {}
  on(l: Listener<E>): void { this.listeners.push(l); }
  emit(e: E): void {
    for (const l of [...this.listeners]) {
      queueMicrotask(() => {           // each delivery runs after the publisher's current task
        try { l(e); } catch (err) { this.onError(err); }
      });
    }
  }
}

const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));

async function main(): Promise<void> {
  const log: string[] = [];

  const sync = new SyncEmitter<string>();
  sync.on((e) => log.push(`sync listener ${e}`));
  sync.emit("A");
  log.push("after sync emit");
  assert(log.join("|") === "sync listener A|after sync emit");

  log.length = 0;
  const errors: unknown[] = [];
  const queued = new AsyncEmitter<string>((err) => errors.push(err));
  queued.on(() => { throw new Error("boom"); });
  queued.on((e) => log.push(`async listener ${e}`));
  queued.emit("B");
  log.push("after async emit");
  assert(log.join("|") === "after async emit");          // nothing delivered yet
  await flush();
  assert(log.join("|") === "after async emit|async listener B");
  assert(errors.length === 1);                           // failure routed, publisher unaffected
  console.log("sync vs async ok");
}

main().catch((err) => { console.error(err); throw err; });

Two rules keep either style safe:

  • Announce after the change is durable. If the order is written in a database transaction and the event is delivered synchronously inside that transaction, an observer may send a confirmation email for an order that then rolls back. Deliver after commit. Spring's @TransactionalEventListener exists for exactly this. Across services, the transactional outbox is the robust version.
  • Decide who handles failures. Synchronous: catch per observer (as above) so one failure doesn't skip the rest, and decide whether any failure should fail the publisher. Asynchronous: the dispatcher needs an error channel, logging, and usually retries. Async delivery also means observers may receive the same event twice after a retry, so make them idempotent.

In an LLD interview, start synchronous (it's simpler and easy to reason about) and say what would make you switch: slow observers, observers that call the network, or a requirement that the publisher respond quickly.

Observer vs event bus

An event bus (also called a message bus or in-process pub-sub) puts a broker between publishers and subscribers. Publishers post to a topic or event type on the bus; subscribers register with the bus, not with the publisher.

Classic ObserverEvent bus
Who subscribers register withThe subject itselfThe bus
Who knows whomObservers know the subjectPublishers and subscribers know only the bus and the event types
RoutingOne subject, its own eventsMany publishers, routed by topic or type
Traceability"Who listens to this subject?" is a find-usages away"Who handles OrderPlaced?" needs a search or tooling

Observer is the right default inside one component or aggregate. A bus starts to pay off when many unrelated modules publish and consume many event types and you don't want each consumer to locate each producer. It's still Observer at heart; the bus is a Mediator that centralises the subscription lists. The event bus patterns page covers the distributed version.

EventEmitter and RxJS

Two JavaScript libraries are Observer in the form most engineers meet it.

Node's EventEmitter is a subject with named events. on (alias addListener) subscribes, off (alias removeListener) unsubscribes, once subscribes for a single delivery, and emit calls the listeners synchronously, in registration order, returning whether any listener existed. The "error" event is special: emitting it with no listener registered throws the error.

import { EventEmitter } from "node:events";
import assert from "node:assert/strict";

const orders = new EventEmitter();
const log = [];
const email = (order) => log.push(`email ${order.id}`);

orders.on("placed", email);
orders.once("placed", (order) => log.push(`first-order bonus ${order.id}`));

assert.equal(orders.emit("placed", { id: "A1" }), true);
orders.emit("placed", { id: "A2" });
assert.deepEqual(log, ["email A1", "first-order bonus A1", "email A2"]);   // sync, in order, once honoured

orders.off("placed", email);                      // needs the same function reference
assert.equal(orders.listenerCount("placed"), 0);
assert.equal(orders.emit("placed", { id: "A3" }), false);                   // nobody listening

assert.throws(() => orders.emit("error", new Error("db down")), /db down/); // unhandled "error" throws
console.log("event emitter ok");

RxJS generalises Observer into a stream. An Observable is a source of values over time; subscribe takes an observer with three callbacks (next for each value, error for a failure, complete when the stream ends) and returns a Subscription whose unsubscribe() stops delivery and runs the source's teardown logic. That error and completion channel is what plain Observer lacks: a classic observer never learns that the subject is finished or broken. Operators such as map, filter, debounceTime and takeUntil transform streams declaratively, and takeUntil(destroy$) is a common idiom for avoiding the lapsed-listener leak. A plain Observable is usually cold (each subscriber triggers its own execution), while a Subject is hot and multicasts one execution to many subscribers, which makes it the closest match to the classic pattern. An observable is also the push-based mirror image of an Iterator: an iterator lets the consumer pull the next value; an observable pushes the next value to the consumer.

Real-world uses

  • java.util.Observer and Observable. The JDK's original version, deprecated since Java 9. The deprecation note explains that its event model was too limited (an Object argument and no ordering guarantees) and that it wasn't safely usable from multiple threads; it points to java.beans and java.util.concurrent instead.
  • java.beans.PropertyChangeSupport and PropertyChangeListener, the JavaBeans mechanism behind many Swing models. Events carry the property name with old and new values.
  • Swing and AWT listeners: ActionListener, MouseListener and the rest all extend the marker interface java.util.EventListener.
  • The DOM: addEventListener / removeEventListener on any element, with once, passive and signal options.
  • Node.js EventEmitter, which streams, HTTP servers and sockets all extend.
  • Spring: ApplicationEventPublisher publishes events, beans react with @EventListener, and @TransactionalEventListener delays delivery until a transaction phase such as after commit.
  • Django signals such as post_save, which let apps react to model changes without the model knowing about them.
  • Reactive libraries: RxJS, RxJava, Project Reactor, and the java.util.concurrent.Flow interfaces that standardise reactive streams in the JDK.

When NOT to use it

  • There's one dependent and there will only ever be one. A direct method call is easier to read, debug and test. Observer adds indirection; spend it where there are several reactions or the set changes.
  • The publisher needs a result. If placeOrder must know whether payment succeeded before continuing, that isn't a notification, it's a call. Observers that return values, or a publisher that inspects observers' side effects, mean the workflow belongs in explicit code (or an orchestrator).
  • Order between reactions matters. "Reserve stock, then charge, then email" is a sequence, and relying on subscription order to enforce it is fragile. Write the sequence down, or use a Chain of Responsibility or a pipeline.
  • Reactions trigger more events that trigger more reactions. Cascades and feedback loops (A updates B, which notifies A) are hard to reason about and can loop forever. If you can't draw the event flow on a whiteboard, it's too implicit.
  • Every reaction must be atomic with the change. Synchronous observers in the same transaction can do this, but then a failing observer fails the business operation, and the decoupling was mostly an illusion. Be honest about which reactions are truly side effects.
PatternHow it relatesThe difference
MediatorBoth decouple senders from receivers.Observer is one-to-many broadcast with no logic in between; observers decide what to do. A mediator contains coordination logic and decides who should react and how. An event bus is a mediator built from observers.
Pub-sub / event busA generalisation of Observer.Adds a broker and topics so publishers and subscribers never reference each other. See the section above.
Chain of ResponsibilityBoth pass a request to several objects.In a chain, handlers are ordered and typically one handles the request (or each may stop it). In Observer, every observer is notified and none can stop the others.
CommandBoth are messages as objects.A command is a request for something to happen ("PlaceOrder") with usually one handler. An event is a statement that something did happen ("OrderPlaced") with any number of observers.
IteratorMirror images.An iterator lets the consumer pull values; an observable pushes them.
StrategyObservers are often passed as functions, like strategies.A strategy computes something the context needs; an observer reacts to something that already happened, and its result is ignored.

The smell that suggests it

  • A method that ends with a list of calls to unrelated services: save the order, then email, then reserve stock, then add points, then track analytics.
  • A core class whose constructor or imports include notification, analytics or caching clients. The dependency arrow points from core to periphery.
  • Adding a side feature requires editing the class that triggers it.
  • Polling. A loop that checks "has the price changed yet?" every second is usually waiting for a notification that should be pushed.
  • Feature flags around side effects inside a core method: if (loyaltyEnabled) loyalty.addPoints(...). With Observer, the flag decides whether to subscribe.

Interview questions

  1. "Push or pull: which would you choose for order events?" Push, with an immutable event that carries the order id and the fields that matter (total, skus, old and new status). Events are a snapshot of what happened, which matters if delivery is ever asynchronous: a pull observer reading the order later might see a newer state. Pull is fine for cheap UI "something changed, re-render" notifications.
  2. "One observer throws. What happens to the others?" In a naive loop, the exception aborts the loop and later observers are silently skipped. Catch per observer, collect or log the failures, and decide explicitly whether any of them should fail the publishing operation. In an async dispatcher, route failures to an error handler and consider retries.
  3. "How do listeners cause memory leaks, and how do you prevent them?" The subject holds strong references to its observers, so a long-lived subject keeps short-lived observers (and everything they reference) alive. Return an unsubscribe handle and tie it to the owner's lifetime, use once for one-shot reactions, test that listener counts return to baseline, and use weak references only as a fallback when lifetimes are unknowable.
  4. "Is notification synchronous or asynchronous in your design? Why?" Start synchronous: deterministic order, easy debugging, and failures are visible. Switch to queued delivery when observers are slow or do I/O, or the publisher must respond quickly, and accept the costs: no ordering guarantee without extra work, observers see later state, and you need an error channel and idempotent observers.
  5. "An observer modifies the subject while being notified. What can go wrong?" Iterating a list that's being modified can throw (ConcurrentModificationException in Java) or skip elements. Re-entrant notifications can deliver events out of order or deliver the same state twice. Iterate over a snapshot (or a copy-on-write list), and consider queuing changes made during a notification until the current round finishes.
  6. "How is Observer different from pub-sub?" In Observer, subscribers register with the subject directly, so they know it exists. In pub-sub, a broker or bus sits between them and routes by topic, so neither side knows the other. Pub-sub decouples more but makes the flow harder to trace.
  7. "How would you make your observer thread-safe?" Use a concurrent collection for the listener list (CopyOnWriteArrayList suits the usual "many notifications, few subscription changes" profile), publish immutable events, and remember that observers themselves run on the publisher's thread when delivery is synchronous, so their own state needs protecting if several publishers run concurrently.
  8. "When would you not use Observer?" When there's a single fixed dependent (call it directly), when the publisher needs a result or a guaranteed order of reactions (write the workflow explicitly), or when reactions must survive a crash (use a durable queue).

Further reading