Bird
Raised Fist0
LLDsystem_design~25 mins

Observer pattern in LLD - System Design Exercise

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Design: Observer Pattern Implementation
Design and implement the core observer pattern components including subject and observers. Out of scope are UI frameworks or network communication.
Functional Requirements
FR1: Allow multiple observer objects to subscribe to a subject object.
FR2: Notify all subscribed observers automatically when the subject's state changes.
FR3: Support adding and removing observers at runtime.
FR4: Ensure observers receive updates in a timely manner after state changes.
FR5: Keep the subject and observers loosely coupled.
Non-Functional Requirements
NFR1: The notification latency should be minimal (under 100ms) for typical state changes.
NFR2: Support up to 1000 observers per subject without significant performance degradation.
NFR3: Ensure thread safety if multiple threads update the subject or observers.
NFR4: Memory usage should be efficient to handle many observers.
Think Before You Design
Questions to Ask
❓ Question 1
❓ Question 2
❓ Question 3
❓ Question 4
❓ Question 5
Key Components
Subject interface/class to manage observers and state
Observer interface/class to receive updates
Concrete subject implementing state changes
Concrete observers implementing reaction to updates
Notification mechanism (push or pull model)
Design Patterns
Publish-Subscribe pattern
Event-driven architecture
Callback functions or listener interfaces
Thread-safe observer management
Reference Architecture
          +----------------+
          |    Subject     |
          |----------------|
          | - observers[]  |
          | + attach()     |
          | + detach()     |
          | + notify()     |
          +--------+-------+
                   |
        +----------+----------+
        |                     |
+---------------+     +---------------+
|  Observer 1   |     |  Observer 2   |
|---------------|     |---------------|
| + update()    |     | + update()    |
+---------------+     +---------------+
Components
Subject
Class or Interface
Manages a list of observers and notifies them of state changes.
Observer
Interface or Abstract Class
Defines the update method that observers implement to receive notifications.
ConcreteSubject
Class
Implements Subject, holds state, and notifies observers when state changes.
ConcreteObserver
Class
Implements Observer, reacts to updates from the subject.
Request Flow
1. 1. Observer calls attach() on Subject to subscribe.
2. 2. Subject stores observer reference in its list.
3. 3. Subject state changes via some method.
4. 4. Subject calls notify(), iterating over observers.
5. 5. Each observer's update() method is called with new state or event.
6. 6. Observers react accordingly to the update.
7. 7. Observers can call detach() to unsubscribe.
Database Schema
Not applicable as this is an in-memory design pattern implementation without persistent storage.
Scaling Discussion
Bottlenecks
Large number of observers causing slow notification loops.
Thread safety issues when multiple threads modify observers or subject state.
Observers that take too long to process updates blocking others.
Memory overhead from storing many observer references.
Solutions
Use asynchronous notification (e.g., event queues) to avoid blocking.
Implement thread-safe data structures or synchronization for observer list.
Use weak references for observers to avoid memory leaks.
Batch notifications or filter observers to reduce notification load.
Interview Tips
Time: Spend 10 minutes explaining the problem and requirements, 15 minutes designing the components and data flow, 10 minutes discussing scaling and thread safety, and 10 minutes answering questions.
Explain the loose coupling benefit of the observer pattern.
Describe how observers register and get notified.
Discuss synchronous vs asynchronous notifications.
Highlight thread safety and performance considerations.
Mention real-world examples like UI event listeners or messaging systems.

Practice

(1/5)
1.

What is the main purpose of the Observer pattern in system design?

easy
A. To create a strict hierarchy of classes
B. To allow objects to automatically update when another object changes
C. To store data in a database
D. To improve the speed of a single function

Solution

  1. Step 1: Understand the Observer pattern role

    The Observer pattern is designed to let one object notify others about changes automatically.
  2. Step 2: Match purpose with options

    To allow objects to automatically update when another object changes correctly describes automatic updates between objects without tight coupling.
  3. Final Answer:

    To allow objects to automatically update when another object changes -> Option B
  4. Quick Check:

    Observer pattern = automatic updates [OK]
Hint: Observer means automatic update on change [OK]
Common Mistakes:
  • Confusing Observer with data storage
  • Thinking it creates class hierarchies
  • Assuming it improves function speed
2.

Which of the following is the correct way to register an observer in the Observer pattern?

subject = Subject()
observer = ConcreteObserver()
# What code registers the observer?
easy
A. subject.addObserver(observer)
B. observer.subscribe(subject)
C. observer.register(subject)
D. subject.attach(observer)

Solution

  1. Step 1: Recall common Observer pattern method names

    Typically, the subject has a method named attach or addObserver to register observers.
  2. Step 2: Identify the most standard method

    While addObserver is used in some languages, attach is the classic and widely accepted method name.
  3. Final Answer:

    subject.attach(observer) -> Option D
  4. Quick Check:

    Register observer = subject.attach(observer) [OK]
Hint: Subject.attach(observer) is classic registration [OK]
Common Mistakes:
  • Calling register on observer instead of subject
  • Using subscribe which is not standard here
  • Confusing addObserver with observer methods
3.

Given this code snippet, what will be printed?

class Subject:
    def __init__(self):
        self.observers = []
        self.state = 0
    def attach(self, observer):
        self.observers.append(observer)
    def set_state(self, state):
        self.state = state
        for obs in self.observers:
            obs.update(state)

class Observer:
    def __init__(self, name):
        self.name = name
    def update(self, state):
        print(f"{self.name} received state {state}")

subject = Subject()
obs1 = Observer('A')
obs2 = Observer('B')
subject.attach(obs1)
subject.attach(obs2)
subject.set_state(5)
medium
A. A received state 5 B received state 5
B. A received state 0 B received state 0
C. No output
D. Error: update method missing

Solution

  1. Step 1: Follow the attach and set_state calls

    Observers A and B are attached to the subject. When set_state(5) is called, it updates the state and calls update(5) on each observer.
  2. Step 2: Understand the update method output

    Each observer prints its name and the new state, so both print lines with state 5.
  3. Final Answer:

    A received state 5 B received state 5 -> Option A
  4. Quick Check:

    Observers print updated state 5 [OK]
Hint: Observers print on update call with new state [OK]
Common Mistakes:
  • Thinking observers print old state
  • Assuming no output without explicit print
  • Confusing method names causing errors
4.

Identify the bug in this Observer pattern implementation:

class Subject:
    def __init__(self):
        self.observers = set()
    def attach(self, observer):
        self.observers.add(observer)
    def notify(self):
        for obs in self.observers:
            obs.update()

class Observer:
    def update(self, state):
        print(f"State updated to {state}")

subject = Subject()
obs = Observer()
subject.attach(obs)
subject.notify()
medium
A. Observer.update requires a state argument but notify calls without it
B. Subject.observers should be a list, not a set
C. attach method should remove observers, not add
D. notify method should not call update

Solution

  1. Step 1: Check method signatures and calls

    The Observer's update method expects a state argument, but notify calls update() without any argument.
  2. Step 2: Identify mismatch causing error

    This mismatch will cause a runtime error due to missing required positional argument.
  3. Final Answer:

    Observer.update requires a state argument but notify calls without it -> Option A
  4. Quick Check:

    Method argument mismatch causes error [OK]
Hint: Check method parameters match calls exactly [OK]
Common Mistakes:
  • Ignoring missing argument errors
  • Thinking sets are invalid for observers
  • Misunderstanding attach method purpose
5.

You are designing a stock price alert system using the Observer pattern. Multiple clients want updates only when the stock price changes by more than 5%. How should you modify the Observer pattern to handle this efficiently?

hard
A. Make observers poll the Subject periodically for changes
B. Notify all observers on every price change regardless of amount
C. Add a threshold check in the Subject before notifying observers
D. Remove the Observer pattern and use direct method calls

Solution

  1. Step 1: Understand the requirement for selective updates

    Clients want updates only if price changes exceed 5%, so notifying on every change is inefficient.
  2. Step 2: Implement threshold logic in Subject

    Adding a check in the Subject to compare new price with old and notify observers only if change > 5% reduces unnecessary notifications.
  3. Final Answer:

    Add a threshold check in the Subject before notifying observers -> Option C
  4. Quick Check:

    Efficient notify = threshold check in Subject [OK]
Hint: Filter notifications in Subject to reduce updates [OK]
Common Mistakes:
  • Not filtering updates causing overload
  • Using polling which wastes resources
  • Removing Observer pattern loses decoupling benefits