---
name: producer-consumer
description: This skill should be used when the user asks about "producer consumer pattern", "when to use producer consumer", "message queue", "bounded buffer", "task distribution", or mentions needing to decouple task production from consumption.
version: 1.0.0
---

# Producer-Consumer Pattern

## What Is It
The Producer-Consumer pattern decouples the production of work items from their consumption. Producers generate tasks/data and place them in a buffer, while consumers retrieve and process them. This enables asynchronous processing and load balancing.

## When to Use
- **Message queues** - Email sending, notifications, webhooks
- **Log processing** - Centralized log aggregation
- **Event streaming** - Real-time data pipelines
- **Task distribution** - Work distribution across workers
- **Video/image processing** - Frame-by-frame processing
- **Order processing** - Async order fulfillment

## When NOT to Use
- **Synchronous processing** - Direct calls are simpler
- **Single producer/consumer** - No decoupling benefit
- **Real-time requirements** - Buffer adds latency
- **Memory constrained** - Buffer requires memory

## How to Implement

### Implementation Steps
1. Create a shared buffer/queue with fixed capacity
2. Producers add items to the buffer (block if full)
3. Consumers remove items from buffer (block if empty)
4. Handle synchronization for thread safety
5. Implement graceful shutdown

### TypeScript Implementation

```typescript
class BoundedBuffer<T> {
  private buffer: T[] = [];
  private waiters: Array<(item: T) => void> = [];

  constructor(private capacity: number) {}

  async put(item: T): Promise<void> {
    if (this.buffer.length < this.capacity) {
      this.buffer.push(item);
    }
    // Handle full buffer with backpressure
  }

  async take(): Promise<T> {
    if (this.buffer.length > 0) {
      return this.buffer.shift()!;
    }
    // Wait for item to be available
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/producer-consumer.ts` - Basic implementation with bounded buffer
- `examples/producer-consumer-advanced.ts` - Real-world example with event streaming

## Related Patterns
- **Thread Pool** - Consumers often use a thread pool
- **Observer** - Can notify consumers of new items
- **Command** - Items can be Command objects
