7
← Back to Pattern Arsenal
behavioral

Mediator

good to-know

Stage 1: Problem

The Problem

You are building a backend for a trading platform. When a trade is executed, several things must happen in coordination:

  • The OrderService validates the trade and locks the funds
  • The PricingService checks the current market price
  • The RiskService evaluates if the trade violates risk limits (depends on the user's portfolio from OrderService AND the price from PricingService)
  • The NotificationService notifies the user (but only if RiskService approves)
  • The AuditService logs everything regardless

The catch: RiskService needs data from both OrderService and PricingService before it can evaluate. NotificationService needs RiskService's result before it can send. The order of operations matters.

typescript
1class OrderService {
2 executeTrade(trade: Trade) {
3 const locked = this.lockFunds(trade);
4 // Now I need to tell PricingService, but also RiskService needs my result...
5 // And NotificationService needs to wait for RiskService...
6 // Who coordinates all this?
7 }
8}

Think about it: If each service calls the next one directly, how many direct dependencies will you have? What happens when you add a ComplianceService that needs data from 3 of the existing services?


Related Patterns

Confused With a Similar Pattern?

1 / 10 — Problem