Using WebSockets

This page applies to Apigee and Apigee hybrid.

View Apigee Edge documentation.

This topic discusses how to use WebSockets with Apigee and Apigee hybrid.

Introduction

There are many situations where web interactions need to happen in real time, such as gaming, communications, financial transactions, and other high-throughput activities.

WebSocket is a protocol that provides a full-duplex communications channel between a web client and web server over a single TCP connection. The WebSocket protocol uses the HTTP protocol to establish the connection between the client and server. Once established, the client and server then use the WebSocket protocol to send and receive data.

The WebSockets spec and protocol is maintained by the W3C.

Support for WebSockets in Apigee

In Apigee and Apigee hybrid, environment groups provide routing to environments and define the hostnames on which API proxies are exposed. Environment groups support both the HTTP and WS protocols natively. You do not have to create a special environment group or any special configuration to use WebSockets. Rather, it is up to the client to request a protocol upgrade from HTTP to WS by including the Upgrade request header. An upgrade request made to an API proxy endpoint returns a 101 Switching Protocols response. Further requests and responses are made bidirectionally on the open WebSockets connection, until it is closed.

Policy support

All policies will work in a web socket proxy until the handshake is completed (i.e. until the HTTP 101 response is returned to the client), after that no policy will execute, but OAuth tokens validated before the handshake are still honored and the connection dropped if the token expires or is revoked.

Revoking the connection

The WebSockets connection is closed when:

  • The proxy endpoint receives a request without an API key or OAuth token.
  • The proxy endpoint receives a request with an expired or invalid API key or OAuth token.
  • The WebSockets connection times out.

Using trace and analytics

In the Debug tool, for each WebSockets connection you'll see one request appear with a 101 Status, as shown in the following screenshot:

Request with 101 status in the Debug tool.

In the Apigee analytics dashboard, you will see traffic counted for each WebSockets session. Back and forth traffic that occurs during the session is not shown in the dashboard.

Sample WebSockets application

To learn more, you can refer to a working websocket-sample application on GitHub. The sample demonstrates how to call an API proxy over a WebSockets connection. The proxy calls a simple backend target application that is deployed in your Kubernetes cluster.