Skip to content

    Frontend System Design

    Observer, Pub/Sub and Mediator

    Three ways page objects learn about each other's changes: observer, in-page pub/sub and mediator. Learn who knows whom, what goes wrong, and how to pick one.

    By Published 13 min read

    • frontend-system-design
    • design-patterns
    • observer
    • events
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Design Patterns for Front Ends

    What you'll learn: By the end of this lesson you will be able to tell Observer, pub/sub and Mediator apart by who knows whom, state the dispatch rules of the DOM event system and why a safe subject copies its listener list, explain the difference between delivering a nested publish at once and queueing it, prevent listener leaks with one cleanup call, and keep the rules of a form in one mediator instead of spreading them across its fields.

    Think of three ways news travels. A magazine subscription: the publisher keeps your name on a list and posts each issue to you directly. A noticeboard with headings: anyone pins a note under "Lost and found" and anyone reading that heading sees it, and nobody knows who pinned it. An air-traffic controller: planes do not talk to each other, they all talk to the tower, and the tower holds the rules about who lands next.

    Those are Observer, pub/sub and Mediator. They look alike because each moves information from one object to another, and they are often mixed up. They differ in who knows whom, and that decides what breaks.

    The running example is a checkout page: an address form (country, state, postcode, a Pay button), an order summary and a cart badge in the header. The lab's names and lists are made up for the lesson.

    The core idea

    1. Observer: a subject holds a list of listeners and calls them. The listener knows the subject it subscribed to. Refactoring.guru describes the intent as a subscription mechanism to notify multiple objects about events that happen to the object they observe.
    2. Pub/sub: a named topic sits between the two sides. Neither side holds the other; they share only a topic name. In this lesson the bus lives in one page. The networked version, with its delivery limits, is in Presence and Pub/Sub.
    3. Mediator: the parts talk only to one object that holds the rules. Refactoring.guru's intent is to reduce chaotic dependencies between objects by restricting direct communication so that they collaborate only through the mediator.
    4. All three fail in the same few ways: a list changed during a loop, a listener that was never removed, an error in one listener, and a delivery that is re-entered.

    Three illustrations run through the lesson: a minimal example (a subject with three listeners), a realistic example (the checkout page: a mediator for the form, a bus for the cart) and a failure example (a listener that removes itself and makes its neighbour miss the news, and a handler that publishes while a delivery is running).

    It builds on Design Patterns for Front Ends, which defines patterns and their costs. The later event-driven UI lesson takes the bus to a whole app.

    Observer: a list and a loop

    The platform ships Observer. MDN defines EventTarget as the interface of objects that can receive events and may have listeners for them, with addEventListener(), removeEventListener() and dispatchEvent(). Element, Document and Window are the most common targets, but other objects can be too, and you can write your own: MDN's example is a Counter class that extends EventTarget and dispatches a valuechange event.

    Figure 1. Observer: the subject holds the list

    Observer: the cart store holds its list of listeners and calls each oneCart store to Header badge (notify); Cart store to Order summary (notify); Cart store to Analytics (notify)Cart store: the subjectCart storethe subjectHeader badge: listenerHeader badgelistenerOrder summary: listenerOrder summarylistenerAnalytics: listenerAnalyticslistenernotifynotifynotify

    How to read this: the store calls every listener it holds, one after another. Each listener had to find the store to subscribe, so it knows who it is listening to.

    What happens when a listener changes the list while the store is looping over it? The DOM Standard is explicit. Its invoke algorithm takes a clone of the target's listener list, and a note says this avoids running listeners added after that point. It then iterates only the listeners whose removed flag is false, so a listener removed during dispatch is skipped. If a listener's callback throws, the exception is reported and dispatch continues. MDN says the same about additions: a listener added during processing of the event does not trigger for that event. Node's EventEmitter calls listeners synchronously in the order registered, and its documentation says a removeListener() call after emitting but before the last listener finishes does not remove the listener from the emit in progress.

    The lab's Subject copies these rules: it works on a copy of its list, skips a listener removed meanwhile, does not call one added meanwhile, and collects the errors of throwing listeners. NaiveSubject loops over the live array instead, and the difference shows in the first section of the demo.

    Expected output, captured from a real run (Node 26.13.1; section 1 and section 2 of the demo):

    === 1. Observer: what happens when a listener changes the list during a notification
    naive loop, a removes itself:        called a,c (b was skipped)
    copy of the list, a removes itself:  called a,b,c
    a removes b and adds "late":         first notify a; second notify a,late
    b throws:                            called a,c; errors: listener b failed
    
    === 2. Pub/sub: a handler publishes while a delivery is running (sync versus queued)
    sync  : h1(a:x) h3(b:from h1) h2(a:x)
    queued: h1(a:x) h2(a:x) h3(b:from h1)

    This is the minimal example and the first failure example. In the naive loop, a removes itself, the array shifts left, and the index moves on past b, so b never hears the news. Refactoring.guru lists a related con of the pattern: "subscribers are notified in random order". The DOM and Node both fix the order, but a design that depends on it is fragile.

    Pub/sub: topic names in the middle

    A bus removes the direct reference. A publisher calls emit("cart:changed", payload) and a subscriber calls on("cart:changed", handler); neither holds the other. In the lab, EventBus is a map from topic name to a Subject, with a type that ties each topic name to its payload type, so a typo or a wrong payload fails at compile time.

    Figure 2. Pub/sub: publishers and subscribers share only a topic name

    In-page pub/sub: publishers and subscribers share only a topic nameAddress form to Event bus (emit); Cart store to Event bus (emit); Event bus to Header badge (cart:changed); Event bus to Analytics (cart:changed)Address form: publisherAddress formpublisherCart store: publisherCart storepublisherEvent bus: topic namesEvent bustopic namesHeader badge: subscriberHeader badgesubscriberAnalytics: subscriberAnalyticssubscriberemitemitcart:changedcart:changed

    How to read this: removing a subscriber changes nothing for the publisher. The price is that nothing in the code says who is listening, so you find out with a search or a log.

    Two delivery choices matter when a handler publishes while a delivery is running. In sync mode the nested publish is delivered at once, in the middle of the outer delivery. In queued mode it waits until the outer delivery has reached every handler.

    Figure 3. A nested publish, delivered at once and queued

    sequenceDiagram accTitle: Nested publish in sync mode and queued mode accDescr: Topic a has two handlers, h1 and h2, and topic b has handler h3. Handler h1 publishes b while it runs. In sync mode h3 runs before h2, so h2 sees topic a after the state has already moved on. In queued mode h2 runs first and h3 runs after the whole delivery of a is finished. participant P as Publisher participant B as Bus participant H1 as h1 on a participant H2 as h2 on a participant H3 as h3 on b P->>B: emit a B->>H1: deliver a H1->>B: emit b Note over B,H3: sync: delivered at once B->>H3: deliver b B->>H2: deliver a Note over B,H3: queued: h2 first, h3 after

    How to read this: in sync mode the handlers run in the order h1, h3, h2. In queued mode they run h1, h2, h3. The second order is the one most handlers expect.

    The two lines of section 2 above are exactly this. Neither mode is wrong: sync is simpler (depth first), queued costs a queue (breadth first). A handler that reads the payload it was given can be stale under sync, because the nested publish may already have changed the state. A handler that reads the current state is safe in both.

    An event on the DOM is also a form of pub/sub through the tree: MDN's event delegation puts one listener on a parent and lets events bubble up from the children, using event.target to find the origin. That is the right tool for a long list of rows; see DOM Events and Delegation.

    Mediator: the rules in one place

    Refactoring.guru's Mediator example is the form: checking a box may reveal a field, and a submit button may need to validate every field, and putting that logic in each element couples the elements. The solution is that each element notifies a mediator, which decides what else should respond. A submit button then depends on the dialog, not on a dozen fields. The cons it lists: over time a mediator can evolve into a God Object. It adds that a common mediator uses Observer inside, but the goals differ: Mediator centralises mutual dependencies, Observer creates one-way, dynamic links.

    Figure 4. Mediator: fields report changes and the mediator applies the rules

    Mediator: each field reports to one object, and that object decides what else changesCountry to Checkout mediator (changed); State to Checkout mediator (changed); Postcode to Checkout mediator (changed); Checkout mediator to Pay button (enable)Country: fieldCountryfieldState: fieldStatefieldPostcode: fieldPostcodefieldCheckout mediator: the rulesCheckoutmediatorthe rulesPay button: on or offPay buttonon or offchangedchangedchangedenable

    How to read this: each field has one link, to the mediator. The rule "changing the country clears the state" is written once, in the mediator, and not inside any field.

    In the lab, Field objects call mediator.changed(this) when a user sets them. CheckoutMediator holds three rules: a new country clears the state and postcode, the state field is on only for a country that has states in the made-up list, and Pay is on only when the postcode and any required state are filled.

    Expected output, captured from a real run (Node 26.13.1; section 4 of the demo):

    === 4. Mediator: a checkout form whose fields know nothing about each other
    start:                 country=- state=-(off) postcode=-(off) pay=off
    type a postcode early: country=- state=-(off) postcode=-(off) pay=off (ignored: the field is off)
    country US:            country=US state=- postcode=- pay=off
    state CA, postcode:    country=US state=CA postcode=94105 pay=on
    country DE:            country=DE state=-(off) postcode=- pay=off
    DE postcode:           country=DE state=-(off) postcode=10115 pay=on
    country IN (resets):   country=IN state=- postcode=- pay=off
    notifications handled by the mediator: 6
    n= 4 objects: up to 6 direct links, 4 through a mediator
    n= 8 objects: up to 28 direct links, 8 through a mediator
    n=12 objects: up to 66 direct links, 12 through a mediator

    The last three lines are arithmetic, not a measurement: n objects that may each talk to every other need up to n(n-1)/2 links, and through one mediator they need n. The cost is the one Refactoring.guru names: the mediator knows everything, so give it one job, such as one form.

    Listeners that never leave

    A subscription outlives the code that made it unless someone removes it. MDN's addEventListener says the once option removes the listener after it runs, and the signal option removes it when the owning AbortController is aborted. It also notes that a new anonymous function is never identical to an earlier one, so repeated calls with anonymous functions add repeated listeners, and you cannot remove one without keeping a reference. Node warns about this: by default more than 10 listeners for one event produce a "possible EventEmitter memory leak" warning, a limit that is not hard. React's useSyncExternalStore makes cleanup part of the contract: subscribe receives a callback and returns a function that cleans up, and React resubscribes if you pass a different subscribe function between renders. See also Memory Management and Leaks.

    The lab's Scope collects the unsubscribe functions a component creates and releases them in one dispose() call. Section 3 of the demo shows a panel that subscribes each time it is shown.

    Expected output, captured from a real run (Node 26.13.1; section 3 of the demo):

    === 3. Lifecycle: a panel subscribes to "price" every time it is shown
    without dispose(): 3 panels shown and hidden, listeners left=3, handlers run by one price event=3
    with dispose()   : 3 panels shown and hidden, listeners left=0, handlers run by one price event=0

    Choosing

    Figure 5. Which of the three?

    flowchart TD accTitle: Choosing between observer, pub/sub and mediator accDescr: If one known object has news for several listeners, use an observer. If the publishers and subscribers should not know each other, use a topic bus. If several objects must coordinate with rules that involve more than one of them, such as the fields of a form, use a mediator. If only two objects are involved, a plain function call is enough. Q{"What is the relationship?"} -->|"one known source, several listeners"| O["Observer
    (subject and listeners)"] Q -->|"sources and listeners should not know each other"| B["Pub/sub
    (typed topics)"] Q -->|"several parts need shared rules"| M["Mediator
    (one rule holder)"] Q -->|"just two objects"| F["A function call"]

    How to read this: pick by who should know whom. If the answer is "just these two", none of the three is needed.

    Choice Gain Cost
    Observer Direct, easy to follow, one list per subject Listeners know the subject; lifecycle is the listener's job
    Pub/sub bus Publishers and subscribers are independent Nothing names the receivers; topic strings can drift
    Mediator Rules in one place, parts reusable Can grow into a God Object
    Function call Least code Tight link between two objects

    Build it: a subject, a bus and a form mediator

    Goal. See what a safe subject does that a naive loop does not, the order of a nested publish in two delivery modes, the effect of cleanup, and a mediator holding the rules of a form.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no browser, no DOM, no timer.

    cd examples/frontend
    pnpm install
    cd labs/observer-bus-mediator
    pnpm test           # 21 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo.
    2. In section 1, find which listener the naive loop skips, and why the copy of the list does not.
    3. In section 2, compare the order of h2 and h3 in the two modes.
    4. In section 3, compare "listeners left" with and without dispose().
    5. In section 4, find the line where the mediator ignores input to a disabled field, and the line where changing the country clears the form.

    What the lab does not show. No real DOM, no browser event loop and no network. Subject copies the DOM Standard's rules for one list; it is not the browser's code. The bus is in memory, in one page, and says nothing about delivery across tabs or servers.

    Break it. In test/lab.test.ts, the test "the naive loop skips the listener after one that removes itself (the bug)" uses NaiveSubject. Change it to Subject and the expected ["a", "c"] fails, because all three listeners are called. Change it back.

    In practice: the cart badge that went back in time

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The checkout page's address fields call each other directly: the country field resets the state field, enables the postcode field and updates the Pay button. Support reports orders shipped with a state from the previous country. Separately, the cart badge in the header sometimes shows the previous count for a moment after an update (illustrative).

    Starting architecture

    Figure 6. Starting point: fields hold each other

    Starting architecture: every field holds references to the others and to the Pay buttonCountry to State (reset); Country to Postcode (enable); State to Pay button (update); Postcode to Pay button (update); Country to Pay button (update)Country: resets, enablesCountryresets, enablesState: knows postcodeStateknows postcodePostcode: knows PayPostcodeknows PayPay button: knows allPay buttonknows allresetenableupdateupdateupdate

    How to read this: each new rule adds a link between two fields. The stale state appears when one of the links is missing.

    Options considered

    Option What it fixes What it costs Risk
    Add the missing link The reported bug One more link The next rule needs the same hunt
    A form mediator All rules in one place A rewrite of the fields' wiring The mediator grows
    Mediator plus a typed bus for cart events, with scoped cleanup The form and the badge, and the cleanup rules A bus, a Scope per component A bus hides who listens

    The decision

    Field Decision record
    Context Rules between fields are spread over several fields, and cross-feature news (the cart) is wired by hand.
    Decision One mediator per form; a typed bus for cart:changed; every subscription is released through a scope; the bus delivers queued.
    Consequences, good The country rule is in one place with a test, and a new listener needs no change to the publisher.
    Consequences, bad A request to "see who listens" needs a search or a debug log.
    Revisit when A mediator needs more than one form's rules, or topics number in the dozens.

    Rollout and verification

    1. Write the mediator's tests first, from the bug reports: country change clears state and postcode.
    2. Move the form to the mediator, one field at a time, and delete the direct links.
    3. Add the bus for cart:changed, badge first, then summary and analytics.

    The 2 a.m. failure

    The summary handler and the badge handler both subscribe to cart:changed. The summary handler, first in the list, publishes cart:total, and a handler of that topic updates the badge with the new count. The bus delivers in sync mode, so that nested delivery runs first. Then the original cart:changed delivery reaches the badge handler with its older payload and overwrites the new count (illustrative). First three checks: (1) log the delivery order of the two topics; (2) check the bus mode; (3) check whether the handler reads its payload or the store. Mitigation: switch the bus to queued delivery. Follow-up: make handlers read the current state, and add the test from the lab that asserts the two orders. Exercise 3 asks for it.

    Architect's notes

    • Decide who should know whom before choosing the pattern. The pattern follows.
    • Make cleanup part of the subscribing code: whatever creates a subscription returns the way to end it.
    • Choose the delivery mode on purpose and let handlers read current state, not the payload they were handed.

    Common mistakes

    • Looping over a live listener list that unsubscribe can change.
    • Subscribing in a show handler without releasing in the hide handler.
    • Anonymous listener functions that cannot be removed.
    • A mediator that grows to cover several features.

    Key takeaways

    • Observer has a subject and listeners; pub/sub puts a topic between them; Mediator puts the rules in one object.
    • The DOM clones its listener list at dispatch, skips removed listeners, does not run added ones and continues after a throwing listener; a safe subject does the same.
    • A nested publish can run in the middle of a delivery or after it; the choice changes the order handlers see.
    • Every subscription needs a matching release; a scope makes that one call.
    • A mediator trades many links for one object that must stay small.

    Practice exercises

    Exercise 1 — Starter (45 min): Add a once method to Subject. Decide and test what happens when the listener removes itself inside its own call.

    Exercise 2 — Intermediate (2 hours): Add a second form with its own mediator that reuses Field, and test that the forms do not affect each other.

    Exercise 3 — Advanced (half day): Make the bus stop a runaway loop: if one drain delivers more than 100 nested publishes, drop the rest and record an error. Write the failing test first, then the fix.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments