Skip to content
Back to blog
Design Patterns

Observer Pattern: Decoupling Event Producers and Consumers

Updated 18 min read

The Observer Pattern is more than notifying listeners when something happens. Learn how to decouple event producers from consumers, handle asynchronous execution and failures, manage subscriptions, and decide when an event bus or durable message queue is the better choice.

Table of Contents

Introduction

When an order is created, saving it to the database may be only the beginning.

The application may also need to send a confirmation email, update analytics, notify an internal team, and publish an event for another component to process.

A straightforward implementation might look like this:

typescript
class OrderService {
  async createOrder(order: Order): Promise<void> {
    await this.repository.save(order);

    await this.emailService.sendConfirmation(order);
    await this.analyticsService.trackOrderCreated(order);
    await this.notificationService.notifyTeam(order);
  }
}

This works, but the order service now knows about every action that follows order creation.

Adding a new notification channel means modifying the service. A failure in analytics may affect the order workflow. Tests may need to account for several unrelated dependencies even when the behavior under test concerns only order creation.

The deeper problem is coupling between the component that produces an event and the components that react to it.

The Observer Pattern offers a way to separate these responsibilities. A producer announces that something has happened, while interested observers receive that notification and react independently.

However, this separation introduces its own questions. What happens when an observer fails? Does the producer wait for observers to finish? What happens when observers are registered twice or never removed? And when should an in-process observer be replaced by a durable message queue?

Understanding those trade-offs is what makes the pattern useful in real applications.

1. The Problem: One Event, Many Reactions

Imagine an application that handles order creation.

Initially, the only requirement is to save the order. Later, the product team introduces confirmation emails. A few weeks later, analytics tracking and internal notifications are added.

The implementation gradually becomes:

typescript
async function createOrder(order: Order): Promise<void> {
  await orderRepository.save(order);

  await emailService.sendConfirmation(order);
  await analyticsService.trackOrderCreated(order);
  await notificationService.notifyTeam(order);
}

The code is not inherently wrong. Explicit orchestration is often the clearest choice when the workflow is small and its steps are tightly related.

The design becomes less attractive when new reactions are added frequently or when the producer should not need to know which reactions exist.

There are three distinct concerns:

  1. The primary operation: Persisting the order.
  2. The event: Communicating that the order has been created.
  3. The reactions: Sending emails, updating analytics, or notifying other components.

These concerns may have different reasons to change.

For example, changing the analytics provider should not normally require modifying the order persistence logic. Adding a new internal notification should not require the order service to learn about another notification implementation.

The design question is:

Can the order service announce a meaningful event without directly depending on every component interested in that event?

Observer provides one possible answer.

2. The Core Idea Behind Observer

The Observer Pattern defines a relationship in which one object, commonly called the subject or publisher, maintains a set of observers and notifies them when something relevant happens.

The essential roles are:

  • Subject or publisher: Exposes a way to subscribe to notifications and announces events.
  • Observer or subscriber: Receives a notification and performs its own work.
  • Event or notification: Describes what happened.

Conceptually:

flowchart TD
    E[Order Created] --> P[Event Publisher]
    P --> H1[Email Handler]
    P --> H2[Analytics Handler]
    P --> H3[Internal Notifier]

The publisher knows that observers have subscribed, but it does not need to know their internal implementation details.

This changes how new behavior is added.

Instead of modifying the order service every time another reaction is introduced, the application can register another observer.

The producer's responsibility becomes narrower: report the event at the appropriate point. Each observer owns its response.

What Observer does not guarantee

Observer does not automatically provide:

  • Durable event storage.
  • Delivery retries.
  • Exactly-once processing.
  • Execution in the background.
  • Isolation from subscriber failures.
  • Cross-process communication.

These capabilities depend on the implementation and infrastructure surrounding the pattern.

An in-process Observer implementation is fundamentally a notification mechanism. It should not be mistaken for a complete distributed event-processing system.

3. Implementing Observer in TypeScript

A practical implementation starts with a typed event contract.

Suppose an application needs to notify interested components when an order is created.

typescript
interface Order {
  id: string;
  customerEmail: string;
  total: number;
}

interface OrderCreatedEvent {
  type: "order.created";
  order: Order;
}

The event contains the information subscribers need to react. In a real system, the event contract should include only the data appropriate for its intended consumers.

Define the observer interface:

typescript
interface Observer<T> {
  handle(event: T): void | Promise<void>;
}

Then implement a publisher:

typescript
class EventPublisher<T> {
  private readonly observers = new Set<Observer<T>>();

  subscribe(observer: Observer<T>): () => void {
    this.observers.add(observer);

    return () => {
      this.observers.delete(observer);
    };
  }

  async publish(event: T): Promise<void> {
    for (const observer of this.observers) {
      await observer.handle(event);
    }
  }
}

This implementation provides a basic subscription lifecycle:

  • subscribe() registers an observer.
  • publish() notifies registered observers.
  • The returned function unsubscribes the observer.

The Set prevents the same observer instance from being registered more than once.

Notice that publish() awaits each observer in sequence. This is a deliberate execution policy, not an inherent requirement of Observer. We will examine its consequences shortly.

Implement concrete observers

Each observer handles one reaction:

typescript
class OrderEmailObserver
  implements Observer<OrderCreatedEvent> {
  async handle(event: OrderCreatedEvent): Promise<void> {
    // Send a confirmation email.
    console.log(`Email for order ${event.order.id}`);
  }
}

class OrderAnalyticsObserver
  implements Observer<OrderCreatedEvent> {
  async handle(event: OrderCreatedEvent): Promise<void> {
    // Record the order in analytics.
    console.log(`Analytics for order ${event.order.id}`);
  }
}

The application assembles the publisher and its observers:

typescript
const orderEvents = new EventPublisher<OrderCreatedEvent>();

orderEvents.subscribe(new OrderEmailObserver());
orderEvents.subscribe(new OrderAnalyticsObserver());

The order service receives the publisher rather than directly depending on every observer:

typescript
class OrderService {
  constructor(
    private readonly repository: OrderRepository,
    private readonly events: EventPublisher<OrderCreatedEvent>,
  ) {}

  async createOrder(order: Order): Promise<void> {
    await this.repository.save(order);

    await this.events.publish({
      type: "order.created",
      order,
    });
  }
}

The service knows that an order-created event should be published after persistence. It does not need to know whether email, analytics, or other observers are registered.

Adding an observer can now happen at the composition boundary without changing the service.

A practical design consideration

The example uses EventPublisher<OrderCreatedEvent> directly. This is fine for a small application, but larger systems may benefit from an EventPublisher interface or a domain-specific event dispatcher.

The goal is not to create an abstraction for every class. It is to establish the boundary needed by the application.

Also, the example publishes the full Order object. In a production system, consider publishing a dedicated event payload instead. That reduces accidental coupling to internal domain models and helps keep event contracts stable as the application evolves.

4. Synchronous vs. Asynchronous Notification

A crucial implementation decision is how observers are executed.

The word asynchronous is often used ambiguously here. An observer may perform asynchronous I/O, but the publisher may still wait for that work to finish before returning.

These are different questions:

  1. Can an observer perform asynchronous operations?
  2. Does the publisher wait for the observer to finish?
  3. Does the observer run in the same process?
  4. Is the event stored durably for later delivery?

An async function alone answers none of the last two questions.

Sequential execution

The implementation above uses:

typescript
for (const observer of this.observers) {
  await observer.handle(event);
}

This means each observer finishes before the next begins.

Advantages include predictable ordering and straightforward error propagation.

However, a slow email provider can delay analytics processing, and one rejected promise can prevent later observers from running.

Sequential execution is appropriate when ordering matters or when the number of observers is small and predictable.

Concurrent execution

If observers are independent, they can run concurrently:

typescript
async publish(event: T): Promise<void> {
  await Promise.all(
    [...this.observers].map((observer) =>
      observer.handle(event),
    ),
  );
}

This can reduce total waiting time when multiple observers perform I/O independently.

However, Promise.all() rejects when one of its promises rejects. Other observers may still be running, and the caller does not receive a complete per-observer result.

Concurrent execution also means observers should not assume that another observer has already completed.

Use it only when those semantics are acceptable.

Fire-and-forget execution

Another possibility is to invoke observers without awaiting them:

typescript
for (const observer of this.observers) {
  void observer.handle(event);
}

This is not a reliable background-processing mechanism by itself.

A rejected promise may become an unhandled rejection. The work may be interrupted when the process terminates, and the publisher has no built-in way to track completion or retry failed work.

If you intentionally choose fire-and-forget behavior, explicitly handle errors and accept the associated reliability limitations.

For important business operations, a durable queue or event-processing system is usually a better fit than unmanaged promises.

Choose execution semantics deliberately

The important decision is not whether to use for, Promise.all(), or void.

It is whether the application requires ordered execution, independent execution, visible failure, or durable delivery.

The implementation should reflect those requirements rather than accidentally determining them.

5. Error Handling and Listener Lifecycle

Observer introduces operational questions that a minimal implementation can easily overlook.

What happens when one observer fails?

Suppose an order is saved successfully, but the email observer fails.

The database now contains the order, while publish() rejects. If the HTTP handler interprets that rejection as a failed order creation, the client may retry the entire operation.

That retry could create duplicate orders unless the operation is idempotent.

The opposite choice also has risks. If the publisher swallows every observer error, important failures may become invisible.

There is no universal error-handling policy. The correct choice depends on whether a reaction is essential to the business operation.

For example:

  • If an order cannot be considered complete without a required validation step, that step should be part of the primary workflow rather than an optional observer.
  • If an email is a secondary notification, its failure may be recorded and retried without rolling back the order.
  • If analytics is noncritical, the system may choose to log failures and continue processing other observers.

Observer should not be used to hide required business steps behind an apparently optional notification mechanism.

Make error isolation explicit

A publisher can collect observer failures and report them after attempting all observers:

typescript
class EventPublisher<T> {
  private readonly observers = new Set<Observer<T>>();

  subscribe(observer: Observer<T>): () => void {
    this.observers.add(observer);

    return () => {
      this.observers.delete(observer);
    };
  }

  async publish(event: T): Promise<void> {
    const failures: unknown[] = [];

    for (const observer of this.observers) {
      try {
        await observer.handle(event);
      } catch (error) {
        failures.push(error);
      }
    }

    if (failures.length > 0) {
      throw new AggregateError(
        failures,
        "One or more observers failed",
      );
    }
  }
}

This version attempts every observer before reporting failures. However, it still does not decide whether the producer should treat those failures as fatal.

That policy belongs to the application boundary that calls publish(), or to a more explicit event-processing abstraction.

For noncritical reactions, a different design may report failures to monitoring while allowing the primary operation to succeed. For critical reactions, the workflow must define how failure affects business state.

Unsubscribe when the observer is no longer needed

In long-running applications, dynamically registered observers can remain in memory if they are never removed.

The subscription API above returns an unsubscribe function:

typescript
const unsubscribe = orderEvents.subscribe(
  new OrderEmailObserver(),
);

// Later, when the subscription is no longer needed:
unsubscribe();

This matters especially in applications with dynamic modules, plugin lifecycles, tests, or UI components that mount and unmount.

A static backend application may register observers once at startup and keep them for the lifetime of the process. In that case, explicit removal may be less important, but it is still useful to understand the lifecycle.

Be careful when the observer collection changes during notification

A production event dispatcher should define what happens if an observer subscribes or unsubscribes while an event is being published.

One common approach is to snapshot the observer collection before dispatch:

typescript
const currentObservers = [...this.observers];

for (const observer of currentObservers) {
  await observer.handle(event);
}

The snapshot makes the current publication's recipient list predictable. Changes to subscriptions affect subsequent publications.

This is a small implementation detail with a significant impact on event semantics.

6. Observer, Callbacks, Event Bus, and Message Queues

These concepts overlap, but they are not interchangeable.

Observer vs. callback

A callback is a function supplied to another function or component to be invoked later.

typescript
async function createOrder(
  order: Order,
  onCreated: (order: Order) => void,
): Promise<void> {
  await orderRepository.save(order);
  onCreated(order);
}

This is a simple way to delegate a reaction without requiring a dedicated observer class.

A callback is often the better choice when there is one known reaction and the relationship is local.

Observer becomes more useful when multiple subscribers need to register independently and the publisher should maintain a subscription lifecycle.

The distinction is not about whether one approach uses a function and another uses a class. The important difference is the structure and ownership of the notification relationship.

Observer vs. event bus

An event bus usually exposes a central interface for publishing events and registering handlers. It can be implemented using the Observer Pattern.

The term event bus generally describes a broader architectural mechanism: producers publish named events, and handlers subscribe to event types through a dispatcher.

For example:

typescript
await eventBus.publish({
  type: "order.created",
  orderId: order.id,
});

Handlers can be registered elsewhere:

typescript
eventBus.subscribe(
  "order.created",
  async (event) => {
    // Handle the event.
  },
);

An event bus may make it easier to coordinate events across modules without direct references between producers and consumers.

However, it also makes control flow less explicit. A developer reading createOrder() may not know which handlers will run or what side effects they introduce.

A good event bus therefore needs clear event contracts, registration rules, logging, and a discoverable way to understand handler relationships.

Observer vs. message queue

A message queue introduces a different set of guarantees and operational capabilities.

A typical in-process Observer implementation delivers notifications to registered objects in the current process. If the process exits before an observer finishes, the notification may be lost.

A durable message queue can store messages for consumers to process later. Depending on the system, it may support acknowledgments, redelivery, delayed retries, consumer groups, and backpressure.

ConcernIn-process ObserverDurable message queue
CommunicationUsually within one processCommonly across processes or services
Delivery after process failureNot guaranteed by the patternSupported when configured with durable storage and appropriate acknowledgments
Retry mechanismMust be implemented separatelyOften provided or supported by the broker and consumer
Operational complexityRelatively lowHigher: infrastructure, monitoring, delivery semantics
Typical useLocal reactions and module decouplingReliable asynchronous processing and distributed workloads

A message queue does not automatically guarantee exactly-once business effects. Consumers may receive messages more than once, and idempotency may still be necessary.

Similarly, an event bus does not automatically imply a distributed architecture. It can be a simple in-memory dispatcher.

Choose based on required guarantees, not naming conventions.

7. Observer in Real Backend Systems

Observer can be useful in several backend scenarios, provided the event semantics are appropriate.

Domain events within an application

An order domain operation may emit an event after an order transitions into a meaningful state.

Local handlers can react to that event without requiring the order's core logic to directly depend on every reaction.

This works best when the event represents a meaningful business fact, such as OrderPlaced or PaymentAuthorized, rather than a vague technical event such as SomethingChanged.

Domain events should reflect something that has actually happened. If an event is published before the corresponding state change is committed, subscribers may observe a fact that later proves false.

Application lifecycle hooks

An application may need to run handlers when a module starts, a connection becomes available, or a background worker shuts down.

Observer-style hooks allow independent modules to register lifecycle reactions without forcing the lifecycle owner to know each module's implementation.

For shutdown hooks, execution order and completion matter. A process should not exit before required cleanup has finished.

Extensible plugin systems

A plugin architecture may allow modules to register handlers for specific events.

For example, a plugin can react to a file upload or a completed job without requiring the core module to import the plugin directly.

However, plugin systems need explicit rules about registration, permissions, error isolation, and lifecycle management. Observer provides the notification relationship, not the complete plugin architecture.

When persistence and messaging must remain consistent

There is a particularly important backend problem: saving business state and publishing an event are often two separate operations.

Consider:

typescript
await orderRepository.save(order);
await messageBroker.publish({
  type: "order.created",
  orderId: order.id,
});

What happens if the database save succeeds but the broker publish fails?

The order exists, but downstream consumers never receive the event.

Reversing the order creates the opposite problem: a message may be published for an order that was never successfully persisted.

For workflows where this inconsistency is unacceptable, a common solution is the Transactional Outbox Pattern. The application writes both the business change and an outbox record in the same database transaction. A separate publisher then delivers the outbox event to the broker and tracks delivery.

This is not a feature of Observer. It is an additional reliability pattern for coordinating persisted state and event publication.

Use it when the business requires reliable event propagation and the database and message broker cannot participate in one shared atomic transaction.

8. Common Design Mistakes

Using events for every interaction

Not every method call should become an event.

If a component needs a result immediately, direct invocation may communicate that relationship more clearly.

Events are especially useful for announcing facts or decoupling reactions, not for obscuring simple request-response operations.

Hiding critical workflow steps

If order creation requires payment authorization before the order can be accepted, treating payment authorization as an arbitrary observer may make the workflow's requirements unclear.

Critical operations should be orchestrated explicitly or represented through a clearly defined workflow. Optional side effects are better candidates for independent observers.

Publishing vague or unstable events

Events are contracts. Names and payloads should convey meaningful facts and should evolve deliberately.

An event such as order.created should have a clear definition of when an order is considered created. Changing that meaning can break subscribers even if the TypeScript interface remains unchanged.

Swallowing failures without observability

Ignoring observer failures may make the primary operation appear reliable while secondary workflows silently stop working.

If the application intentionally allows noncritical observers to fail independently, record failures and provide enough context to investigate them.

Assuming execution is asynchronous because a method returns a promise

A publisher can wait for asynchronous observers, run them concurrently, or return before they complete. These are different execution models.

Document the chosen semantics, particularly when consumers depend on ordering or error propagation.

Using an in-memory event bus for durable business work

An in-memory event bus is not a replacement for durable delivery, retry management, or cross-process communication.

If an event must survive process failure, design the persistence and delivery mechanism accordingly.

9. When Not to Use Observer

Observer adds value when multiple independent components need to react to an event and direct coupling between them is undesirable.

It may be unnecessary when:

  • There is only one reaction and a direct method call is clearer.
  • The workflow is small and its steps must execute in a specific sequence.
  • The caller needs the result of a reaction before it can continue.
  • The event hides a dependency that should be explicit.
  • The application requires durable delivery but has only an in-memory notification mechanism.

A simple example illustrates the point.

If creating an order must immediately calculate tax and validate inventory, the workflow may be clearer when these operations are explicit dependencies of an application service.

If creating an order should also trigger analytics and a noncritical email notification, independent event handlers may be appropriate.

The distinction depends on business semantics, failure handling, and the guarantees the application needs.

Do not choose Observer because it reduces the number of imports. Choose it when independent reactions should be able to evolve without tightly coupling the producer to each consumer.

Summary

The Observer Pattern separates event producers from the components that react to their notifications.

It is useful when a single event may trigger multiple independent reactions and the producer should not need to manage each reaction directly.

A good implementation makes several decisions explicit:

  • What constitutes an event, and when is it published?
  • Who can subscribe, and how are subscriptions removed?
  • Are observers executed sequentially or concurrently?
  • How are failures reported and isolated?
  • Does the event need to survive process failure?
  • Are observers optional reactions or required steps in a business workflow?

Observer, callbacks, event buses, and message queues may appear similar, but they operate at different levels and provide different capabilities.

Start with direct calls when they express the workflow clearly. Use Observer when independent subscribers provide a real architectural benefit. Introduce durable messaging and patterns such as Transactional Outbox when reliability requirements go beyond in-process notification.

Decoupling event producers from consumers is valuable—but only when the delivery, failure, and lifecycle semantics are just as carefully designed as the abstraction itself.

  • Design Patterns
  • Observer Pattern
  • OOP
  • Programing
  • Software Architecture
  • Event-Driven Architecture
  • Event Bus
  • Publish-Subscribe Pattern
  • Message Queue
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.