System Design Academy

Saving…

Lesson 8 of 11 in Module 30 of 45 lessons complete

Observer

Module 3, lesson 8Concept12 min

Definition

Publisher and subscriber

In plain English
A publisher announces events, and a subscriber is code that has asked to be told about them.
Think of it like
Like a radio station and its listeners.

Observer

In plain English
Observer lets many subscribers register interest in an event, and the publisher notifies all of them when it happens.
Think of it like
It is like signing up for a delivery app's notifications instead of checking the doorstep every five minutes.

Unsubscribe

In plain English
Unsubscribing removes a subscriber so it stops receiving events.
Think of it like
Like cancelling a newsletter.

Why it exists

A checkpoint service directly calls the leaderboard, family tracker and photo service. Adding another listener means editing the checkpoint service.

Let interested code register instead. The publisher announces an event without listing each reaction inside its business logic.

How it works

Callback

In plain English
A callback is a function you register so other code can call it later.
Think of it like
It is like leaving your phone number for a call when your order is ready.
Complete library: a reusable hub protects registration and supports unsubscribe.
Go
package hub

import "sync"

type Event struct{ Name string }
type Listener func(Event)
type Hub struct {
	mu        sync.Mutex
	next      int
	listeners map[int]Listener
}

func (h *Hub) Subscribe(fn Listener) func() {
	h.mu.Lock()
	if h.listeners == nil {
		h.listeners = make(map[int]Listener)
	}
	id := h.next
	h.next++
	h.listeners[id] = fn
	h.mu.Unlock()
	return func() { h.mu.Lock(); delete(h.listeners, id); h.mu.Unlock() }
}
func (h *Hub) Publish(e Event) {
	h.mu.Lock()
	snapshot := make([]Listener, 0, len(h.listeners))
	for _, fn := range h.listeners {
		snapshot = append(snapshot, fn)
	}
	h.mu.Unlock()
	for _, fn := range snapshot {
		fn(e)
	}
}

Leaderboard and FamilyTracker subscribe to Hub, which notifies registered Listener functions.

Listeners register without becoming publisher dependencies.

Leaderboard and FamilyTracker subscribe to Hub, which notifies registered Listener functions.

Channel

In plain English
A channel is a Go value used to send typed values between parts of a program.
Think of it like
It is like a conveyor belt carrying messages from a sender to a receiver.
  • Publish copies listeners while holding the mutex, then releases it before calling them. Callbacks can therefore subscribe or unsubscribe.
  • Unsubscribe prevents inclusion in later snapshots. An event already copied for delivery may still arrive.
  • Separate channels need space for waiting values and a rule for full channels. Separation alone does not prevent blocking.

Examples

Notify every interested service

A smoke event triggers SMS alerts, the map and fire crews. A drone dispatcher joins with another Subscribe call.

Notify every interested service.
Go
package main

import "fmt"

type Listener func(string)
type Hub struct{ listeners []Listener }

func (h *Hub) Subscribe(fn Listener) { h.listeners = append(h.listeners, fn) }
func (h *Hub) Publish(event string) {
	for _, fn := range h.listeners {
		fn(event)
	}
}
func main() {
	h := &Hub{}
	for _, service := range []string{"SMS", "map", "crew", "drone"} {
		h.Subscribe(func(e string) { fmt.Println(service, e) })
	}
	h.Publish("smoke at zone 4")
}

This single-threaded demonstration calls every listener directly. The protected hub above is the starting point when registration and publishing may overlap.

The insight

Publishers do not need to know who is listening.

Trade-offs

Pros

  • One event supports many reactions.
  • New listeners register independently.
  • Publisher code stays focused.

Cons

  • Reactions are harder to trace.
  • Ordering and failure rules need decisions.
  • Forgotten subscriptions retain data.

Use when

  • Several independent consumers react to one event.
  • Listeners change without changing the publisher.

Avoid when

  • One consumer needs an immediate result.
  • A direct call already expresses the required order.

Quick check

A checkpoint service directly calls three other services and must change for every new one. Which pattern helps?
Why give each subscriber its own channel?

Takeaways

  • Observer = publish once, many subscribers react.
  • Publishers don't know their listeners.
  • Protect the subscriber list and watch for slow subscribers.

Try the quick check above whenever you feel ready.

Previous: Strategy