Subscriptions and streaming
Strawberry turns a GraphQL subscription into an asynchronous result source and lets an integration deliver each result through WebSocket or HTTP streaming. The same transport-facing path also carries single-result queries and mutations and can carry experimental incremental @defer and @stream frames. See GraphQL execution, operation execution, and data loading and batching for the surrounding execution model.
Subscription model
Subscriptions represent long-lived GraphQL operations. A client starts one operation, Strawberry waits for values from its source, and the selected fields are resolved for each value before the transport sends the result.
Subscription fields
A subscription field is declared with @strawberry.subscription on the schema's subscription type. Its source normally returns an async iterator or async generator. Each yielded value must match the GraphQL type selected by the subscription, so normal GraphQL field selection and result errors still apply to every event. The schema receives the subscription type when it is created, in the same way that it receives query and mutation types.
References: strawberry/…/mutation.py• L293-342 strawberry/…/schema.py• L263-316 tests/…/test_subscription.py• L19-39
Subscription result sources
Schema.subscribe is the subscription-only entry point. It returns an asynchronous result source that yields execution results until the source ends or the caller closes it. Schema.stream is the wider entry point used by streaming transports. It dispatches by operation type, so a subscription yields many results while a query or mutation yields one result and completes.
The source can yield a first PreExecutionError when parsing, validation, operation selection, or another pre-execution step fails. Transport handlers use that distinction to send an operation-level error instead of treating the error as a normal subscription event.
References: strawberry/…/schema.py• L906-1030 strawberry/…/schema.py• L1090-1171 strawberry/…/execution.py• L108-131
Subscription cancellation
Cancellation is part of the subscription contract. A client can stop one operation or close its connection. Strawberry closes the asynchronous result source, cancels the operation task, and sends the protocol's completion signal when the transport can still send one. Finished and stopped operations release their connection bookkeeping, so an operation ID can be reused and an active-operation limit does not remain occupied. Subscription code can use cancellation handling to stop event listeners and release resources.
References: strawberry/…/handlers.py• L169-243 strawberry/…/handlers.py• L335-362 docs/…/subscriptions.md• L482-529
Streaming transports
The selected transport owns the wire format and the connection behavior. The execution layer supplies a sequence of results; the transport turns that sequence into WebSocket messages, SSE events, or multipart parts.
Transport selection
Strawberry supports two WebSocket protocols by default and keeps HTTP streaming protocols opt-in. An integration's subscription_protocols setting controls which protocols are available. HTTP clients select an enabled HTTP stream with the Accept header, while WebSocket clients select a WebSocket subprotocol during the handshake.
| Transport | Main use | Selection and scope |
|---|---|---|
graphql-transport-ws | Current WebSocket protocol | Negotiated as a WebSocket subprotocol. Supports subscriptions and single-result queries or mutations. |
graphql-ws | Legacy WebSocket protocol | Negotiated as a WebSocket subprotocol for backward compatibility. Its operation flow is centered on subscriptions. |
graphql-sse | Server-Sent Events over HTTP | Enabled with GRAPHQL_SSE_PROTOCOL and selected with Accept: text/event-stream. Each operation uses its own SSE response. |
multipart-subscription | Multipart HTTP subscriptions | Enabled with MULTIPART_SUBSCRIPTION_PROTOCOL and selected with the multipart subscription media type. It accepts subscription operations only. |
The protocol names are defined in strawberry/…/__init__.py. WebSocket negotiation advertises only the two WebSocket names, even when SSE is also enabled.
References: strawberry/…/__init__.py• L1-11 strawberry/…/base.py• L33-41 strawberry/…/base.py• L89-131 strawberry/…/async_base_view.py• L97-118 strawberry/…/async_base_view.py• L173-185
WebSocket lifecycle
Both WebSocket protocols establish a connection before they start an operation. The legacy protocol uses start, data, and stop; the newer protocol uses subscribe, next, and complete. The handler keeps each operation separate so one connection can carry more than one active operation.
The legacy handler replaces an existing operation when a new start message reuses its ID. It also rejects a new operation when the configured active-operation limit has been reached. These rules keep task and source bookkeeping bounded per connection.
The lifecycle below shows the shared intent. Message names in parentheses identify the protocol-specific form.
sequenceDiagram
participant Client
participant WebSocket as WebSocket handler
participant Schema
Client->>WebSocket: WebSocket handshake
Client->>WebSocket: connection_init
WebSocket->>WebSocket: Build connection context
WebSocket-->>Client: connection_ack
Client->>WebSocket: subscribe (or start)
WebSocket->>Schema: Start stream
loop Until source ends
Schema-->>WebSocket: Execution result
WebSocket-->>Client: next (or data)
end
WebSocket-->>Client: complete
Client->>WebSocket: complete (or stop)
WebSocket->>Schema: Cancel and close source
The connection initialization payload is placed in context as connection_params. The on_ws_connect hook can accept or reject the connection and can return an acknowledgement payload. The newer protocol also requires initialization within its wait period and supports ping and pong messages. Keep-alive messages are available in the legacy protocol.
References: strawberry/…/async_base_view.py• L326-363 strawberry/…/handlers.py• L74-215 strawberry/…/handlers.py• L61-177 strawberry/…/types.py• L6-87 strawberry/…/types.py• L6-81
WebSocket result delivery
The newer protocol sends each normal result in a next message and sends complete after the result source ends. The legacy protocol sends the same result shape in a data message. Errors that occur before execution are sent as operation errors; errors that belong to a particular event remain with that event's payload.
The newer protocol also allows queries and mutations on the same connection. These operations produce one next message and then complete. Its configured operation limit applies to all in-flight operations on that connection, not only subscription operations. The legacy protocol reports a reached operation limit as an operation error and sends complete when a running operation ends or is cancelled.
References: strawberry/…/handlers.py• L251-329 strawberry/…/handlers.py• L393-425 strawberry/…/handlers.py• L135-239 strawberry/…/handlers.py• L245-262 strawberry/…/types.py• L49-75 strawberry/…/types.py• L42-64
HTTP event delivery
SSE and multipart subscriptions use a normal asynchronous HTTP request. The view selects an enabled transport from the request headers, starts Schema.stream, and sends one encoded item for each execution result. Both transports send a completion marker after the source ends and add heartbeat output while an otherwise idle source remains open.
SSE sends next and complete events. It does not send event IDs or replay old results after reconnect. Multipart subscriptions send each result as a JSON part inside the subscription multipart format. HTTP batching is not supported for multipart subscriptions.
References: strawberry/…/async_base_view.py• L187-237 strawberry/…/async_base_view.py• L398-501 strawberry/…/streaming.py• L109-191 strawberry/…/streaming.py• L211-282 tests/…/test_multipart_subscription.py• L67-104
Streamable values
Streamable values support incremental delivery inside a single GraphQL response. They are different from subscription events: a subscription starts a long-lived operation that can produce many complete execution results, while @stream sends parts of one list field as those items become available.
Streamable fields
strawberry.Streamable[T] marks an async generator that supplies values of type T for a list field. A client uses the GraphQL @stream directive to request incremental list delivery. Strawberry's type system recognizes the marker and preserves the element type for schema generation.
References: strawberry/streamable.py• L5-33 strawberry/annotation.py• L397-403 docs/…/defer-and-stream.md• L146-199
Incremental result frames
When experimental incremental execution is enabled, Schema.stream presents incremental execution as a flat sequence. The first frame contains the initial response and pending work. Later frames contain list items or deferred data, followed by a final frame that reports completion.
The HTTP view adds transport fields such as hasNext, pending, incremental, and completed before encoding the frames. The graphql-transport-ws protocol has no wire shape for these raw incremental frames, so Strawberry rejects incremental delivery on that WebSocket protocol instead of sending an incomplete payload.
References: strawberry/…/config.py• L20-49 strawberry/…/schema.py• L1032-1088 strawberry/…/async_base_view.py• L408-430 strawberry/…/async_base_view.py• L503-563 strawberry/…/handlers.py• L283-328
Transport-facing lifecycle
The transport lifecycle connects request parsing, asynchronous execution, wire encoding, heartbeats, and cleanup. This separation lets the schema produce GraphQL results without knowing whether a client uses WebSocket, SSE, or multipart HTTP.
Result stream pipeline
The pipeline below shows how one operation becomes a sequence of transport events. A subscription may produce many normal results; a query or mutation may produce one; incremental execution may add later frames.
flowchart LR
Request[GraphQL request] --> Select[Select enabled transport]
Select --> Execute[Start schema stream]
Execute --> Results[Async result source]
Results --> Process[Process GraphQL result]
Process --> Encode[Encode next event or part]
Encode --> Client[Deliver to client]
Results -->|source ends| Complete[Encode complete]
Complete --> Client
Heartbeat[Heartbeat timer] --> Client
Client -->|stop, complete, or disconnect| Cancel[Cancel and close source]
The HTTP stream uses a size-one coordination queue for result and heartbeat output. This keeps backpressure between the producer and client and prevents heartbeat messages from accumulating while result data is active. WebSocket shutdown performs the same resource role by cancelling operation tasks and closing their sources. The legacy WebSocket handler also removes finished operation state, which lets the connection accept a replacement operation without counting the completed task.
References: strawberry/…/async_base_view.py• L461-501 strawberry/…/streaming.py• L211-282 strawberry/…/handlers.py• L92-105 strawberry/…/handlers.py• L179-243
Context and authorization
The integration creates the request or connection context before execution. HTTP streams use the normal HTTP context path, so cookies and request headers are available to the resolver. WebSocket streams can receive connection-wide data in connection_init and let on_ws_connect make the connection decision before any operation starts.
References: strawberry/…/async_base_view.py• L333-337 strawberry/…/async_base_view.py• L636-641 strawberry/…/handlers.py• L164-205 strawberry/…/handlers.py• L95-124 docs/…/subscriptions.md• L285-341
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the protocol constants, integration protocol settings, and transport lookup rules aligned. Adding an HTTP protocol without adding header or content-type selection leaves the protocol unreachable.
- Keep WebSocket message types and handler state transitions aligned for both supported subprotocols. A message rename affects client negotiation and operation completion.
- Preserve the distinction between a pre-execution error, an event result, and an incremental frame. Each has a different wire representation.
- If the shape of incremental execution changes, update both frame processing in
AsyncBaseHTTPViewand the transport that encodes those frames. - If operation limits or operation IDs change, keep task cleanup, source closure, completion messages, and active-operation counts aligned in both WebSocket handlers.
- If cancellation or heartbeat behavior changes, check that the source and all background tasks close on client stop, disconnect, and normal completion.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Client uses a WebSocket protocol that is not enabled | The handshake closes with an unacceptable-subprotocol error. | Configure the same protocol name in the integration and the client. |
Client starts a WebSocket operation before connection_ack | The connection is rejected as unauthorized. | Wait for connection_ack after connection_init. |
| A legacy WebSocket connection reaches its configured active-operation limit | The new operation receives an operation error and does not start. | Stop completed or unwanted operations before starting more, or raise the connection limit. |
graphql-transport-ws receives @defer or @stream output | Strawberry sends an operation error because the protocol cannot represent incremental frames. | Use an HTTP streaming transport for incremental delivery. |
| Multipart subscription is used with a batch request | The request fails because this transport supports one subscription operation per response. | Open separate streaming requests. |
| A long-lived HTTP stream is placed behind buffering or compression middleware | Results and heartbeats can be delayed until the middleware flushes or completes the response. | Exclude SSE and multipart routes from response buffering and compression. |
| A client disconnects without source cleanup | Event listeners or async tasks can remain active. | Close the async source and release application-level listeners on cancellation. |
Key files
| File | Why to read it |
|---|---|
| strawberry/…/schema.py | Defines the common subscription and streaming execution paths. |
| strawberry/…/mutation.py | Defines the public @strawberry.subscription field marker. |
| strawberry/…/async_base_view.py | Connects HTTP and WebSocket requests to schema streams and transport output. |
| strawberry/…/handlers.py | Shows the newer WebSocket connection and operation lifecycle. |
| strawberry/…/handlers.py | Shows the legacy WebSocket lifecycle, keep-alive behavior, operation limits, and cleanup. |
| strawberry/…/types.py | Defines the current WebSocket message contract for initialization, subscription results, errors, and completion. |
| strawberry/…/types.py | Defines the legacy WebSocket message contract and its keep-alive behavior. |
| strawberry/…/streaming.py | Defines SSE, multipart, heartbeat, and stream encoding behavior. |
| strawberry/streamable.py | Defines the public type marker for @stream list fields. |
| strawberry/…/execution.py | Defines normal, pre-execution, subscription, and incremental result contracts. |