Skill: quochungto/bookforge-event-driven-topology-selector (version 1.0.0)

--- name: event-driven-topology-selector description: Choose between broker and mediator event-driven topologies based on workflow control needs, error handling requirements, and performance trade-offs. Use this skill whenever the user is designing an event-driven system, choosing between choreography and orchestration, deciding how events should flow between processors, debating broker vs mediator, building async workflows, evaluating event-driven error handling strategies, or comparing request-based vs event-based communication models — even if they don't use the terms "broker" or "mediator." version: 1.0.0 homepage: https://github.com/bookforge-ai/bookforge-skills/tree/main/books/fundamentals-of-software-architecture/skills/event-driven-topology-selector metadata: {"openclaw":{"emoji":"📚","homepage":"https://github.com/bookforge-ai/bookforge-skills"}} status: draft depends-on: [] source-books: - id: fundamentals-of-software-architecture title: "Fundamentals of Software Architecture" authors: ["Mark Richards", "Neal Ford"] chapters: [14] tags: [software-architecture, architecture, event-driven, broker, mediator, choreography, orchestration, async, messaging, error-handling] execution: tier: 1 mode: full inputs: - type: none description: "System description and event processing requirements — the skill guides topology selection" tools-required: [Read, Write] tools-optional: [Grep, Glob] mcps-required: [] environment: "Any agent environment." --- # Event-Driven Topology Selector ## When to Use You are designing or evaluating an event-driven architecture and need to choose between broker topology (decentralized event chains) and mediator topology (centralized event orchestration). Typical situations: - Building a new event-driven system and need to decide how events flow - Evaluating whether existing event workflows need central coordination - Debugging error handling problems in an async system — events are being lost or workflows get stuck - Comparing choreography vs orchestration for inter-service communication - Deciding whether a use case is better served by request-based or event-based processing - System has a mix of simple and complex workflows — need to choose the right topology for each Before starting, verify: - Has the team already decided on event-driven architecture? If not, this skill selects the TOPOLOGY within event-driven, not whether to use event-driven at all. - Does the system have async processing needs? If everything is synchronous request-reply, event-driven may not be the right style — consider request-based model first. ## Context & Input Gathering ### Input Sufficiency Check This skill depends on understanding the WORKFLOW characteristics, not just the system description. The same system may need different topologies for different workflows. ### Required Context (must have — ask if missing) - **System description and use cases:** What does the system do? What events need to be processed? - Check prompt for: system purpose, event types, processing steps, workflow descriptions - If missing, ask: "What does your system do, and what events or workflows need to be processed asynchronously?" - **Workflow dependencies:** Are processing steps independent or do they depend on each other? - Check prompt for: step ordering, conditional logic, rollback needs, parallel vs sequential - If missing, ask: "When an event occurs, do the processing steps depend on each other (step B needs step A's result), or can they all happen independently in parallel?" - **Error handling requirements:** What happens when a processing step fails? - Check prompt for: rollback, compensation, retry, notification, data consistency needs - If missing, ask: "When a processing step fails (e.g., payment declined), do you need to (a) roll back previous steps, (b) retry automatically, (c) just log and continue, or (d) halt everything until resolved?" - **WHY this is critical:** Error handling is the single biggest differentiator between broker and mediator. Broker topology has no built-in error handling — failed events are silently lost unless you build custom recovery. ### Observable Context (gather from environment) - **Existing messaging infrastructure:** What message brokers or event systems are in place? - Look for: RabbitMQ, Kafka, ActiveMQ, AWS SQS/SNS configs, event bus implementations - Reveals: whether infrastructure already favors one topology - **Current event patterns:** Are there existing event handlers or processors? - Look for: event handler classes, message consumers, saga implementations - Reveals: current topology direction and complexity level ### Default Assumptions - If error handling requirements unknown, assume they ARE important (safer to recommend mediator and simplify than to recommend broker and discover you need coordination later) - If workflow complexity unknown, assume moderate complexity (some dependencies between steps) - If performance requirements unspecified, assume standard (not sub-millisecond) ### Sufficiency Threshold ``` SUFFICIENT: system description + workflow dependencies + error handling needs are known MUST ASK: error handling requirements are unknown (this drives the entire topology decision) PROCEED WITH DEFAULTS: workflow dependencies partially known but error handling is clear ``` ## Process ### Step 1: Determine If Event-Based Model Is Appropriate **ACTION:** Evaluate whether the use case is better served by a request-based or event-based processing model. **WHY:** Not everything should be event-driven. Request-based models are better when processing is data-driven, deterministic, and needs a direct response. Event-based models are better when processing is reactive, requires high responsiveness, and the system must adapt to situations as they arise. Choosing the wrong model wastes the entire topology analysis. | Dimension | Request-Based | Event-Based | |-----------|:---:|:---:| | Communication style | Synchronous | Asynchronous | | Data access | Request-reply (ask for data) | Fire-and-forget (react to events) | | Determinism | High — same request gives same path | Lower — event chains are dynamic | | Responsiveness | Moderate (bound by slowest step) | High (immediate acknowledgment) | | Typical use case | "Get me the order history" | "A bid was placed, react to it" | | Workflow control | Easy (caller controls the flow) | Hard (no single controller in broker) | | Error handling | Straightforward (caller gets error) | Complex (no caller waiting) | **IF** the use case is purely data-retrieval with synchronous needs, recommend request-based model. Stop here. **ELSE** proceed to Step 2. ### Step 2: Map the Workflow Characteristics **ACTION:** For each identified workflow/use case, map its characteristics across the 7 comparison dimensions. **WHY:** Broker and mediator topologies have opposite strengths. Mapping the workflow against these dimensions prevents gut-feel decisions and reveals which trade-offs matter most for THIS specific system. For each workflow, evaluate: | Dimension | Favors Broker | Favors Mediator | |-----------|:---:|:---:| | **Workflow control** | No coordination needed — events flow freely | Steps must execute in specific order with conditions | | **Error handling** | Errors are tolerable or self-healing | Failures require rollback, compensation, or retry coordination | | **Recoverability** | System can recover organically | Must be able to recover to a known state | | **Restart capability** | No need to restart a failed workflow | Must restart workflows from point of failure | | **Scalability need** | Maximum throughput is critical | Moderate throughput is acceptable | | **Performance need** | Sub-millisecond or very high performance | Standard latency is acceptable | | **Fault tolerance** | Individual processor failure is acceptable | Single processor failure must not break the chain | ### Step 3: Select the Topology **ACTION:** Based on the dimension mapping, recommend broker, mediator, or hybrid topology. **WHY:** The choice is fundamentally a trade-off between workflow control and error handling capability (mediator) versus high performance and scalability (broker). Neither is inherently better — it depends entirely on which dimensions the system prioritizes. **Decision logic:** **IF** workflow steps are independent AND error handling is not critical AND performance/scalability are top priorities: - **Recommend BROKER topology** - Processors are self-contained, events chain through channels - No central coordinator — maximum decoupling and performance - Each processor advertises what it did; other processors react **IF** workflow steps have dependencies AND error handling/recoverability are important AND workflow must be coordinated: - **Recommend MEDIATOR topology** - Central mediator orchestrates the processing steps - Mediator knows the workflow, manages state, handles errors - Processing events are commands (things to do) not events (things that happened) **IF** system has BOTH types of workflows: - **Recommend HYBRID topology** - Use mediator for complex workflows requiring coordination - Use broker for simple, independent event chains - Route through a simple mediator that classifies events and delegates ### Step 4: Determine Mediator Complexity Level (If Mediator Selected) **ACTION:** If mediator topology was selected, determine the appropriate mediator implementation complexity. **WHY:** Mediators range from simple source-code routers to full BPM engines. Over-engineering the mediator wastes months; under-engineering it creates a bottleneck that can't handle the workflow complexity. Matching mediator complexity to workflow complexity is critical. | Mediator Type | Use When | Implementation | |---------------|----------|----------------| | **Simple mediator** | Linear workflows, basic error handling, routing logic | Source code (e.g., Apache Camel, Spring Integration, custom code) | | **Hardcoded mediator** | Complex conditional workflows, multiple dynamic paths, structured error handling | BPEL engine (e.g., Apache ODE, Oracle BPEL Process Manager) | | **Complex mediator (BPM)** | Long-running transactions, human intervention points, complex state machines | BPM engine (e.g., jBPM, Camunda) | **Classify each event type:** Determine if it's simple, hard, or complex. Route through the simple mediator first — it classifies and delegates to the appropriate mediator type. This delegation model handles mixed-complexity events efficiently. ### Step 5: Address Error Handling and Data Loss Prevention **ACTION:** Design the error handling strategy based on the selected topology. **WHY:** Asynchronous event-driven architectures have THREE points where data loss can occur in the async communication chain. Protecting only one point still leaves the system vulnerable at the other two. Most architects only think about the message queue and forget about the send and acknowledgment links. **The three data loss points:** 1. **Message send (producer to queue):** Event is created but never reaches the queue - **Mitigation:** Synchronous send with broker acknowledgment. Use persistent message queues. The producer waits for confirmation that the message was persisted before proceeding. 2. **Message processing (queue to consumer):** Event is dequeued but consumer crashes before processing - **Mitigation:** Client acknowledge mode (not auto-acknowledge). The message stays on the queue until the consumer explicitly acknowledges successful processing. If the consumer crashes, the message is re-delivered. 3. **Post-processing (consumer to database):** Event is processed but the database write fails - **Mitigation:** Use the last participant support pattern — the database commit and the message acknowledgment happen in the same transaction scope. If the DB fails, the message is not acknowledged and will be redelivered. **For broker topology error handling:** - Implement the **workflow event pattern**: a dedicated error-handling event processor monitors for failures and can trigger compensating actions - Use **dead letter queues** for events that fail repeatedly — prevents infinite retry loops and allows manual inspection **For mediator topology error handling:** - The mediator itself manages error state — it knows which step failed and can stop the workflow - Mediator persists workflow state, enabling restart from point of failure - Compensating transactions can be orchestrated by the mediator (e.g., reverse payment if shipping fails) ### Step 6: Produce the Topology Recommendation **ACTION:** Compile the complete topology recommendation with rationale. **WHY:** The recommendation must be specific enough to implement. A vague "use mediator" without explaining the error handling strategy, data loss prevention, and mediator complexity level leaves the team to figure out the hard parts on their own. ## Inputs - System description and event processing use cases - Workflow dependencies and ordering requirements - Error handling and data consistency requirements - Performance and scalability targets (if known) ## Outputs ### Event-Driven Topology Recommendation ```markdown # Event-Driven Topology Recommendation: {System Name} ## Request-Based vs Event-Based Assessment **Model selected:** {Request-based / Event-based / Mixed} **Rationale:** {why this model fits} ## Workflow Analysis | Workflow | Steps | Dependencies | Error Handling Need | Topology | |----------|-------|:---:|:---:|:---:| | {workflow 1} | {step list} | Independent / Dependent | Low / Medium / High | Broker / Mediator | | {workflow 2} | ... | ... | ... | ... | ## Topology Decision ### Selected: {Broker / Mediator / Hybrid} **Primary driver:** {the dimension that tipped the decision} ### 7-Dimension Trade-off Assessment | Dimension | This System's Need | Broker | Mediator | Fit | |-----------|-------------------|:---:|:---:|:---:| | Workflow control | {need level} | Low | High | {which fits} | | Error handling | {need level} | Low | High | {which fits} | | Recoverability | {need level} | Low | High | {which fits} | | Restart capability | {need level} | Low | High | {which fits} | | Scalability | {need level} | High | Moderate | {which fits} | | Performance | {need level} | High | Moderate | {which fits} | | Fault tolerance | {need level} | High | Low | {which fits} | ## Mediator Complexity (if applicable) **Level:** {Simple / Hardcoded / Complex (BPM)} **Implementation suggestion:** {specific technology recommendation} **Rationale:** {why this complexity level} ## Error Handling Strategy **Data loss prevention:** - Message send: {mitigation} - Message processing: {mitigation} - Post-processing: {mitigation} **Error recovery pattern:** {workflow event pattern / dead letter queue / mediator-managed / combination} ## Architecture Characteristics Impact - Performance: {stars}/5 - Scalability: {stars}/5 - Fault tolerance: {stars}/5 - Evolutionary: {stars}/5 - Testability: {stars}/5 ``` ## Key Principles - **The choice is workflow control vs performance** — Broker topology maximizes performance, scalability, and decoupling. Mediator topology maximizes workflow control, error handling, and recoverability. Neither is inherently better. The decision hinges on which of these your system values more. - **Events vs commands reveal the topology** — In broker topology, processing events describe what HAPPENED (order-created, payment-applied). In mediator topology, processing events are COMMANDS telling processors what to DO (place-order, apply-payment). If your events are naturally commands with expected outcomes, you need a mediator. - **Error handling is the deal-breaker** — If a processing step can fail and the failure requires coordinated recovery (rollback, compensation, retry), broker topology cannot handle this without significant custom infrastructure. The mediator exists precisely for this scenario. When in doubt about error handling needs, lean toward mediator. - **Protect all three links in the async chain** — Data loss can occur at message send, message processing, and post-processing. Most architects only protect the message queue itself (persistence) but forget about the send confirmation and the consumer acknowledgment. All three must be addressed. - **Hybrid is often the right answer** — Real systems rarely have uniformly simple or uniformly complex workflows. A simple mediator that classifies incoming events and delegates simple ones to broker-style processing while routing complex ones through a full mediator gives the best of both worlds. - **Match mediator complexity to workflow complexity** — Using a BPM engine for simple routing wastes months of effort. Using source-code routing for complex workflows with human intervention points creates unmaintainable spaghetti. Classify your events (simple/hard/complex) and pick the mediator type accordingly. ## Examples **Scenario: Order fulfillment with payment rollback** Trigger: "We're building an order fulfillment system. When a customer places an order, we need to validate inventory, charge payment, send confirmation email, update warehouse, and notify shipping. If payment fails, we need to rollback the inventory reservation." Process: Mapped workflow — steps have dependencies (payment must succeed before fulfillment). Error handling is critical (payment failure requires inventory rollback). This is a coordinated workflow with compensation requirements. Evaluated 7 dimensions: workflow control = high need, error handling = high need, recoverability = high need. Performance and scalability are standard. All three critical dimensions favor mediator. Output: **Mediator topology.** Simple mediator implementation (source code, e.g., custom orchestrator or Apache Camel). 5-step workflow: (1) create order, (2) process order (email + payment + inventory in parallel), (3) fulfill order, (4) ship order, (5) notify customer. Mediator waits for acknowledgment from parallel step 2 processors before proceeding. If payment fails at step 2, mediator triggers inventory rollback and halts workflow. Data loss prevention: persistent queues with synchronous send, client-acknowledge mode, last-participant-support for DB writes. **Scenario: Social media fan-out with independent processors** Trigger: "Users post content that needs to: update feeds, notify followers, run content moderation, update search index, and generate analytics. These are all independent." Process: Mapped workflow — all steps are independent (no ordering, no dependencies). Error handling is low priority (if search indexing fails, it can retry independently without affecting other steps). Evaluated 7 dimensions: workflow control = not needed, error handling = low (each processor handles its own), scalability = high (viral posts need fan-out), performance = high (real-time feed updates). All critical dimensions favor broker. Output: **Broker topology.** Post-created initiating event fans out to 5 independent event processors. Each processor publishes its own processing event (feed-updated, followers-notified, etc.) for extensibility. No mediator needed — processors are self-contained. Dead letter queues for each processor to catch persistent failures. Per-processor scaling based on load. **Scenario: Mixed workloads — trading platform with compliance** Trigger: "Trade events need sub-millisecond processing. We also have compliance reporting that aggregates trades daily with complex rules." Process: Identified two distinct workflows. Trade execution: independent, performance-critical, fault-tolerant — classic broker. Compliance reporting: complex rules, conditional paths, must complete all steps, needs audit trail — classic mediator. Recommended hybrid topology. Output: **Hybrid topology.** Trade execution path uses broker topology for maximum performance — trade-executed events fan out to position tracking, risk calculation, and P&L processors independently. Compliance reporting path uses mediator topology — daily compliance mediator orchestrates trade aggregation, rule evaluation, exception flagging, and report generation in sequence. Simple event router at entry point classifies events by type and delegates to the appropriate topology. Trade path uses Kafka for high-throughput; compliance path uses RabbitMQ with a lightweight orchestrator. ## References - For the detailed broker vs mediator comparison table with full trade-off analysis, see [references/broker-vs-mediator-comparison.md](references/broker-vs-mediator-comparison.md) ## License This skill is licensed under [CC-BY-SA-4.0](https://creativecommons.org/licenses/by-sa/4.0/). Source: [BookForge](https://github.com/bookforge-ai/bookforge-skills) — Fundamentals of Software Architecture by Mark Richards, Neal Ford. ## Related BookForge Skills This skill is standalone. Browse more BookForge skills: [bookforge-skills](https://github.com/bookforge-ai/bookforge-skills)

path: references/broker-vs-mediator-comparison.md
content: # Broker vs Mediator Topology — Detailed Comparison

Read this reference when you need the full trade-off details for broker and mediator topologies, including architecture characteristics ratings, implementation guidance, and anti-pattern warnings.

## Topology Overview

### Broker Topology

**Architecture components:** Initiating event, event broker (message broker), event processors, processing events.

**How it works:**
1. An initiating event enters the system (e.g., PlaceOrder)
2. The event is sent to an event channel in the event broker
3. A single event processor picks up the initiating event and processes it
4. That processor advertises what it did by publishing a processing event
5. Other processors react to the processing event, do their work, and publish their own processing events
6. This chain continues until no processor is interested in the latest processing event

**Key metaphor:** A relay race. Each runner (processor) takes the baton, runs their leg, and hands off. Once they hand off, they're done. No coach (mediator) tells them what to do.

**Event broker implementation:** Usually federated (multiple domain-based clustered instances). Uses topics (publish-subscribe) for the fire-and-forget broadcasting model. Technologies: RabbitMQ, ActiveMQ, HornetQ, Kafka.

**Best practice:** Every event processor should advertise what it did, even if no other processor currently cares. This provides architectural extensibility — new processors can tap into existing event streams without modifying the producers.

### Mediator Topology

**Architecture components:** Initiating event, event queue, event mediator, event channels, event processors.

**How it works:**
1. An initiating event enters the system and is placed on an event queue
2. The event mediator picks up the event from the queue
3. The mediator knows the workflow steps required to process this event
4. The mediator generates processing events (commands) sent to dedicated event channels (point-to-point queues)
5. Event processors listen on their dedicated channels, process the command, and respond back to the mediator
6. The mediator waits for acknowledgment before proceeding to the next step
7. Steps within a workflow group execute concurrently; steps across groups execute serially

**Key metaphor:** An orchestra conductor. The conductor (mediator) knows the score (workflow), directs each section (processors) when to play, and coordinates the overall performance.

**Processing event semantics:** In the mediator topology, processing events are COMMANDS — things that NEED to happen (place-order, send-email, apply-payment). In broker topology, they are EVENTS — things that HAVE happened (order-created, email-sent, payment-applied). This semantic difference is fundamental.

## Trade-Off Comparison Table

### Broker Topology

| Advantage | Detail |
|-----------|--------|
| Highly decoupled event processors | Processors don't know about each other. Adding/removing processors requires no changes to others. |
| High scalability | Each processor scales independently. No bottleneck from a central coordinator. |
| High responsiveness | Events are processed as they arrive. No waiting for a coordinator to schedule. |
| High performance | No intermediary adds latency. Direct event-channel-to-processor communication. |
| High fault tolerance | One processor failing doesn't affect others. The broker provides back-pressure. |

| Disadvantage | Detail |
|-------------|--------|
| Workflow control | No component knows the overall workflow state. No one knows when a business transaction is "complete." |
| Error handling | If a processor crashes mid-processing, no component is aware. The business process gets stuck with no automatic recovery. Other processors continue as if everything is fine. |
| Recoverability | Because no component owns the workflow state, there's no way to recover to a known good state. |
| Restart capabilities | Cannot restart from point of failure. The initiating event has already been consumed and processed. Re-submitting it would duplicate work. |
| Data inconsistency | With no coordination, processors can get out of sync. Inventory may be decremented even when payment failed. |

### Mediator Topology

| Advantage | Detail |
|-----------|--------|
| Workflow control | The mediator knows the complete workflow. It knows which steps are done, which are pending, and what comes next. |
| Error handling | The mediator receives error responses from processors. It can stop the workflow, trigger compensation, or retry. |
| Recoverability | The mediator persists workflow state. If the mediator crashes, it can recover and resume from its persisted state. |
| Restart capabilities | Workflows can restart from the point of failure. The mediator knows exactly where the workflow stopped. |
| Better data consistency | The mediator coordinates steps, ensuring downstream steps don't execute until upstream steps succeed. |

| Disadvantage | Detail |
|-------------|--------|
| More coupling of event processors | Processors are coupled to the mediator's command structure. Adding a new step means changing the mediator. |
| Lower scalability | The mediator is a potential bottleneck. Although you can have multiple mediators per domain, each mediator instance is a single point of coordination. |
| Lower performance | The mediator adds an intermediary hop. Processing events go: processor -> mediator -> next processor, rather than processor -> broker -> next processor directly. |
| Lower fault tolerance | If the mediator goes down, all workflows it manages are halted. This is a single point of failure per domain. |
| Modeling complex workflows | Declaratively modeling dynamic, conditional processing in a mediator (especially BPEL) is difficult. Many workflows end up as hybrid (mediator for general flow, broker for dynamic parts). |

## 7-Dimension Direct Comparison

| Dimension | Broker | Mediator | Notes |
|-----------|:---:|:---:|-------|
| Workflow control | Low | High | The defining trade-off. Broker has NO workflow awareness. |
| Error handling | Low | High | Broker: errors are silent. Mediator: errors are caught and managed. |
| Recoverability | Low | High | Broker: no state to recover. Mediator: persists workflow state. |
| Restart | Low | High | Broker: can't restart. Mediator: restarts from point of failure. |
| Scalability | High | Moderate | Broker: no bottleneck. Mediator: coordinator can bottleneck. |
| Performance | High | Moderate | Broker: direct communication. Mediator: extra hop through coordinator. |
| Fault tolerance | High | Low | Broker: isolated failures. Mediator: coordinator is SPOF. |

## Architecture Characteristics Ratings (Event-Driven Overall)

| Characteristic | Rating | Notes |
|---------------|:---:|-------|
| Partitioning type | Technical | Events and processors organized by processing type |
| Number of quanta | 1 to many | Depends on topology and processor isolation |
| Deployability | 2/5 | Complex deployment due to event contracts and processor dependencies |
| Elasticity | 3/5 | Processors can scale independently (better in broker) |
| Evolutionary | 5/5 | Excellent — new processors added without changing existing ones |
| Fault tolerance | 5/5 | Processor isolation prevents cascading failures (better in broker) |
| Modularity | 4/5 | Good separation of processing concerns |
| Overall cost | 3/5 | Moderate — messaging infrastructure adds cost |
| Performance | 5/5 | Async processing eliminates blocking (better in broker) |
| Reliability | 3/5 | Moderate — async complexity can reduce reliability |
| Scalability | 5/5 | Excellent processor-level scaling (better in broker) |
| Simplicity | 1/5 | Low — async event flows are inherently complex to reason about |
| Testability | 2/5 | Low — testing async event chains is difficult |

## Mediator Complexity Levels — Detailed Guide

### Simple Mediator (Source Code)

**When to use:**
- Events require simple error handling and orchestration
- Workflows are mostly linear with basic conditional branching
- No long-running transactions or human intervention points

**Implementation options:** Apache Camel, Mule ESB, Spring Integration, custom source code (Java, C#, etc.)

**How it works:** Message flows and routes are written in programming code. The mediator intercepts events, classifies them (simple/hard/complex), and either processes them directly or delegates to more capable mediators.

**Advantages:** Easy to write and maintain. Fast to develop. Good for 80% of events.

### Hardcoded Mediator (BPEL)

**When to use:**
- Complex conditional processing with multiple dynamic paths
- Structured error handling with redirection and multicasting
- Workflows that are well-defined but have many branches

**Implementation options:** Apache ODE, Oracle BPEL Process Manager

**How it works:** Uses Business Process Execution Language (BPEL), an XML-like structure describing processing steps, error handling, redirection, and multicasting. Usually created via graphical interface tools.

**Advantages:** Declarative workflow definition. Good tooling for visualization. Handles complex branching well.

**Limitations:** Does NOT handle long-running transactions with human intervention. BPEL is powerful but relatively complex to learn.

### Complex Mediator (BPM)

**When to use:**
- Long-running transactions requiring human intervention
- Workflows that pause and wait for external actions (approvals, manual reviews)
- Complex state machines with many possible states

**Implementation options:** jBPM, Camunda, Activiti

**How it works:** Uses Business Process Management engines that support human task management, timers, complex state transitions, and long-running process instances.

**Example:** A stock trade where the mediator must pause processing, notify a senior trader for manual approval (because the trade exceeds a threshold), and wait for the approval before continuing.

**Advantages:** Handles human-in-the-loop workflows. Persistent process state. Resume from any point.

**Limitations:** Heavy infrastructure. Overkill for simple event routing.

### Mediator Delegation Model

Given that real systems have a MIX of simple, hard, and complex events, the recommended approach is:

1. ALL events enter through a **Simple Event Mediator** (source code)
2. The simple mediator classifies each event as simple, hard, or complex
3. Simple events are processed directly by the simple mediator
4. Hard events are forwarded to the **BPEL mediator**
5. Complex events are forwarded to the **BPM mediator**

This delegation model ensures each event type is processed by the mediator with the appropriate capability level, without over-engineering simple cases or under-engineering complex ones.

## Error Handling Patterns

### Workflow Event Pattern (Broker Topology)

Since broker topology has no central coordinator for error handling, the **workflow event pattern** provides a mechanism:

1. A dedicated **workflow processor** monitors the event flow
2. When it detects a failure (processor doesn't emit expected processing event within timeout), it generates a corrective workflow event
3. Other processors react to the corrective event (e.g., reverse inventory, issue refund)

**Limitation:** This effectively rebuilds mediator-like coordination on top of broker topology. If you need extensive use of this pattern, you probably need a mediator.

### Dead Letter Queues

For events that fail processing repeatedly:

1. After N retry attempts, move the failed event to a **dead letter queue**
2. Dead letter queues are monitored for manual inspection and resolution
3. Prevents infinite retry loops that waste resources
4. Provides an audit trail of failed events

### Data Loss Prevention — The Three-Link Chain

Every asynchronous message exchange has three potential failure points:

```
[Producer] ---(Link 1)---> [Message Queue] ---(Link 2)---> [Consumer] ---(Link 3)---> [Database]
```

| Link | Failure Mode | Prevention |
|------|-------------|------------|
| **Link 1: Send** | Producer sends message but it doesn't reach the queue (network failure, broker down) | Use **synchronous send** with broker acknowledgment. Producer blocks until broker confirms message persistence. |
| **Link 2: Processing** | Message is dequeued but consumer crashes before completing processing | Use **client acknowledge mode** (not auto-acknowledge). Message stays on queue until consumer explicitly acknowledges. On crash, message is redelivered to another consumer instance. |
| **Link 3: Post-processing** | Consumer processes message but database write fails | Use **last participant support** pattern. Database commit and message acknowledgment are in the same transaction scope. If DB fails, message is not acknowledged and will be redelivered. |

**Critical insight:** Most architects protect only Link 2 (persistent message queues). This still leaves data loss at Link 1 (fire-and-forget sends) and Link 3 (process-then-ack without DB transaction). ALL THREE links must be protected for reliable event processing.

## Request-Based vs Event-Based Model Comparison

Use this table when deciding whether a use case should be event-driven at all, before selecting broker vs mediator.

| Dimension | Request-Based | Event-Based |
|-----------|:---:|:---:|
| **Communication** | Synchronous request-reply | Asynchronous fire-and-forget |
| **Coupling** | Higher (caller knows the callee) | Lower (publisher doesn't know subscribers) |
| **Data pattern** | Pull: ask for data | Push: react to occurrences |
| **Determinism** | High: same request, same processing path | Lower: event chains are dynamic |
| **Responsiveness** | Bound by total processing time | Immediate acknowledgment |
| **Scalability** | Limited by synchronous chain | High: processors scale independently |
| **Error handling** | Simple: caller gets error response | Complex: no caller waiting for response |
| **Workflow visibility** | Clear: follow the request path | Opaque: follow event chains across processors |

**Use request-based when:** Retrieving data, synchronous operations, well-defined request-response patterns, when the caller needs an immediate answer.

**Use event-based when:** Reacting to situations, high responsiveness needed, fire-and-forget operations, multiple independent processors need to react to the same occurrence.


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)