Observer or Mediator? Design Decisions Workbook
Separate independent notifications from coordinated workflows.
When to use Observer, when to use a Mediator, and the delivery, ordering, lifetime and failure questions an interviewer expects you to ask about either one.
At a glance
- Observer: independent subscribers react to a fact, and the publisher does not know their concrete types.
- Mediator: one coordinator owns how collaborators interact and which step comes next.
- A required order belongs in visible control flow, never in the order subscribers happened to register.
- Neither pattern gives durable delivery, transactions or exactly-once effects: say what is synchronous, what is retried and what happens on failure.
- Subscriptions have a lifetime: a short-lived subscriber must unsubscribe from a long-lived publisher.
- A direct method call is often clearest when there is one fixed collaborator.
Observer or Mediator?
| Question | Observer | Mediator |
|---|---|---|
| Relationship | independent reactions to a fact | collaborators following a rule or sequence |
| Example | dashboard panels react to a new reading | reserve stock, then authorize payment, then confirm |
| Owner to name | who subscribes and unsubscribes | who decides the next step and the recovery |
| Common mistake | hiding a required order in subscriber registration | one huge coordinator that holds every business rule |
In .NET code, "mediator" often means a request dispatcher such as MediatR: one request, one handler. That decouples the sender from the handler, but it is not the same as a coordinator that owns a workflow.
Observer in C#: events, failures and unsubscribing
var sensor = new Sensor();
EventHandler<int> chart = (_, v) => Console.WriteLine($"chart: {v}");
EventHandler<int> broken = (_, v) => throw new InvalidOperationException("panel failed");
EventHandler<int> log = (_, v) => Console.WriteLine($"log: {v}");
sensor.Reading += chart;
sensor.Reading += broken;
sensor.Reading += log;
try { sensor.Publish(21); }
catch (InvalidOperationException ex) { Console.WriteLine($"stopped: {ex.Message}"); }
sensor.Reading -= broken; // unsubscribe
sensor.Publish(22);
class Sensor
{
public event EventHandler<int>? Reading;
public void Publish(int value) => Reading?.Invoke(this, value);
}chart: 21 stopped: panel failed chart: 22 log: 22
- A field-like C# event calls its handlers one after another on the publisher's thread. When a handler throws synchronously, the rest do not run (an
async voidhandler's exception surfaces later, outside the call): decide whether to fail fast or to call each handler with its owntry/catch. -=removes a handler. A publisher that outlives its subscribers keeps instance subscribers alive through its handler list: unsubscribe when the subscriber is done.- With
IObservable<T>,Subscribereturns anIDisposable; dispose it to unsubscribe. The order in which observers are notified is not defined.
Six scenarios and their answers
| Scenario | Answer |
|---|---|
| A dashboard publishes sensor values; charts and logs come and go | Observer: independent subscribers; say who owns each subscription |
| Reserve stock, authorize payment, then confirm a booking | a coordinator (mediator or workflow) owns the order and the failure response |
| One subscriber must save a value before another reads it | not a subscriber-order contract: make the dependency explicit in a coordinator or pipeline |
| A short-lived screen subscribes to a long-lived provider | unsubscribe (dispose the subscription) when the screen closes, and test that it stops |
| A handler throws before later handlers run | choose fail-fast or isolated handlers, and test a failing subscriber |
| A retry after a timeout reaches a receiver that already applied it | an idempotent effect: the same operation ID, deduplicated by the receiver |
A coordinator owns the workflow
public async Task<BookingResult> BookAsync(BookingRequest request, CancellationToken ct)
{
var reservation = await stock.ReserveAsync(request.Items, request.OperationId, ct);
var payment = await payments.AuthorizeAsync(request.Total, request.OperationId, ct);
if (!payment.Succeeded)
{
await stock.ReleaseAsync(reservation, ct); // the coordinator owns compensation
return BookingResult.Declined(payment.Reason);
}
await bookings.ConfirmAsync(reservation, payment, ct);
events.Publish(new BookingConfirmed(request.OperationId)); // observers react afterwards
return BookingResult.Confirmed();
}- The order and the declined-payment compensation are in one place you can read and test. A complete workflow must also handle a timeout or a failure after the reservation.
- The same
OperationIdon every call lets each receiver detect a duplicate after a retry, if it stores and checks that ID durably. - A timeout is not a decline: the payment may have gone through. Check its status before you compensate or retry.
Common mistakes
- Encoding "save first, then bill" as subscriber registration order: put the dependency in a coordinator.
- Forgetting to unsubscribe: a long-lived publisher keeps short-lived subscribers in memory and keeps calling them.
- Swallowing handler exceptions to make other handlers run: log and handle them on purpose, per handler.
- Treating a timeout as a failure and retrying with a new ID: reuse the operation ID, so a receiver that deduplicates by it applies the effect once.
- Routing every interaction through one mediator: keep unrelated rules in their own classes.
- Adding either pattern for one fixed collaborator: a direct call is simpler.
In an interview
What is the Observer pattern? A subject keeps a list of observers and notifies them when something happens, without knowing their concrete types. In C#, events and IObservable<T> / IObserver<T> implement it.
What is the Mediator pattern? Objects talk through one mediator instead of to each other, so their interaction rules live in one place. Use it when collaborators must follow a sequence or a rule.
Observer or Mediator for a booking workflow? A mediator or workflow coordinator: the order (reserve, authorize, confirm) and the compensation are rules that need an owner. Observers fit the side reactions after the booking is confirmed.
Can observers rely on the order they are notified in? No. For IObservable<T> the order is not defined. A field-like event calls its handlers in registration order, but that order is a fragile place for a business rule: make a required order explicit.
How do events cause memory leaks? An instance handler's delegate references its subscriber, so the publisher's handler list keeps that subscriber alive until it unsubscribes with -= or disposes its subscription.
What happens when one event handler throws? When it throws synchronously, the exception goes to the code that raised the event, and the handlers after it are not called. Catch per handler if they must be isolated.
Check yourself
A C# event has three handlers, and the second one throws synchronously. What happens to the third?
Show answer
Correct answer: B
Handlers run one after another; the exception leaves the invocation, so the remaining handlers are skipped.
Option A: Nothing logs and continues unless the publisher catches per handler.
Option C: Event handlers run on the publisher's thread, in sequence.
Option D: A field-like event calls its handlers in registration order.
Billing must happen only after a reading is saved. Where should that rule live?
Show answer
Correct answer: B
A required order is part of the business rule, so it belongs in visible control flow that you can test.
Option A: Registration order is incidental and easy to break.
Option C: Events and observers have no priority setting to rely on.
Option D: Observer order is not defined, and event order is a poor place for a business rule.
A short-lived screen subscribes to a long-lived provider. What must it do when it closes?
Show answer
Correct answer: B
The provider's reference keeps the screen alive and notified until the screen unsubscribes.
Option A: The provider still references the screen, so the GC cannot collect it.
Option C: Throwing breaks the other handlers too.
Option D: Clearing the list removes every other subscriber as well.
Timed practice on the same decisions: the Observer, Mediator, Chain of Responsibility and Visitor practice test.
Sources
- Observer design pattern:
IObservable<T>,IObserver<T>and unsubscribing throughIDisposable. - Observer design pattern best practices: notification order is not defined; events for simple in-process notification.
- Using delegates: multicast delegates call their methods in order.
- Retry pattern: retried operations must be idempotent.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·