What is WebTransport and can it replace WebSockets?
Tags: webdev, javascript, discuss
Published: 2023-11-27 11:03:18

[WebTransport](https://www.w3.org/TR/webtransport/) is a new specification that could offer an [alternative to WebSockets](https://ably.com/topic/websocket-alternatives).

For applications that need low latency, event-driven communication between endpoints, WebSockets has been the go-to choice, but WebTransport may change that.

In this article, you’ll learn what WebTransport offers and how it differs from WebSockets. You’ll also learn when—and if—you should make the switch.

## WebSockets vs WebTransport, at a glance

[WebSockets](https://hubs.la/Q029qgRb0) is a technology that enables bidirectional, full-duplex communication between client and server over a persistent, single-socket connection. This allows for low-latency, realtime updates, and the creation of richer communication and gaming applications. Previously, the web was dependent on [requests and responses](https://hubs.la/Q029qh830), which aren’t dynamic enough for those kinds of apps.

The newer WebTransport offers secure, multiplexed, realtime transport and already has APIs for sending data both reliably and unreliably.

In a reliable data transfer, the sender is notified of the success or failure of the data transmission, and failed transmissions are usually resent until they succeed, after which the next data packet is sent. In unreliable transfer, there’s no confirmation of transmission success, and packets that aren’t received simply don’t get delivered. Unreliable transfer is often used for things like streaming videos, where speed is a concern, and minor data loss, such as a few frames of video, is acceptable. Because WebTransport uses both of these methods, there are many use cases for it, such as bidirectional data streaming for multiplayer gaming, interactive live streams, and data transfer for sensors and internet of things devices.

![WebTransport sends multiple streams within a single connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ujoaedrno1hdr2et8ap.png)

While WebSockets creates a single stream per connection, WebTransport allows you to create multiple streams over a single connection. It avoids the head-of-line blocking delays that WebSockets suffers from, and is less resource intensive when creating connections. While WebSockets starts as a HTTP/1.1 protocol, WebTransport works on top of several different protocols, including some that WebSockets don't support.

It works with [HTTP/3](https://hubs.la/Q029qhCl0), the upcoming version of the transport protocol used by the World Wide Web. HTTP/3 uses the [QUIC protocol](https://www.chromium.org/quic/) for transport layer data exchange, which has several advantages. QUIC can prevent [head-of-line blocking delays](https://en.wikipedia.org/wiki/Head-of-line_blocking), improving network performance in many situations. This is a limitation of WebSockets.

With WebTransport, you can also use features like [promises](https://en.wikipedia.org/wiki/Promise_theory) and the [await keyword for asynchronous functions](https://hubs.la/Q029qjs90). The API runs in Web Workers, too, enabling multithreading.

Here’s an example of an async function from the [WebTransport Working Group’s documentation](https://www.w3.org/TR/webtransport/#example-sending-stream).

```javascript
async function sendData(url, data) {
    const wt = new WebTransport(url);
    const writable = await wt.createUnidirectionalStream();
    const writer = writable.getWriter();
    await writer.write(data);
    await writer.close();
}
```
The WebTransport working group is still hammering out the details of the specification, so more features and capabilities may come.

## 4 WebTransport use cases

There are many potential use cases for WebTransport. Let’s look at four where it shines.

### 1. Encrypted streaming

WebTransport’s streams API allows you to create connections for sending ordered data. As WebTransport uses the QUIC protocol, these connections are [less resource intensive to open and close](https://web.dev/webtransport/) than with TCP used by WebSockets.

You can also do things like offer streaming media more securely. WebTransport has several [security measures](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/#page-10) in place, such as requiring use of the Origin header as well as specific opt-in via a transport parameter.

### 2. Communication

WebTransport can send [multiple types of data](https://blog.bitsrc.io/will-webtransport-replace-webrtc-in-near-future-436c4f7f3484) over the same connection. That means you can send and receive video information unreliably while sending text or file data reliably.

This feature allows you to do more with each connection, leading to richer communication between a greater number of simultaneous users. It means that you can send different types of content on different channels, so something like a large image could be sent over a different connection than other data, which would mean that the image can’t [block chat communication](https://www.youtube.com/watch?v=jvdg-jOYK5E).

You can also create bidirectional streams that allow either the server or client to initiate communication, so if you’re implementing a messaging system, data exchange can happen quickly.

### 3. Multiplayer gameplay

WebTransport works with the [HTTP/2](https://hubs.la/Q029qjLF0), HTTP/3, and QUIC protocols. It can receive data out of order over HTTP and can request data itself or listen to data that is pushed by the server. It can do this both reliably and unreliably.

With WebTransport’s bidirectional streams, data pushed by the server has very low latency, which is a big advantage for game development. It means less delay between user input and the response, which can be critical in action games, such as shooting, driving, or fighting.

It can also improve response times for cloud gaming services, where the server handles rendering and gameplay and streams video to a thin client, which passes back user input to the server.

### 4. Sensor data

Many [Internet of Things (IOT)](https://www.oracle.com/internet-of-things/what-is-iot/) devices log data that needs to be transferred to a server, and a potential use of WebTransport is having a low-latency method for transferring this. IOT devices often send small amounts of data regularly. Consuming fewer resources has advantages for both the battery life of the devices and with regard to network congestion.

As the IOT grows, the large number of devices in use consuming an ever-increasing number of connections could become a problem, so the more lightweight those devices are, the better.

## Can you use WebTransport?

Now let’s look at what specific features and capabilities WebTransport offers. The specification is still at the public draft stage but is fully usable.

In addition to the QUIC protocol, there’s an API that lets browsers control streams and datagrams. The API is HTTPS only, enforcing security.

### QUIC

QUIC is a transport protocol designed to replace TCP and improve web performance. It uses UDP, and HTTP/3 is designed to take advantage of it. When using HTTP/3 over QUIC, it’s faster to establish connections, and congestion control feedback is available to help avoid problems. As mentioned previously, QUIC also prevents head-of-line blocking.

It doesn’t require as much header information, which allows lightweight communication—without the overhead of HTTP. It’s also hardware independent, with support required only at the [application level](https://www.ionos.com/digitalguide/hosting/technical-matters/quic-the-internet-transport-protocol-based-on-udp/).

QUIC is already widely supported in browsers and applications. Currently [7.7% of websites](https://w3techs.com/technologies/details/ce-quic) use it, but the figure is increasing steadily.

If you want to experiment with QUIC in Chrome and many other Chromium-based browsers, you can [activate it in the settings](https://ma.ttias.be/enable-quic-protocol-google-chrome/).

Type `chrome://flags` in the URL bar, then find the **Experimental QUIC protocol** setting and enable it, as in the screenshot below. (For Chromium-based browsers, simply replace `chrome://flags` with `[browser name]://flags`.)

![Chrome settings showing QUIC being enabled](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rdmv6fjeapdp6768gy1.png)

### Other protocols

WebTransport can also run on top of either HTTP/2 or HTTP/3 without QUIC. It can also use HTTP/2 as a fallback, allowing you to take advantage of the benefits of WebTransport, regardless of the network.

HTTP/2 compatibility could potentially let you run it on older setups that don’t support HTTP/3 and lets you take advantage of features like resource prioritization.

### Datagrams

WebTransport works primarily with datagrams and streams. A datagram is a self-contained packet of data that can arrive in any particular order. Datagrams are sent unreliably. Unreliable data can be sent at high speed, and the connection can cope if some data is dropped. The WebTransport specification allows you to limit the datagram size using the `maxDatagramSize` attribute.

WebTransport objects have a datagrams object that can be accessed via its readable and writable attributes. Datagrams can be queued, and you can also create promises to wait for datagram transmission.

The WebTransport objects also include state data, indicating whether they are connecting, connected, closed, or failed. They also include promises indicating if the object is ready or closed.

### Streams
Streams allow you to send ordered, reliable data. You can establish a stream and have the server push this content to the client. It allows low-latency, real-time communication.

In the API, WebTransport objects have slots for further objects representing different types of stream. These include SendStream, ReceiveStream, and Bidirectional Stream objects, all defined in the [working draft](https://www.w3.org/TR/webtransport) of the specification.

WebTransport also allows multistream data to be sent in a partially reliable manner. Sent like this, data is not guaranteed to arrive in the right order overall but is ordered by the status of other related streams. This works well when sending video frames.

With streams, you can also pipe received data into a handler, such as a TextDecoderStream that converts it into a format readily usable by your application.

#### SendStream

SendStream objects are a kind of [WritableStream](https://streams.spec.whatwg.org/#writablestream) used for outgoing data. They store stream objects, but a SendStream object also contains a promise, which defines an action it will take, such as being closed or aborted.

SendStream objects also include a slot to attach them to the HTTP/3 transport layer.

#### ReceiveStream

ReceiveStream objects are a kind of [ReadableStream](https://streams.spec.whatwg.org/#readablestream) that handles incoming data.

The ReceiveStream object is structured similarly to the SendStream objects, with a stream slot and transport slot. It doesn’t, however, include promises.

#### Bidirectional stream

The bidirectional stream combines the send and receive streams into a single object, which allows you to manage two-way communication in one place. Objects have a readable and writable property, corresponding to the ReceiveStream and SendStream objects discussed above.

These properties let them work with data sent in either direction. You read the incoming stream and write to the outgoing stream.

#### Unidirectional streams

You can also create unidirectional streams. IncomingUnidirectionalStreams are ReadableStreams consisting of multiple ReceiveStreams. You can call `createUnidirectionalStream()` to create an outgoing equivalent.

## Could WebTransport replace WebSockets?

The WebTransport specification is still in flux, but its future looks bright. As it continues to take shape, we’re sure to see more developers adopt it and utilize the new features it brings.

Early adopters stand to reap big rewards but also take the biggest risks as it isn’t clear how fully the specification will deliver on its promises. We don’t know how well browsers will support it, how likely developers are to adopt it, or how it will evolve.

WebTransport has advantages in some use cases, such as low-latency scenarios and reusing connections for multiple purposes. It isn’t a silver bullet, though, and there are scenarios where WebSockets will still be the best choice—or at least a perfectly good one.

As a new specification, WebTransport is still nascent, so it will be harder to get working until other tools are updated to work with it. For now, that means keeping eyes and minds open and being ready to adapt.

WebSockets still offer a great deal of functionality, and as an established standard, are fully supported by all modern browsers. WebTransport should offer modest performance improvements and incremental gains, but will also likely create new engineering challenges that will have to be addressed to build production-ready systems.

## Does Ably support WebTransport?

At [Ably](https://hubs.la/Q029qkfD0) where we offer a realtime communication API used by developers to build experiences like [chat](https://hubs.la/Q029qkpx0), [multiplayer collaboration](https://hubs.la/Q029qkGG0), and other live updates in your web and mobile applications at scale. Under the hood, we build on lower-level communication protocols to enable features like online presence, message history, queues, and more. Most developers use Ably with WebSocket transport, but we also support HTTP, SSE, and MQTT. Our community sometimes wonders - [is Ably currently exploring WebTransport](https://hubs.la/Q029qkHP0)? And the answer is yes, but  until the future of WebTransport is more certain, we’re focused on WebSockets.

If you are looking to implement reliable realtime messaging in your application, I encourage you to [give Ably a try](https://hubs.la/Q029qk-M0)!

## Conclusion

[WebTransport](https://www.w3.org/TR/webtransport/) is already a viable [alternative to WebSockets](https://hubs.la/Q029qlvN0), with several advantages. The lack of head of line blocking, slightly lower latency, and versatility of the multi-protocol approach offer benefits in many scenarios.

As the technology is not fully defined yet, the tooling is less developed, and will be for a while. On the other hand, the API is usable, and the opportunity is there to be the quickest to market with products that benefit from its strengths.

It’s too early to predict [what WebTransport will be used for](https://github.com/quicwg/datagram/issues/68), but the first teams to use it have every chance to build something groundbreaking.

Though there’s no urgent need to switch, developers should keep an eye on it for future projects and be ready to use it if it’s the best fit.