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

# Messages

Messages represent the data payloads sent and received on Ably channels. Each message contains the message data, metadata, and optional event name.

## Message Properties

<ParamField path="name" type="string">
  Optional event name for the message. Used to filter subscriptions.
</ParamField>

<ParamField path="data" type="any">
  The message payload. Supported types:

  * String
  * JSON object or array
  * Binary data (Buffer, ArrayBuffer, Uint8Array)
  * null
</ParamField>

<ParamField path="id" type="string">
  Unique message ID assigned by Ably.
</ParamField>

<ParamField path="timestamp" type="integer">
  Timestamp when message was received by Ably (milliseconds since epoch).
</ParamField>

<ParamField path="clientId" type="string">
  Client ID of the publisher.
</ParamField>

<ParamField path="connectionId" type="string">
  Connection ID of the publisher.
</ParamField>

<ParamField path="encoding" type="string">
  Encoding information for the message data (for example, `json`, `utf-8`, `base64`).
</ParamField>

<ParamField path="extras" type="object">
  Optional metadata and ancillary payloads:

  * `headers` - Custom string-to-string headers
  * `push` - Push notification payload
  * `ephemeral` - Mark message as ephemeral
  * `privileged` - Privileged message markers
</ParamField>

## Message Structure

Example message object:

<Code>
  ```json theme={null}
  {
    "id": "abc123:0",
    "name": "update",
    "data": {
      "temperature": 21.5,
      "humidity": 65
    },
    "timestamp": 1640000000000,
    "clientId": "client-123",
    "connectionId": "conn-456",
    "encoding": "json"
  }
  ```
</Code>

## Publishing Messages

Publish messages using the channel's `publish` method:

<Code>
  ```javascript theme={null}
  // Publish simple message
  await channel.publish('event-name', 'message data');

  // Publish with complex data
  await channel.publish('sensor-update', {
    temperature: 21.5,
    humidity: 65,
    timestamp: Date.now()
  });

  // Publish with extras
  await channel.publish({
    name: 'notification',
    data: 'New message',
    extras: {
      headers: {
        'priority': 'high'
      }
    }
  });
  ```

  ```python theme={null}
  # Publish simple message
  await channel.publish('event-name', 'message data')

  # Publish with complex data
  await channel.publish('sensor-update', {
      'temperature': 21.5,
      'humidity': 65,
      'timestamp': time.time()
  })
  ```
</Code>

## Receiving Messages

Receive messages by subscribing to channels:

<Code>
  ```javascript theme={null}
  // Subscribe to all messages
  await channel.subscribe((message) => {
    console.log('Received:', message.name, message.data);
    console.log('From:', message.clientId);
    console.log('At:', new Date(message.timestamp));
  });

  // Subscribe to specific event
  await channel.subscribe('sensor-update', (message) => {
    const { temperature, humidity } = message.data;
    console.log(`Temp: ${temperature}°C, Humidity: ${humidity}%`);
  });
  ```

  ```python theme={null}
  async def on_message(message):
      print('Received:', message.name, message.data)
      print('From:', message.client_id)
      print('At:', datetime.fromtimestamp(message.timestamp / 1000))

  await channel.subscribe(on_message)
  ```
</Code>

## Message Extras

### Custom Headers

Add custom metadata to messages:

<Code>
  ```javascript theme={null}
  await channel.publish({
    name: 'order',
    data: orderData,
    extras: {
      headers: {
        'order-id': '12345',
        'priority': 'high',
        'region': 'us-east'
      }
    }
  });
  ```
</Code>

### Push Notifications

Include push notification payload:

<Code>
  ```javascript theme={null}
  await channel.publish({
    name: 'notification',
    data: 'You have a new message',
    extras: {
      push: {
        notification: {
          title: 'New Message',
          body: 'You have a new message from Alice'
        },
        data: {
          messageId: '12345'
        }
      }
    }
  });
  ```
</Code>

### Ephemeral Messages

Mark messages as ephemeral (not persisted):

<Code>
  ```javascript theme={null}
  await channel.publish({
    name: 'typing',
    data: { isTyping: true },
    extras: {
      ephemeral: true
    }
  });
  ```
</Code>

## Message Encoding

Ably automatically encodes and decodes message payloads:

* **JSON**: Objects and arrays are JSON-encoded
* **Binary**: Binary data is base64-encoded for transport
* **UTF-8**: Strings are UTF-8 encoded

The `encoding` property indicates the encoding applied.

## Batch Publishing

Publish multiple messages atomically:

<Code>
  ```javascript theme={null}
  // All messages succeed or fail together
  await channel.publish([
    { name: 'event1', data: 'data1' },
    { name: 'event2', data: 'data2' },
    { name: 'event3', data: 'data3' }
  ]);
  ```

  ```python theme={null}
  await channel.publish([
      {'name': 'event1', 'data': 'data1'},
      {'name': 'event2', 'data': 'data2'},
      {'name': 'event3', 'data': 'data3'}
  ])
  ```
</Code>

Batch benefits:

* Atomic delivery (all or nothing)
* Single rate limit operation
* Combined size limit check
* Better performance

## Message Size Limits

Default message size limit: 64 KB

Custom limits available for enterprise accounts. Configure in SDK:

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime({
    key: 'your-api-key',
    maxMessageSize: 131072 // 128 KB
  });
  ```
</Code>

## Message History

Retrieve message history:

<Code>
  ```javascript theme={null}
  const result = await channel.history({
    limit: 50,
    direction: 'backwards'
  });

  for (const message of result.items) {
    console.log(message.name, message.data);
  }
  ```
</Code>

See [Channels API](/docs/api/realtime-sdk/channels#history) for full history options.

## Related Resources

* [Channels API](/docs/api/realtime-sdk/channels)
* [Publishing Messages](/docs/messages)
* [Message History](/docs/storage-history/history)
* [Message Encryption](/docs/channels/options#encryption)
