NexisChat Docs
Evolution API LiteCore Concepts

Event System

Understanding the event-driven architecture for real-time WhatsApp updates in Evolution API Lite

Event System

Evolution API Lite features a comprehensive event-driven architecture that allows you to receive real-time updates about WhatsApp activities. The system supports multiple delivery methods including Webhooks, RabbitMQ, SQS, Pusher, and WebSockets.

Architecture Overview

The event system is built around the EventManager which coordinates event distribution across multiple channels:

Event Types

The system supports a comprehensive set of event types that cover all WhatsApp activities:

Connection Events

  • APPLICATION_STARTUP - API server startup
  • INSTANCE_CREATE - New instance created
  • INSTANCE_DELETE - Instance deleted
  • CONNECTION_UPDATE - Connection status changes
  • QRCODE_UPDATED - QR code updated for authentication
  • REMOVE_INSTANCE - Instance removed from memory
  • LOGOUT_INSTANCE - Instance logged out

Message Events

  • MESSAGES_SET - Initial message history loaded
  • MESSAGES_UPSERT - New messages received or sent
  • MESSAGES_EDITED - Messages edited
  • MESSAGES_UPDATE - Message status updated (delivered, read, etc.)
  • MESSAGES_DELETE - Messages deleted
  • SEND_MESSAGE - Message sent confirmation

Contact Events

  • CONTACTS_SET - Initial contacts loaded
  • CONTACTS_UPSERT - New contacts added or updated
  • CONTACTS_UPDATE - Contact information updated
  • PRESENCE_UPDATE - Contact presence status changed (online, offline, typing)

Chat Events

  • CHATS_SET - Initial chat list loaded
  • CHATS_UPSERT - New chats created or updated
  • CHATS_UPDATE - Chat information updated
  • CHATS_DELETE - Chats deleted

Group Events

  • GROUPS_UPSERT - Group information updated
  • GROUP_UPDATE - Group settings changed
  • GROUP_PARTICIPANTS_UPDATE - Group participants added/removed/promoted

Other Events

  • CALL - Incoming or outgoing calls
  • LABELS_EDIT - Message labels edited
  • LABELS_ASSOCIATION - Labels associated with messages
  • TYPEBOT_START - Typebot conversation started
  • TYPEBOT_CHANGE_STATUS - Typebot status changed

Event Delivery Methods

1. Webhooks

Webhooks deliver events via HTTP POST requests to your specified endpoints.

Configuration

# Global webhook configuration
WEBHOOK_GLOBAL_ENABLED=true
WEBHOOK_GLOBAL_URL=https://your-server.com/webhook
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false

# Event-specific configuration
WEBHOOK_EVENTS_MESSAGES_UPSERT=true
WEBHOOK_EVENTS_CONNECTION_UPDATE=true

Instance-Specific Webhooks

Configure webhooks per instance during creation:

curl -X POST http://localhost:8080/instance/create \
  -H "Content-Type: application/json" \
  -H "apikey: YOUR_GLOBAL_API_KEY" \
  -d '{
    "instanceName": "my-instance",
    "integration": "WHATSAPP-BAILEYS",
    "webhook": {
      "enabled": true,
      "url": "https://your-server.com/webhook",
      "byEvents": false,
      "base64": true,
      "headers": {
        "Authorization": "Bearer your-token"
      },
      "events": [
        "MESSAGES_UPSERT",
        "CONNECTION_UPDATE"
      ]
    }
  }'

Webhook Payload Format

{
  "event": "messages.upsert",
  "instance": "my-instance",
  "data": {
    "key": {
      "remoteJid": "5511999999999@s.whatsapp.net",
      "fromMe": false,
      "id": "3EB0C767D82B632A2E4A"
    },
    "message": {
      "conversation": "Hello World!"
    },
    "messageTimestamp": 1640995200,
    "pushName": "John Doe"
  },
  "destination": "https://your-server.com/webhook",
  "date_time": "2023-12-01T10:30:00.000Z",
  "sender": "5511999999999@s.whatsapp.net",
  "server_url": "http://localhost:8080",
  "apikey": "instance-token"
}

Webhook Features

  • Retry Logic: Automatic retry with exponential backoff (up to 10 attempts)
  • Custom Headers: Add authentication or custom headers
  • Event Filtering: Subscribe to specific events only
  • Base64 Media: Option to include media as base64 in webhook payload
  • By Events: Send events to different endpoints based on event type

2. RabbitMQ

Publish events to RabbitMQ exchanges for distributed processing.

Configuration

RABBITMQ_ENABLED=true
RABBITMQ_URI=amqp://localhost:5672
RABBITMQ_EXCHANGE_NAME=evolution_exchange
RABBITMQ_GLOBAL_ENABLED=true

# Event configuration
RABBITMQ_EVENTS_MESSAGES_UPSERT=true
RABBITMQ_EVENTS_CONNECTION_UPDATE=true

Exchange and Routing

  • Exchange Type: Topic exchange
  • Routing Key Pattern: {instanceName}.{event}
  • Example: my-instance.messages.upsert

Message Format

{
  "event": "messages.upsert",
  "instance": "my-instance",
  "data": {
    /* event data */
  },
  "date_time": "2023-12-01T10:30:00.000Z",
  "sender": "5511999999999@s.whatsapp.net"
}

3. Amazon SQS

Send events to AWS SQS queues for cloud-based processing.

Configuration

SQS_ENABLED=true
SQS_ACCESS_KEY_ID=your-access-key
SQS_SECRET_ACCESS_KEY=your-secret-key
SQS_ACCOUNT_ID=123456789012
SQS_REGION=us-east-1

Queue Naming

Queues are automatically created with the pattern: {instanceName}-{event}

4. Pusher

Real-time events via Pusher channels for web applications.

Configuration

PUSHER_ENABLED=true
PUSHER_GLOBAL_ENABLED=true
PUSHER_GLOBAL_APP_ID=your-app-id
PUSHER_GLOBAL_KEY=your-key
PUSHER_GLOBAL_SECRET=your-secret
PUSHER_GLOBAL_CLUSTER=us2
PUSHER_GLOBAL_USE_TLS=true

Channel Structure

  • Channel: {instanceName}
  • Event: {event-type}

5. WebSockets

Real-time bidirectional communication via WebSocket connections.

Configuration

WEBSOCKET_ENABLED=true
WEBSOCKET_GLOBAL_EVENTS=true

Connection

const ws = new WebSocket('ws://localhost:8080')

ws.on('message', (data) => {
  const event = JSON.parse(data)
  console.log('Received event:', event)
})

Event Manager Implementation

The EventManager class coordinates all event delivery:

Key Features

  • Multi-Channel Distribution: Events are sent to all configured channels simultaneously
  • Instance-Specific Configuration: Each instance can have different event settings
  • Event Filtering: Configure which events to receive per channel
  • Error Handling: Robust error handling with logging and retry mechanisms

Event Flow

Configuration Examples

Complete Instance Configuration

{
  "instanceName": "production-bot",
  "integration": "WHATSAPP-BAILEYS",
  "webhook": {
    "enabled": true,
    "url": "https://api.mycompany.com/whatsapp/webhook",
    "byEvents": true,
    "base64": false,
    "headers": {
      "Authorization": "Bearer prod-token-123",
      "X-Instance": "production-bot"
    },
    "events": ["MESSAGES_UPSERT", "CONNECTION_UPDATE", "CONTACTS_UPDATE"]
  },
  "rabbitmq": {
    "enabled": true,
    "events": ["MESSAGES_UPSERT", "SEND_MESSAGE"]
  },
  "websocket": {
    "enabled": true,
    "events": ["CONNECTION_UPDATE", "QRCODE_UPDATED"]
  }
}

Global Event Configuration

# Enable global webhooks for all instances
WEBHOOK_GLOBAL_ENABLED=true
WEBHOOK_GLOBAL_URL=https://api.mycompany.com/global-webhook

# Enable specific events globally
WEBHOOK_EVENTS_MESSAGES_UPSERT=true
WEBHOOK_EVENTS_CONNECTION_UPDATE=true
WEBHOOK_EVENTS_INSTANCE_CREATE=true
WEBHOOK_EVENTS_INSTANCE_DELETE=true

# RabbitMQ global configuration
RABBITMQ_GLOBAL_ENABLED=true
RABBITMQ_EVENTS_MESSAGES_UPSERT=true
RABBITMQ_EVENTS_SEND_MESSAGE=true

Best Practices

Webhook Security

  • Use HTTPS endpoints in production
  • Implement webhook signature verification
  • Add authentication headers
  • Validate incoming payloads

Error Handling

  • Implement proper error handling in webhook endpoints
  • Return appropriate HTTP status codes (200 for success)
  • Log webhook failures for debugging
  • Set up monitoring and alerting

Performance

  • Use asynchronous processing for webhook handlers
  • Implement proper database connection pooling
  • Consider using queues for heavy processing
  • Monitor event delivery latency

Scaling

  • Use RabbitMQ or SQS for distributed processing
  • Implement horizontal scaling for webhook handlers
  • Use load balancers for webhook endpoints
  • Monitor queue depths and processing rates

Troubleshooting

Common Issues

  1. Webhook Timeouts: Ensure webhook endpoints respond quickly (< 30 seconds)
  2. Missing Events: Check event configuration and instance status
  3. Duplicate Events: Implement idempotency in event handlers
  4. Connection Issues: Verify network connectivity and credentials

Debugging

Enable webhook logging to debug event delivery:

LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS

Monitoring

Monitor these metrics for healthy event delivery:

  • Event delivery success rates
  • Webhook response times
  • Queue depths (RabbitMQ/SQS)
  • Error rates and types

This comprehensive event system provides the foundation for building reactive WhatsApp applications that respond to real-time events across multiple delivery channels.