Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Observer

Intent

Let one subject broadcast updates to any number of subscribers without knowing who they are.

Motivation

An online order changes status to “shipped” and both email and SMS services must react. Calling each notifier directly from the order wires the order to every channel — adding push means editing order code. Letting notifiers subscribe to the order and receive a broadcast keeps the order focused on status while channels come and go freely.

Structure

flowchart LR
  Order[Order Subject] --> E[Email Observer]
  Order --> S[SMS Observer]
  E --> Order
  S --> Order
  • Subject (Order) — keeps the subscriber list and broadcasts each status change.
  • Observers (Email, SMS) — register themselves and react when notified; never polled.

Consequences

  • Benefit: subjects and channels evolve independently; adding a channel means adding a subscriber, not editing the subject.
  • Cost: broadcast order is loose and cascading updates can surprise — document whether notification is synchronous and reentrancy-safe.

Basic Recap

Observer establishes a one-to-many notification relationship in which a subject announces changes without depending on concrete subscribers. Observers register interest and react through a common notification contract. The subject owns the change and subscription mechanism, while observers own their responses. Delivery semantics—synchronous or queued, ordered or unordered, at-most-once or at-least-once—are additional design choices, not guarantees supplied by the pattern name.

Complex Scenario

A warehouse telemetry subject publishes equipment temperature changes to an alerting observer, a search indexer, and a maintenance predictor. New analytical consumers can subscribe without modifying sensor ingestion. A local event bus dispatches durable event envelopes containing equipment identity, sequence, and event identifier. Alert delivery remains isolated from indexing cost so a slow analytical observer cannot block ingestion of every reading.

Edge cases

  • Ordering: Observers that require equipment chronology consume per-equipment sequences and detect gaps; global ordering across all equipment is unnecessary and expensive.
  • Retries: At-least-once delivery repeats events after acknowledgements are lost, so alert observers deduplicate and index writes are idempotent.
  • Partial failure: One failing observer is isolated in its own subscription and dead-letter path rather than preventing unrelated observers from progress.
  • Memory pressure: Slow consumers need bounded queues and backpressure or discard policies instead of an ever-growing pending-event list.

The event record should describe a fact already committed, not expose a mutable subject that observers can alter during notification.

Sketch (illustrative pseudocode, not runnable):

TelemetryIngest.onReading(reading):
    event = eventStore.append(reading, nextEquipmentSequence)
    bus.publishDurably(event)

Subscription.dispatchLoop():
    batch = queue.receiveBounded()
    for event in batch:
        result = observer.handle(event)
        if result.succeeded:
            checkpoint.advance(event.id)
        else:
            retryPolicy.scheduleOrDeadLetter(event, result)

When to Use / When Not to Use

Use when:

  • One state change must reach many unknown or changing parties (status feeds, UI refresh, alerts).
  • Subscribers should attach and detach at runtime.

Avoid when:

  • Only one fixed receiver exists, or update order and exactly-once delivery are critical — prefer direct calls or a queue.

Examples

  • examples/elixir/observer/
  • examples/dart/observer/
  • examples/go/observer/
  • examples/rust/observer/

Expected outcome: one order-status change notifies both the email and SMS channels.

Anti-pattern / Failure Mode

  • Misuse: Broadcasts where every follower mutates shared state during notification.

  • Review signal: Update storms from cascaded notifications with no ordering guarantees.

  • Misuse symptom: The subject synchronously calls observers that perform email, database writes, and further publications on its critical path. Observer lists become hidden business orchestration, and notification cycles recursively trigger the same changes.

  • Review signal: Look for strong references that prevent unsubscribe, mutable events, observers throwing through the publisher, and no documented ordering or retry contract. Rising pending-queue depth, repeated event IDs, and latency tied to the slowest subscriber are operational signs that the simple pattern needs an explicit delivery architecture.

Exercise

Add a push notifier, then unsubscribe SMS and re-broadcast. Confirm only email and push react, with no edit to the order’s broadcast logic.

Self-check

  • Who holds the subscriber list?
    AnswerThe subject — observers only register and react, they never track each other.
  • Push vs pull updates: what differs?
    AnswerPush sends the new state inside the notification; pull sends “changed” and observers query back. The example pushes the status line.
  • Observer vs Mediator: what differs?
    AnswerObserver is one-to-many broadcast with no routing; Mediator is many-to-many with the hub choosing recipients.