WebSockets passthrough
WebSockets are two-way communication channels between a client device (such as a web browser) and a server, allowing the server to send messages to the client at any time without the client having to make a request.
Unlike the HTTP requests that make up the bulk of web traffic handled by Fastly, WebSockets are long-lived connections and do not have a request-response cycle. They instead can carry data in either direction at any time. As a result, WebSockets don't fit Fastly's normal processing model for edge traffic, but because WebSocket connections begin life as HTTP requests, you can pass them directly to the origin server.
HINT: WebSockets passthrough creates one WebSocket connection to origin for every connection from a client device to Fastly. To have Fastly broker messages for you with channels and one-to-many publishing, consider using Fanout instead.
Enabling WebSockets passthrough
WebSockets passthrough is an optional upgrade to Fastly service plans. To use WebSockets passthrough, you need a paid Fastly account. If you have not yet purchased access, contact Customer Support to start a free trial.
Once your Fastly account has full access to WebSockets, it can be enabled on an individual service in the Fastly control panel or by enabling the WebSockets product using the Products API for WebSockets.
WARNING: Enabling or disabling WebSockets immediately impacts all service versions, including the active one.
- VCL
- Compute
In a VCL service, your VCL is invoked for each inbound client request and the VCL workflow is designed to manage a conventional request-response cycle. To handle the WebSocket connection, you must hand off the request from VCL so that Fastly can continue to hold the connection and relay traffic in both directions. To do this, return(upgrade)
from vcl_recv
:
if (req.http.Upgrade) { return (upgrade);}
Tips
The following tips and best practices may help you get the most out of WebSockets passthrough:
- If you use the web interface or API to create the backend, be sure to set a host header override if your server's hosting is name-based. Learn more.
- Unlike most Rust-based Compute programs, you cannot use the
#[fastly::main]
macro in a program that doeshandoff_websocket
. This is becausehandoff_websocket
will immediately start a response to the client, making it impossible to return aResponse
from themain()
function without causing an error. - Client request headers that are added, removed, or modified on your
Request
(orreq.http
in VCL) will be reflected in the WebSocket handoff. - Once handed off, WebSocket connections are not subject to the
between_bytes_timeout
and will only drop when either the client or server disconnects. If either the client or server disconnects, Fastly will relay that disconnect to the other party.