DEV Community

Cover image for API Gateway as Websocket
Amit Kayal
Amit Kayal

Posted on

2

API Gateway as Websocket

API Gateway as websocket

API Gateway as WS Components

Websocket provides bidirectional session aware communication between caller and receiver and a crucial component for realtime application.

  • Setup API Gateway for WebSocket

    • Create a WebSocket API in the Amazon API Gateway console or through IAC.
    • Define the WebSocket API route selection expression. Routes here are simply like a bridge to connections e.g.,
      • $request.body.action.
      • Define the following WebSocket routes:
      • $connect: Triggered when a client establishes a connection.
      • $disconnect: Triggered when a client disconnects.
      • Custom routes, e.g., sendMessage, to handle specific actions.
  • Create an Integration with AWS Lambda

    • For each route ($connect, $disconnect, custom routes), integrate a Lambda function to handle the respective logic.
    • Use the Lambda function's handler to process:
      • $connect: Store the connection in DynamoDB.
      • $disconnect: Remove the connection from DynamoDB.
      • Custom routes: Process the message and forward it to SQS.
  • DynamoDB for Connection Management

    • Create a DynamoDB table to store:
      • Connection ID (Primary Key).
      • Session ID or other metadata for grouping connections.
    • This table allows tracking active WebSocket connections for broadcasting messages.
  • Configure SQS for Message Queue

    • Use an SQS FIFO queue for guaranteed order and deduplication.
    • Messages processed in Lambda (custom routes) are sent to SQS for downstream services.
  • IAM Roles and Permissions

    • Assign an IAM role to the API Gateway to invoke the integrated Lambda functions.
    • Grant Lambda permissions to read/write from DynamoDB and send messages to SQS.
  • Client Connection and Messaging

    • Use WebSocket-compatible libraries (e.g., ws in Node.js or WebSocket API in browsers) to:
    • Establish a WebSocket connection to the API Gateway endpoint.
    • Send and receive messages using the WebSocket protocol.

Architecture of Websocket mechanism

  • WebSocket Client:
    • Initiates WebSocket connection and communicates via send() and onmessage().
  • API Gateway (WebSocket API):

    • Manages WebSocket connections and invokes Lambda functions for defined routes.
  • Route Integration (Lambda Functions):
    Every route should have an integration. There are 3 types — Mock, HTTP and Lambda.

    • $connect: Adds connection metadata to DynamoDB.
    • $disconnect: Removes connection metadata from DynamoDB.
    • $default route: selected when route cant be evaluated against message
    • Custom Routes: Processes messages to invoke integration based on message content and forwards them to SQS.
  • DynamoDB:

    • Maintains active connection records, including connectionId and associated metadata.
  • SQS FIFO Queue:

    • Queues messages for downstream processing, ensuring delivery order and deduplication.
  • Downstream Services:

    • Processes messages from SQS and performs actions like notifications, data updates, or storage.

Security

Authentication and Authorization

  • Custom Authorizer (Lambda Authorizer)
    It can only be used for the $connect route.

    • Create a Lambda Authorizer to validate custom tokens or headers sent during connection attempts.
    • Example:
      • Validate a JWT token from an identity provider (e.g., Cognito, Auth0).
      • Check the token against allowed users or roles.
  • Amazon Cognito:

    • Use Amazon Cognito for user authentication.
    • Configure API Gateway to use Cognito to validate tokens in connection requests.
    • Best suited for applications with user pools.

Secure WebSocket Connections

  • Always use the secure WebSocket protocol (wss://). API Gateway enforces HTTPS/TLS, ensuring encrypted communication.
  • Associate a custom domain with API Gateway WebSocket endpoint. We should AWS Certificate Manager (ACM) to manage SSL/TLS certificates.

IP Whitelisting and Blacklisting

  • IP Whitelisting and Blacklisting: We should Attach AWS WAF to API Gateway and Block/allow requests based on IP addresses or CIDR ranges. we should also use rate limit to protect from DDoS attack ### API Gateway Throttling
  • We can Set rate and burst limits on API Gateway routes to limit the number of connections per client.
  • We can create API keys and associate them with usage plan and then we Limit the number of allowed requests per API key

Environment-based Access Control:

  • We should always use distinct stages (e.g., dev, prod) and restrict connections to the production API through IP rules.

Tools to test

There are following tools which we can explore to test websocket.

  • Piesocket
  • Postman

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay