Skip to content
ADP
API Design PrincipleBETA

WebSocket API Design Guide

WebSocket is a full-duplex communication protocol suitable for real-time applications such as chat, games, and instant notifications. When designing a WebSocket API, considerations MUST be made for message format, connection management, security, and scalability. The following guidelines MUST be followed when designing a WebSocket API:

Message Format

  • All messages transmitted via WebSocket MUST use a unified format, such as JSON.
  • Messages SHOULD include a type field to distinguish between different types of messages.
  • A timestamp SHOULD be included for message ordering and debugging.

Example of JSON message format:

json
{
  "type": "message_type",
  "data": {
    "key1": "value1",
    "key2": "value2"
  },
  "timestamp": "2024-07-29T12:34:56Z"
}

Connection Management

  • Handshake: The client MUST establish a connection using the standard WebSocket handshake. The server MUST respond with appropriate headers.
  • Keep-Alive: The server SHOULD implement a keep-alive mechanism using ping/pong frames to detect and close idle or dead connections.
  • Reconnection: The client MUST implement a robust reconnection strategy to gracefully handle disconnections.
  • Graceful Shutdown: The server MUST be able to gracefully shut down, properly closing all active WebSocket connections.

Security

  • Authentication: The client MUST authenticate before establishing a WebSocket connection. This SHOULD be done using a token (e.g., JWT) sent during the handshake.
  • Encryption: Secure WebSocket (wss://) MUST be used to encrypt data transmitted between the client and server.
  • Authorization: The server MUST implement authorization checks to ensure that clients can only perform actions they are allowed to.

DRAFT Error Handling

  • Standard Error Messages: The server MUST define a set of standard error messages and codes to send to the client in case of errors.
  • Error Logging: The server SHOULD log errors for debugging and monitoring purposes.

Example of error message format:

json
{
  "type": "error",
  "error": {
    "type": "/problems/unauthorized",
    "message": "Unauthorized access"
  },
  "timestamp": "2024-07-29T12:34:56Z"
}

Rate Limiting

The WebSocket API can primarily limit the number of sockets in a connection. When the limit is reached, the following response SHOULD be returned via WebSocket:

json
{
  "type": "error",
  "error": {
    "type": "/problems/reach-maximum-connections",
    "message": "Maximum number of connections reached"
  },
  "timestamp": "2024-07-29T12:34:56Z"
}

Version Control

Please refer to API Versioning. For WebSocket APIs, URL versioning is primarily used.

Documentation

  • Provide comprehensive documentation for your WebSocket API.

OAS 3.1 Example

OpenAPI Specification (OAS) 3.1 supports documenting WebSocket APIs. Below is an example of documenting a WebSocket API using OAS 3.1:

yaml
openapi: 3.1.0
info:
  title: Chat WebSocket API
  version: 1.0.0
  description: WebSocket API for real-time chat applications
servers:
  - url: wss://chat.example.com/ws
paths:
  /chat:
    post:
      summary: Establish WebSocket connection
      responses:
        '101':
          description: Switching Protocols
components:
  schemas:
    Message:
      type: object
      properties:
        type:
          type: string
          description: Type of the message
        data:
          type: object
          additionalProperties: true
          description: Payload of the message
        timestamp:
          type: string
          format: date-time
          description: Timestamp of when the message was sent
    ErrorMessage:
      type: object
      properties:
        type:
          type: string
          const: error
          description: Indicates this is an error message
        error:
          type: object
          properties:
            code:
              type: integer
              description: Error code
            message:
              type: string
              description: Error message
        timestamp:
          type: string
          format: date-time
          description: Timestamp of when the error occurred

This example defines a WebSocket server located at wss://chat.example.com/ws with a /chat path. It includes schemas for standard messages and error messages, ensuring consistency in the message format across the entire WebSocket API.

References