> ## Documentation Index
> Fetch the complete documentation index at: https://www.docs.wazap.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Message Buffer System

> Group messages for better context and performance

## Overview

The Message Buffer System groups messages from the same phone number during a configurable time period. This is **optional** and **backwards compatible**.

## Quick Setup

Just add `enableBuffer: true` to your webhook processor:

```typescript theme={null}
const webhookProcessor = client.createWebhookProcessor({
  enableBuffer: true,        // Enable buffer
  bufferTimeMs: 10000,      // Wait 10 seconds
  maxBatchSize: 50,         // Max 50 messages per batch

  onTextMessage: async (messages) => {
    // Can receive 1 message or array of messages
    if (Array.isArray(messages)) {
      console.log(`Batch of ${messages.length} messages`);
    } else {
      console.log(`Single message: ${messages.text}`);
    }
  }
});
```

## Why Use It?

* **AI Bots**: Get complete conversation context
* **Performance**: Reduce handler calls for message bursts
* **Analysis**: Process related messages together

Example: User sends 3 messages quickly

* **Without buffer**: 3 separate handler calls
* **With buffer**: 1 handler call with all 3 messages

## Configuration

| Option         | Default | Description               |
| -------------- | ------- | ------------------------- |
| `enableBuffer` | `false` | Enable message buffering  |
| `bufferTimeMs` | `5000`  | Wait time in milliseconds |
| `maxBatchSize` | `100`   | Max messages per batch    |

## Basic Example

```typescript theme={null}
const processor = client.createWebhookProcessor({
  enableBuffer: true,
  bufferTimeMs: 8000,  // 8 seconds
  maxBatchSize: 20,

  onTextMessage: async (messages) => {
    if (Array.isArray(messages)) {
      console.log(`Got ${messages.length} messages in batch`);
      for (const msg of messages) {
        await client.sendText(msg.from, `Batch: ${msg.text}`);
      }
    } else {
      await client.sendText(messages.from, `Single: ${messages.text}`);
    }
  }
});
```

## Without Buffer (Default)

Your existing code works unchanged:

```typescript theme={null}
const processor = client.createWebhookProcessor({
  onTextMessage: async (message) => {
    // Always single message
    await client.sendText(message.from, `Reply: ${message.text}`);
  }
});
```

## All Message Types Supported

Works with all handlers: `onTextMessage`, `onImageMessage`, `onButtonClick`, etc.

## Simple Pattern

```typescript theme={null}
onTextMessage: async (messages) => {
  // Always work with arrays
  const msgs = Array.isArray(messages) ? messages : [messages];

  for (const msg of msgs) {
    await client.sendText(msg.from, `Echo: ${msg.text}`);
  }
}
```
