---
name: pub-sub
description: This skill should be used when the user asks about "pub sub pattern", "publish subscribe", "event distribution", "message broadcast", "decoupled messaging", or mentions one-to-many event communication with loose coupling.
version: 1.0.0
---

# Publish-Subscribe Pattern

## What Is It
Pub-Sub decouples message producers (publishers) from consumers (subscribers) via a message broker. Publishers emit messages to topics; subscribers receive all messages from topics they subscribe to.

## When to Use
- **Loose coupling** - Publishers don't know subscribers
- **One-to-many** - One event, multiple handlers
- **Distributed systems** - Services communicate async
- **Scalable messaging** - Handle high throughput

## When NOT to Use
- **Request-response** - Need synchronous reply
- **Simple events** - Observer pattern simpler
- **Guaranteed delivery** - Need transactions
- **Low latency** - Broker adds delay

## How to Implement

```typescript
type MessageHandler = (message: unknown) => void;

class PubSub {
  private topics = new Map<string, Set<MessageHandler>>();

  subscribe(topic: string, handler: MessageHandler): () => void {
    if (!this.topics.has(topic)) {
      this.topics.set(topic, new Set());
    }
    this.topics.get(topic)!.add(handler);

    // Return unsubscribe function
    return () => {
      this.topics.get(topic)?.delete(handler);
    };
  }

  publish(topic: string, message: unknown): void {
    const handlers = this.topics.get(topic);
    if (handlers) {
      for (const handler of handlers) {
        handler(message);
      }
    }
  }
}

// Usage
const pubsub = new PubSub();
const unsub = pubsub.subscribe("user.created", (msg) => {
  console.log("New user:", msg);
});

pubsub.publish("user.created", { id: 1, name: "Alice" });
unsub(); // Unsubscribe
```

## Code Examples
- `examples/pub-sub.ts` - Basic implementation
- `examples/pub-sub-advanced.ts` - Real-world usage

## Related Patterns
- **Observer** - Synchronous variant
- **Mediator** - Central coordinator
- **Message Queue** - Persistent variant
