Understand TzKT WebSocket message types
masterOnce a client connects and subscribes via the WebSocket, the server sends three distinct types of messages. Understanding these is critical for maintaining data consistency and handling chain reorganizations.
1. State Message (type: 0)
This is the first message received after opening a subscription. It serves as a confirmation that the subscription was successful. The state field indicates the current progress of the subscription.
- Usage: Use the
statevalue to fetch historical data from the REST API to bridge the gap between your last known state and the real-time stream, ensuring no data is missed or duplicated. - Example: If subscribing to blocks and you receive
state: 1300123, the next expected block is1300124.
2. Data Message (type: 1)
Sent after the state message. The data field contains the actual blockchain information (blocks, operations, etc.).
- Format:
datacan be an object or an array. Receiving multiple items in a single message is common for performance optimization. - Consistency: The data models used in WebSocket messages are identical to those used in the TzKT REST API.
3. Reorg Message (type: 2)
Signals a chain reorganization where blocks and operations are rolled back in favor of a different chain branch.
- Criticality: You must handle these messages to avoid accumulating duplicate or invalid data.
- Handling Logic: If you have saved blocks
10, 11, 12, 13and receive a reorg message withstate: 11, you must remove blocks12and13from your local storage as they are no longer valid.
// State message example
{
type: 0,
state: 0
}
// Data message example
{
type: 1,
state: 0,
data: {}
}
// Reorg message example
{
type: 2,
state: 0
}