Observer is the pattern you have written the most times without ever calling it by name. Every addEventListener, every emitter.on, every subscribe(), every useEffect that listens to a store, every webhook registration. A subject keeps a list of interested parties and, when something changes, walks the list and calls each one. That is the whole idea, and it fits in twenty lines.
The twenty lines are not where Observer goes wrong. It goes wrong in production in four specific places: listeners that never leave, a list that changes while you are looping over it, one observer's exception taking down the others, and observers that see a state of the world that should never have existed. Java's own standard library gave up on its built-in version over problems in this family. My claim in this issue: the subscribe/notify mechanics are the easy 20 percent of Observer. The other 80 percent is four policies, and the event systems that survived (the DOM and Node.js in particular) each made an explicit choice on every one of them.
The pattern in one paragraph
The Gang of Four describe Observer as a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically. Refactoring Guru's write-up shows the usual shape: a subject (they call it the publisher) with subscribe, unsubscribe and notify, and observers that implement a single update method. The point is decoupling. The subject knows that someone cares, not who or why. The checkout service emits order_paid; the email sender, the analytics pipeline and the loyalty-points service each react, and the checkout code never imports any of them.
Here is the version that appears in every tutorial, in Python:
class Subject:
def __init__(self):
self._observers = []
def subscribe(self, fn):
self._observers.append(fn)
return lambda: self._observers.remove(fn) # unsubscribe handle
def notify(self, event):
for fn in self._observers:
fn(event)
Every snippet in this issue was run locally on Python 3.12. The outputs quoted are real. Now let's break it.
Break 1: the listener that never leaves
The subject holds a strong reference to every observer. If the observer is a bound method, the subject is holding the whole object it belongs to. So the lifetime of every observer is now at least the lifetime of the subject, and subjects (an app-wide event bus, a store, window) tend to live forever.
class Widget:
def __init__(self, bus):
bus.subscribe(self.on_price)
def on_price(self, event):
...
bus = Subject()
for _ in range(1000):
Widget(bus) # created, used, "thrown away"
gc.collect()
# alive widgets: 1000
A thousand widgets nobody references, all still alive, all still being called on every price update. This is the lapsed listener problem, and it is the single most common memory leak in UI code. A component mounts, subscribes to a global store, unmounts, and forgets to unsubscribe. Nothing crashes. Memory climbs slowly, and every event gets a little more expensive because it is delivered to a growing crowd of ghosts, some of which may still touch DOM nodes or sockets that are gone.
Node.js ships a smoke detector for exactly this. By default an EventEmitter allows 10 listeners per event, and when you add the 11th it does not throw. It adds the listener and prints a MaxListenersExceededWarning saying "possible EventEmitter memory leak detected" (Node.js events docs). The number 10 is arbitrary on purpose. It is not a limit, it is a tripwire: most events have a handful of listeners, so a count that keeps growing usually means something subscribes in a loop and never cleans up. The bad fix is setMaxListeners(0), which silences the detector and keeps the leak.
There are two real fixes. The first is to make unsubscription structural instead of remembered. The DOM's addEventListener accepts a signal option: the listener is removed when the owning AbortController calls abort() (MDN). That turns "remember to remove these six listeners" into one call tied to the component's lifetime:
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
window.addEventListener("keydown", onKey, { signal: controller.signal });
socket.addEventListener("message", onMessage, { signal: controller.signal });
// on teardown, all three are gone
controller.abort();
This is the same idea as React's effect cleanup function, Go's context.Context, or RxJS returning a Subscription from every subscribe: the act of subscribing hands you the handle that undoes it, and you attach that handle to something with a clear end.
The second fix is weak references: the subject does not keep observers alive at all.
import weakref
class WeakSubject(Subject):
def subscribe(self, method):
self._observers.append(weakref.WeakMethod(method))
def notify(self, event):
live = []
for ref in self._observers:
fn = ref()
if fn is not None:
fn(event)
live.append(ref)
self._observers = live
# same 1000 widgets, after gc.collect() and one notify:
# alive widgets: 0, observers: 0
Weak observers are tempting and I use them rarely. They make lifetime depend on the garbage collector, so an observer can keep receiving events for an unpredictable window after you "dropped" it, and a lambda subscribed weakly dies immediately because nothing else holds it. Explicit, scoped unsubscription is boring and deterministic. Prefer boring.
Break 2: the list changes while you loop over it
Observers react to events, and reacting often means subscribing or unsubscribing. A one-shot handler removes itself. A handler for user_logged_out tears down the session and the session's listeners. Now look at what the tutorial notify does when that happens:
s = Subject()
calls = []
def once(event):
calls.append("once")
unsub() # remove myself
unsub = s.subscribe(once)
s.subscribe(lambda e: calls.append("audit"))
s.notify("order-1")
# calls: ['once']
The audit observer never ran. Removing element 0 from a Python list during a for loop shifts element 1 into slot 0, the iterator moves to slot 1, and the loop ends. No exception, no warning, just an audit log with a hole in it for order-1. A JavaScript forEach over a plain array that gets spliced mid-loop skips the same way.
The fix is one character of code and one sentence of policy: iterate over a snapshot.
def notify(self, event):
for fn in list(self._observers): # snapshot
fn(event)
# calls: ['once', 'audit']
The policy that comes with it is the important part: the set of observers for a given notification is fixed at the moment the notification starts. Node.js documents exactly this. Listeners attached when emit is called all run for that emit, even if one of them removes another; the removal only affects later emits (Node.js events docs). Pick this rule, write it down, and test it, because the opposite rule (changes apply immediately) is also defensible and the bugs come from code that assumes one rule while the subject implements the other.
Snapshotting has one consequence worth knowing. An observer you just unsubscribed can still be called once more, for the notification already in flight. If that observer touches a resource you freed in the same breath, guard it with a "disposed" flag. Snapshotting moves the edge case; it does not delete it.
Break 3: one observer throws and the rest go dark
The tutorial loop has no error handling, so an exception in observer 1 propagates out of notify and observer 2 never runs:
s = Subject()
seen = []
s.subscribe(lambda e: 1 / 0) # the analytics client has a bug
s.subscribe(lambda e: seen.append(e)) # the email sender
s.notify("paid") # ZeroDivisionError
# seen: []
Read that through the checkout example. A bug in the analytics observer means the customer does not get a receipt, and worse, the exception surfaces in the checkout code that called notify, which has no idea analytics exists. Observer was supposed to decouple these services. Unhandled, it couples every observer's failure to every other observer and to the subject.
There is no universal right answer here, but there must be an explicit one. The options are: let the first failure abort the rest (sometimes right, for validation-style observers that can veto); isolate each observer and report failures after everyone has run; or isolate and only log. For most domain events, isolate-and-report is what you want:
def notify(self, event):
errors = []
for fn in list(self._observers):
try:
fn(event)
except Exception as exc:
errors.append(exc)
if errors:
raise ExceptionGroup("observer failures", errors)
# group: 1 failure, seen: ['paid']
The DOM chose isolation. If one event listener throws, the browser reports the exception and keeps dispatching to the remaining listeners, so one broken analytics snippet does not stop your click handler. Node.js chose the opposite for its most important event: emitting 'error' with no 'error' listener registered throws, and if nothing catches it the process crashes (Node.js events docs). That is a deliberate stance: an error event nobody handles is a bug you must not be allowed to ignore. Both choices are reasonable. What is not reasonable is not having chosen, which is what the tutorial loop does.
Break 4: observers see a world that never existed
This one is subtle and it is the reason the frontend world spent the last decade rebuilding Observer under new names. Take three values: a, b = a * 2, and c = a + b. Wire them up with plain synchronous observers, the way you would by hand:
a = Cell(1)
b = Cell(2)
def recompute_c(_):
c_values.append(a.v + b.v)
a.subscribe(recompute_c) # c depends on a
a.subscribe(lambda _: b.set(a.v * 2)) # b depends on a
b.subscribe(recompute_c) # c depends on b
a.set(2)
# c observed: [4, 6]
The correct value of c after a = 2 is 6. But c was computed twice, and the first time it was 4: new a, old b. Four is a value that is never valid for any input. If an observer on c sends an alert, renders a frame, or writes to a database, it acted on a state that never existed. This is called a glitch, and it appears whenever the dependency graph has a diamond (two paths from one source to one sink) and notifications are pushed eagerly in subscription order. Change the order of the subscribe calls and the glitch disappears, which is exactly what makes it a production bug: it depends on registration order nobody designed.
This is also what Java's deprecation note is pointing at. When java.util.Observable was deprecated in Java 9, the Javadoc said its event model is quite limited, the order of notifications it delivers is unspecified, and state changes are not in one-for-one correspondence with notifications (Java SE API docs). That last clause is the glitch problem stated as an API limitation.
The fix used by modern reactive libraries is to split notification into two phases: push "something changed" eagerly, but pull values lazily and in dependency order. Observers mark themselves dirty when a source changes, and recompute only when read, by which time every input is up to date:
class Computed:
def __init__(self, fn, deps):
self.fn, self.dirty, self.cache, self.subs = fn, True, None, []
for d in deps:
d.subs.append(self)
def mark_dirty(self): # push phase: cheap, no values
if not self.dirty:
self.dirty = True
for s in list(self.subs):
s.mark_dirty()
def get(self): # pull phase: compute on read
if self.dirty:
self.cache, self.dirty = self.fn(), False
return self.cache
a = Signal(1)
b = Computed(lambda: a.get() * 2, [a])
c = Computed(lambda: a.get() + b.get(), [a, b])
c.get() # 3
a.set(2)
c.get() # 6, computed once, no 4 ever produced
That push-dirty, pull-value design is the core of the TC39 Signals proposal, which describes signals as a push-pull construction with glitch-free computation, and which was written with input from the maintainers of Angular, Preact, Solid, Vue, MobX and others. It is still Observer. It is Observer with an explicit answer to "what is an observer allowed to see mid-update": only consistent states.
You do not need a signals library to apply the lesson. In backend code the equivalent move is batching: apply all state changes, then notify once with the final state. A domain object that records events while a command runs and publishes them after the transaction commits is doing exactly this, and it also fixes the related bug where an observer reads the database before the write it was told about is visible.
Push or pull the payload
One smaller decision rides along with the four above. In push style, notify(event) hands observers the data. In pull style, notify() just says "I changed" and observers call back into the subject to read what they need. Push is simpler and works across process boundaries (a webhook is push Observer over HTTP). Pull keeps observers from depending on a payload shape and avoids sending data nobody reads, but it means observers read the subject's current state, which may have moved on since the notification was sent.
My default: push an immutable event that describes what happened (OrderPaid(order_id, amount, at)), not the whole object and not a bare "changed" ping. Immutable events can be queued, logged, retried and replayed, which is how in-process Observer grows into the event-driven architecture covered earlier in this series without a rewrite.
When not to use it
Observer hides control flow. When checkout() calls notify, nothing at the call site tells you that seven things happen next, in what order, or which can fail. That is the decoupling working as designed, and it is also why debugging an event-heavy codebase feels like reading a novel with the pages shuffled. If there are exactly one or two consumers and they will not change, a direct call is clearer. If the reaction must happen for correctness (charging the card, not sending the receipt), it belongs in the main flow, not behind a subscription that someone can forget to register. Use Observer for the reactions that are genuinely optional to the subject: notifications, metrics, caches, UI updates.
The four questions
Find the event system in your codebase. There is always one: an in-house event bus, a store, a model with on_change hooks, a plugin system. Then ask four questions. Who unsubscribes each observer, and what ties that to a lifetime? If an observer subscribes or unsubscribes during a notification, what happens to the current loop? If an observer throws, do the others still run, and who finds out? Can an observer ever see a half-updated state?
Each answer is a short test. The skipped-audit-log bug, the missing-receipt bug and the impossible-value glitch above are each under fifteen lines to reproduce. Write them before you need them. The subscribe/notify loop is what makes Observer elegant. The four policies are what make it safe to build on.

