# Best Practices

### 1. Error Handling

```typescript
try {
  await whatsapp.sendMessage(to, message);
} catch (error) {
  console.error('Failed to send message:', error);
  // Implement retry logic or alert
}
```

### 2. Message Validation

```typescript
whatsapp.setWebhookHandlers({
  onMessage: async (message, metadata) => {
    const text = message.text?.body;
    
    // Validate message exists
    if (!text) return;
    
    // Validate sender
    if (!metadata.waId) return;
    
    // Process message
    await processMessage(text, metadata.waId);
  }
});
```

### 3. Rate Limit Handling

```typescript
// Use queue for bulk operations
for (const recipient of largeRecipientList) {
  await whatsapp.sendMessage(recipient, message, {
    queueIfBusy: true
  });
  
  // Add small delay
  await new Promise(resolve => setTimeout(resolve, 100));
}
```

### 4. Storage Management

```typescript
// Enable auto-cleanup
const whatsapp = createWhatsAppHandler({
  storage: {
    type: 'memory',
    autoCleanup: true,
    maxMessagesPerConversation: 1000
  }
});

// Or manual cleanup
whatsapp.on('storageCleaned', (data) => {
  console.log(`Cleaned ${data.deletedCount} old messages`);
});
```

---