DEV Community

Cover image for GraphQL Subscriptions in Production: Real-Time Without the Tears
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

GraphQL Subscriptions in Production: Real-Time Without the Tears

The first time I shipped a GraphQL subscriptions endpoint, it worked perfectly on localhost with one user. The second time, with two users on two different servers, nothing happened. I stared at the logs for an hour before realizing that the in-process pub/sub I'd cribbed from a tutorial didn't fan out across instances. Each server was happily publishing to itself and nobody else.

That's GraphQL subscriptions in miniature. The protocol is straightforward, the server library is fine, the client library is fine. The pain is in everything around it: auth over WebSocket, fan-out across processes, connection lifecycle, backpressure, and the fact that WebSocket connections behave nothing like HTTP when your load balancer has opinions. This is the guide I wish I'd had before that first debugging session.

GraphQL subscriptions are the real-time part of GraphQL. Queries fetch data, mutations change it, subscriptions stream updates as they happen. Under the hood it's almost always WebSocket, with a small protocol layer that lets the client say "I want updates on this query" and the server push them when relevant events fire.

Subscriptions vs Polling vs SSE vs Plain WebSockets

Let's get the "why" out of the way. There are four ways to do real-time updates from a server, and they're not interchangeable.

Approach Direction Overhead GraphQL-native Best for
HTTP polling Client → Server High (wasted requests) N/A Trivial cases, no infra changes allowed
Server-Sent Events (SSE) Server → Client Low Possible One-way updates, no client messages
Plain WebSocket Bidirectional Low No Custom protocols, non-GraphQL apps
GraphQL subscriptions Bidirectional Low-medium Yes Apps already using GraphQL for queries/mutations

If you're already on GraphQL for the rest of your API, subscriptions are the obvious choice. You get one client library, one type system, one auth story. If you're not on GraphQL, adding it just for real-time is overkill-use SSE or plain WebSocket.

The common mistake is reaching for subscriptions when polling would do. If your "real-time" requirement is "users see updates within 30 seconds," polling every 15 seconds is simpler, cheaper, and more robust than WebSocket. Subscriptions earn their complexity when you need sub-second updates or when the same client needs many different update streams.

Prerequisites

  • A GraphQL server already running. We'll use Strawberry + FastAPI, but the patterns translate to Ariadne, Graphene, or Apollo Server (Node).
  • Python 3.11+. Strawberry 0.230+ uses modern typing.
  • Redis 6+ for cross-instance pub/sub. Local dev: docker run -d --name redis -p 6379:6379 redis:7.
  • A frontend with Apollo Client (or urql with the graphql-ws package). I'll show both client patterns.
  • Familiarity with GraphQL queries and mutations. If you've never written a resolver, start there.

You'll also want wscat for debugging: npm install -g wscat. The first time your subscription silently doesn't work, you'll want to poke the WebSocket by hand to see what's actually being sent.

Architecture Overview

Here's the system we're building:

CodeCopy

Enter fullscreen mode Exit fullscreen mode

┌───────────────┐ ┌──────────────────┐ ┌─────────┐
│ Browser │ │ FastAPI + │ │ Redis │
│ Apollo │◀───────▶│ Strawberry │◀───────▶│ pub/sub│
│ Client │ WS │ (per instance) │ pub/sub│ │
└───────────────┘ └──────────────────┘ └─────────┘
▲
│ events published by
│ mutations or workers
┌─────┴──────┐
│ App logic │
│ (any │
│ instance) │
└────────────┘

Enter fullscreen mode Exit fullscreen mode

The key insight: every FastAPI instance has its own set of connected WebSocket clients. When a mutation fires on instance A and needs to notify a client connected to instance B, instance A publishes to Redis. Instance B is subscribed to Redis and forwards the message to its connected client. Without this, your "real-time" feature works for users on the same instance and silently fails for everyone else.

This is what tripped me up that first time. The fix is one Redis pub/sub layer. It's not optional for any deployment with more than one process.

Project Layout

CodeCopy

Enter fullscreen mode Exit fullscreen mode


plaintext
app/
init.py
main.py # FastAPI app, mounts GraphQL + WS
config.py # settings
redis_client.py # async redis + pub/sub helpers
schema.py # strawberry Schema
context.py # context builder (DB, user, publisher)
auth.py # JWT verification for WS connections
pubsub.py # the broker abstraction
types/
init.py
user.py
message.py
resolvers/
init.py
queries.py
mutations.py
subscriptions.py
tests/
conftest.py
test_subscriptions.py

Enter fullscreen mode Exit fullscreen mode


markdown

Environment Setup

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
python -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install "fastapi==0.115.0" "uvicorn[standard]==0.30.6"
pip install "strawberry-graphql[asgi]==0.243.0"
pip install "redis[hiredis]==5.0.8" "redislite==5.0.0" # redislite optional, for tests
pip install "pydantic==2.9.2" "pydantic-settings==2.5.2"
pip install "python-jose[cryptography]==3.3.0"
pip install "httpx==0.27.2" "pytest==8.3.3" "pytest-asyncio==0.24.0"
pip install "websockets==13.1"

Enter fullscreen mode Exit fullscreen mode


markdown

Pin strawberry-graphql carefully. Strawberry ships frequent releases and the ASGI integration has changed signature twice in the last year. The [asgi] extra pulls in the ASGI helpers we need.

Config and Redis Client

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/config.py

from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_prefix="APP_")

redis_url: str = "redis://localhost:6379/0"
secret_key: str = "change-me"
algorithm: str = "HS256"
cors_origins: list[str] = ["http://localhost:3000"]
environment: str = "development"

@​lru_cache
def get_settings() -> Settings:
return Settings()

settings = get_settings()

Enter fullscreen mode Exit fullscreen mode


plaintext

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/redis_client.py

import redis.asyncio as redis

from app.config import settings

Connection pool for normal commands (publish, etc.)

_pool = redis.ConnectionPool.from_url(settings.redis_url, max_connections=20)

def get_redis() -> redis.Redis:
return redis.Redis(connection_pool=_pool)

Enter fullscreen mode Exit fullscreen mode


markdown

I keep two Redis access patterns: the connection pool for commands like publish, and a dedicated connection per subscription for subscribe. Pub/sub in Redis blocks the connection-you can't share it.

The Pub/Sub Broker

This is the abstraction that makes everything else clean. A Broker interface with an in-memory implementation for tests and a Redis implementation for prod.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/pubsub.py

import asyncio
import json
from collections.abc import AsyncIterator
from typing import Any, Protocol

import redis.asyncio as redis

from app.redis_client import get_redis

class Broker(Protocol):
async def publish(self, channel: str, payload: dict[str, Any]) -> int: ...
async def subscribe(self, channel: str) -> AsyncIterator[dict[str, Any]]: ...

class InMemoryBroker:
'''Single-process broker. Use only for tests or single-instance dev.'''

def init(self) -> None:
self._channels: dict[str, asyncio.Queue] = {}

async def publish(self, channel: str, payload: dict[str, Any]) -> int:
q = self._channels.get(channel)
if q is None:
return 0
await q.put(payload)
return 1

async def subscribe(self, channel: str) -> AsyncIterator[dict[str, Any]]:
if channel not in self._channels:
self._channels[channel] = asyncio.Queue()
q = self._channels[channel]
try:
while True:
yield await q.get()
finally:
self._channels.pop(channel, None)

class RedisBroker:
'''Multi-process broker backed by Redis pub/sub.'''

def init(self, redis_client: redis.Redis | None = None) -> None:
self._redis = redis_client or get_redis()

async def publish(self, channel: str, payload: dict[str, Any]) -> int:
return await self._redis.publish(channel, json.dumps(payload))

async def subscribe(self, channel: str) -> AsyncIterator[dict[str, Any]]:
# Each subscription needs its own dedicated connection.
pubsub = self._redis.pubsub()
await pubsub.subscribe(channel)
try:
async for message in pubsub.listen():
if message["type"] != "message":
continue
yield json.loads(message["data"])
finally:
await pubsub.unsubscribe(channel)
await pubsub.close()

Enter fullscreen mode Exit fullscreen mode


markdown

The Protocol lets your resolver code depend on the interface, not the implementation. In tests you swap in InMemoryBroker; in prod you use RedisBroker. Same resolver code, no monkeypatching.

Strawberry Schema: Types, Queries, Mutations

Let's model a chat system: users, messages, channels. The subscription is "new messages in a channel."

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/types/message.py

import uuid
from datetime import datetime
from typing import Optional

import strawberry
from strawberry.types import Info

@​strawberry.type
class User:
id: strawberry.ID
display_name: str

@​strawberry.type
class Message:
id: strawberry.ID
channel_id: strawberry.ID
author: User
body: str
created_at: datetime

Enter fullscreen mode Exit fullscreen mode


plaintext

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/resolvers/queries.py

from typing import Optional

import strawberry

from app.types.message import Message, User

@​strawberry.type
class Query:
@​strawberry.field
async def me(self, info: strawberry.Info) -> Optional[User]:
user = info.context["user"]
if user is None:
return None
return User(id=strawberry.ID(user["sub"]), display_name=user["name"])

@​strawberry.field
async def messages(
self, info: strawberry.Info, channel_id: strawberry.ID, limit: int = 50
) -> list[Message]:
# In real code, fetch from DB. Returning placeholder shape.
return []

Enter fullscreen mode Exit fullscreen mode


plaintext

The mutation is where we publish events. The pattern: do the write, publish the event, return the result. The publish happens after the commit-never before, or a subscriber might see an event for data that doesn't exist yet.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/resolvers/mutations.py

import uuid
from datetime import datetime, timezone

import strawberry

from app.types.message import Message, User
from app.pubsub import Broker

@​strawberry.type
class Mutation:
@​strawberry.mutation
async def send_message(
self, info: strawberry.Info, channel_id: strawberry.ID, body: str
) -> Message:
user = info.context["user"]
if user is None:
raise Exception("Not authenticated")

# Persist to DB here. Skipping for brevity.
message = Message(
id=strawberry.ID(str(uuid.uuid4())),
channel_id=channel_id,
author=User(id=strawberry.ID(user["sub"]), display_name=user["name"]),
body=body,
created_at=datetime.now(timezone.utc),
)

# Publish to the channel's subscribers.
broker: Broker = info.context["broker"]
await broker.publish(
f"channel:{channel_id}",
{
"type": "message_added",
"channel_id": str(channel_id),
"message": {
"id": str(message.id),
"channel_id": str(message.channel_id),
"author": {
"id": str(message.author.id),
"display_name": message.author.display_name,
},
"body": message.body,
"created_at": message.created_at.isoformat(),
},
},
)
return message

Enter fullscreen mode Exit fullscreen mode


markdown

The Subscription Resolver

The subscription resolver is the part that actually streams data. The client sends a subscription query; the resolver returns an async generator that yields events as they arrive.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/resolvers/subscriptions.py

import strawberry

from app.types.message import Message, User
from app.pubsub import Broker

@​strawberry.type
class Subscription:
@​strawberry.subscription
async def message_added(
self, info: strawberry.Info, channel_id: strawberry.ID
) -> strawberry.AsyncGenerator[Message, None]:
user = info.context["user"]
if user is None:
raise Exception("Not authenticated")

# Authorization: in real code, check that user can see channel_id.
broker: Broker = info.context["broker"]
async for event in broker.subscribe(f"channel:{channel_id}"):
if event["type"] != "message_added":
continue
m = event["message"]
yield Message(
id=strawberry.ID(m["id"]),
channel_id=strawberry.ID(m["channel_id"]),
author=User(
id=strawberry.ID(m["author"]["id"]),
display_name=m["author"]["display_name"],
),
body=m["body"],
created_at=m["created_at"], # Strawberry parses ISO strings
)

Enter fullscreen mode Exit fullscreen mode


markdown

Two things to internalize:

  1. The generator runs once per subscription. Each connected client gets its own instance of this generator. That's fine-in Redis pub/sub, multiple subscribers each get a copy of every message. Just don't put global state inside the generator.
  2. Auth happens inside the resolver, not at connection time. A user might be allowed to subscribe to channel A and not channel B. You need per-subscription authorization, not just connection-time auth. We'll do both.

Authentication for WebSocket Connections

This is the part that catches everyone. WebSocket connections don't have HTTP headers in the way browsers send them-you can't just put Authorization: Bearer ... on a WebSocket upgrade request from a browser. (You can from Node, but not from Chrome.)

There are two common patterns:

  1. Send the token in the first message. Client opens the WS, immediately sends a connection_init message with the token in the payload. Server validates before accepting subscriptions.
  2. Pass the token as a query param. wss://api.example.com/ws?token=.... Works but tokens leak into access logs.

I prefer the first pattern. The graphql-ws protocol formalizes it. Here's the implementation.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/auth.py

from typing import Optional

import jwt
from jwt import InvalidTokenError

from app.config import settings

def verify_token(token: str) -> Optional[dict]:
try:
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
except InvalidTokenError:
return None

Enter fullscreen mode Exit fullscreen mode


plaintext

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/context.py

from typing import Any

from strawberry.types import Info

from app.auth import verify_token
from app.pubsub import Broker, RedisBroker

def make_context(connection_params: dict[str, Any], broker: Broker) -> dict[str, Any]:
token = connection_params.get("Authorization") or connection_params.get(
"authorization"
)
if token and token.startswith("Bearer "):
token = token[7:]
user = verify_token(token) if token else None
return {"user": user, "broker": broker}

Enter fullscreen mode Exit fullscreen mode


markdown

Strawberry's ASGI integration lets you pass a context_getter that receives the connection params. Let's see how that wires up.

Wiring Up the ASGI App

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/main.py

from typing import Any

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from strawberry.fastapi import GraphQLRouter
from strawberry.schema import BaseSchema

from app.config import settings
from app.context import make_context
from app.pubsub import RedisBroker, InMemoryBroker, Broker
from app.schema import build_schema

def create_app() -> FastAPI:
app = FastAPI(title="Chat API")
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=[""],
allow_headers=["
"],
)

broker: Broker = (
RedisBroker() if settings.environment != "test" else InMemoryBroker()
)
schema: BaseSchema = build_schema()

async def context_getter(
connection_params: dict[str, Any],
) -> dict[str, Any]:
return make_context(connection_params, broker)

graphql_app = GraphQLRouter(
schema,
context_getter=context_getter,
subscription_protocols=["graphql-ws", "graphql-transport-ws"],
)
app.include_router(graphql_app, prefix="/graphql")
app.state.broker = broker
return app

app = create_app()

Enter fullscreen mode Exit fullscreen mode


plaintext

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

app/schema.py

import strawberry

from app.resolvers.queries import Query
from app.resolvers.mutations import Mutation
from app.resolvers.subscriptions import Subscription

def build_schema():
return strawberry.Schema(
query=Query,
mutation=Mutation,
subscription=Subscription,
)

Enter fullscreen mode Exit fullscreen mode


markdown

The subscription_protocols list tells Strawberry which WS protocols to accept. graphql-transport-ws is the newer one (used by Apollo Client v3 and graphql-ws). graphql-ws is the older subscriptions-transport-ws protocol-keep it for legacy clients, drop it when you can.

The Client Side: Apollo Client

Most frontend code uses Apollo Client. Here's the setup that works with the server above.

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
// src/apollo.ts
import { ApolloClient, InMemoryCache, split, HttpLink } from "@​apollo/client";
import { GraphQLWsLink } from "@​apollo/client/link/subscriptions";
import { createClient as createWsClient } from "graphql-ws";
import { getMainDefinition } from "@​apollo/client/utilities";

const httpLink = new HttpLink({
uri: "http://localhost:8000/graphql",
credentials: "include",
});

const wsLink = new GraphQLWsLink(
createWsClient({
url: "ws://localhost:8000/graphql",
connectionParams: () => {
const token = localStorage.getItem("token");
return token ? { Authorization: Bearer ${token} } : {};
},
}),
);

const splitLink = split(
({ query }) => {
const def = getMainDefinition(query);
return (
def.kind === "OperationDefinition" && def.operation === "subscription"
);
},
wsLink,
httpLink,
);

export const apolloClient = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});

Enter fullscreen mode Exit fullscreen mode


plaintext

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


tsx
// src/components/ChannelView.tsx
import { useSubscription, gql } from "@​apollo/client";

const MESSAGE_ADDED = gql
subscription MessageAdded($channelId: ID!) {
messageAdded(channelId: $channelId) {
id
body
author {
id
displayName
}
createdAt
}
}
;

export function ChannelView({ channelId }: { channelId: string }) {
const { data, loading } = useSubscription(MESSAGE_ADDED, {
variables: { channelId },
shouldResubscribe: true,
});

// Use data.messageAdded to update your UI / cache.
return null;
}

Enter fullscreen mode Exit fullscreen mode


markdown

Three things clients always get wrong:

  1. connectionParams as a function, not a static object. Tokens expire. If you pass a static object, you'll connect once with a valid token and never refresh. A function re-evaluates on reconnect.
  2. shouldResubscribe: true when the variables change. Without this, Apollo won't re-run the subscription when channelId changes.
  3. Updating the cache correctly. The easiest pattern is subscribeToMore on a query, which appends incoming messages to the query's result. Don't try to manage a separate state array-it desyncs from the cache.

Scaling: The Connection Math

WebSocket connections are persistent. Each one holds a file descriptor, memory (typically 50-200KB per connection), and a goroutine/task on the server. This is fundamentally different from HTTP, where each request is short-lived.

Rough numbers on a single Uvicorn worker with Strawberry's ASGI handler:

  • Comfortable: ~2,000-5,000 concurrent connections per worker.
  • Maximum: ~10,000-15,000, after which event loop lag becomes noticeable.
  • Memory: ~100MB per 1,000 connections in my tests, mostly from per-connection state.

Multiply by workers and instances. A 4-worker instance handles ~20K connections. A 10-instance cluster handles ~200K. Past that, you need a dedicated WS tier (no HTTP traffic competing) and probably HAProxy or Envoy in front, configured for long-lived connections.

The thing that bites you at scale: idle connections still cost memory. A user who opens your app and walks away holds a connection for hours. Implement a heartbeat (ping/pong every 30s) and disconnect clients that don't respond within 60s. Both Apollo Client and graphql-ws support this.

Connection Lifecycle and Reconnection

Clients will disconnect. Networks drop, laptops sleep, mobile apps background. Your client library should reconnect with exponential backoff, and your server should handle the churn gracefully.

graphql-ws has built-in reconnect:

TypeScriptCopy

Enter fullscreen mode Exit fullscreen mode


javascript
const wsClient = createWsClient({
url: "ws://localhost:8000/graphql",
retryAttempts: 5,
retryWait: (attempt) => new Promise((resolve) =>
setTimeout(resolve, Math.min(1000 * 2 ** attempt, 30000))
),
connectionParams: () => ({ Authorization: Bearer ${getToken()} }),
on: {
connected: () => console.log("WS connected"),
closed: (event) => console.log("WS closed", event.code, event.reason),
},
});

Enter fullscreen mode Exit fullscreen mode


markdown

Server-side, log connection events with a correlation ID. When a user reports "my subscriptions stopped working," you need to know whether the WS died, the auth expired, or the broker lost its Redis subscription. Without logging these transitions, you're guessing.

Production Considerations

Load balancer timeouts. AWS ALB defaults to 60s idle timeout for WebSocket. If your heartbeat is 30s, fine. If it's 2 minutes, the LB closes the connection first and you get random disconnects. Set LB idle timeout > heartbeat interval.

Sticky sessions: usually not needed. Subscriptions don't require the same instance-the client can reconnect to any instance. But sticky sessions reduce churn during reconnects. Trade-off: stickiness breaks horizontal scaling for connection count. I skip stickiness and let reconnects happen.

Auth token expiry. If your JWT expires in 1 hour, the WS connection stays open past that. You have two choices: proactively close the WS before the token expires (and let the client reconnect with a refreshed token), or validate the token on every message (more expensive, but tighter security). I prefer the former.

Redis cluster vs single Redis. For pub/sub, a single Redis instance handles ~50K published messages per second easily. Redis Cluster adds complexity because pub/sub in cluster mode doesn't shard-you have to use SPUBLISH/SSUBSCRIBE (sharded pub/sub) or accept fan-out overhead. Start with single Redis, scale when you have evidence you need it.

Backpressure. If a client is slow to consume messages (e.g., on a flaky mobile connection), the server can build up a queue. graphql-ws doesn't have built-in backpressure. Mitigation: drop messages older than N seconds for non-critical subscriptions, or use a bounded buffer and disconnect clients that overflow it.

Monitoring. Track: active connections per instance, messages published per second, messages delivered per second, reconnect rate, average connection duration. If publish rate is high but delivery rate is low, you have subscribers not consuming. If reconnect rate spikes, your LB or network is misbehaving.

Common Mistakes

Mistake: In-process pub/sub in prod. Works on one instance, fails on multiple. Detect: subscriptions work for users on the same instance, fail for users on different instances. Fix: Redis pub/sub, always.

Mistake: Auth at connection time only. User connects with a valid token, then loses permission to view a channel 10 minutes later. They keep receiving updates. Fix: re-check authorization inside the subscription generator on each event, or implement a permission revocation channel that publishes "disconnect this user" messages.

Mistake: Forgetting to unsubscribe. Client navigates away, but the WS stays open and the subscription keeps running on the server. Detect: connection count grows over time, never drops. Fix: ensure the client sends complete on unsubscribe (Apollo Client does this automatically). Server-side, treat WS close as "complete all subscriptions."

Mistake: Publishing before commit. Mutation writes to DB, publishes event, then the commit fails. Subscribers see a phantom message. Fix: commit first, then publish. If you need transactional "exactly once," use the transactional outbox pattern-write the event to a table, a separate worker reads and publishes.

Mistake: One Redis connection for everything. You share a Redis connection between publish calls and subscribe generators. Pub/sub blocks the connection. Fix: dedicated connection per subscriber, separate connection pool for commands.

Mistake: No heartbeat. Clients go idle, NAT timeouts kill the connection silently, server still thinks they're connected. Detect: connection count never drops even when no traffic. Fix: ping every 30s, disconnect on no pong within 60s.

Troubleshooting: Real Issues I've Hit

Subscription silently does nothing. 90% of the time, the client isn't sending connection_init with the token, or the server isn't reading the right key. Debug: run wscat -c ws://localhost:8000/graphql and send the protocol messages by hand. See exactly what the server logs.

Connection 1-1 didn't send a valid ack. You're using subscriptions-transport-ws protocol with a server expecting graphql-transport-ws. The two are different. Fix: align client and server-use graphql-ws (the package) on both sides.

Redis SUBSCRIBE returns but no messages arrive. Likely the publisher and subscriber are on different Redis databases (redis://host/0 vs /1). Debug: redis-cli PSUBSCRIBE '*' in one terminal, run your mutation, see if it appears.

Memory grows without bound. Every subscriber holds a queue. If events pile up faster than the client consumes, the queue grows. Fix: bounded asyncio.Queue(maxsize=100) with queue.put_nowait() and drop-or-disconnect on full.

Tests hang forever. Your subscription generator never returns. Pytest waits. Fix: use a timeout in tests (asyncio.wait_for(...)), and ensure your InMemoryBroker properly closes queues when tests end.

Connection drops every 60s in prod. AWS ALB idle timeout. Fix: set heartbeat < 60s, or raise the LB timeout to 3600s.

Testing Subscriptions

Subscriptions are awkward to test because they're stateful. The pattern I use: connect, subscribe, mutate, assert event arrives, disconnect.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python

tests/test_subscriptions.py

import asyncio
import json

import pytest
import websockets
from httpx import AsyncClient

from app.main import create_app
from app.pubsub import InMemoryBroker

GRAPHQL_WS_URL = "ws://localhost:8000/graphql"

async def gql_ws_flow(ws, token: str, sub_query: str, variables: dict):
# 1. connection_init with token
await ws.send(json.dumps({"type": "connection_init", "payload": {
"Authorization": f"Bearer {token}",
}}))
ack = await ws.recv()
assert json.loads(ack)["type"] == "connection_ack"

# 2. subscribe
await ws.send(json.dumps({
"type": "subscribe",
"id": "1",
"payload": {"query": sub_query, "variables": variables},
}))

# 3. wait for next event (caller then triggers a mutation)
while True:
msg = json.loads(await ws.recv())
if msg["type"] == "next":
return msg["payload"]["data"]

@​pytest.mark.asyncio
async def test_message_added_subscription(auth_token_factory):
token = await auth_token_factory(email="alice@example.com")
query = '''
subscription($channelId: ID!) {
messageAdded(channelId: $channelId) {
id
body
author { displayName }
}
}
'''
async with websockets.connect(GRAPHQL_WS_URL) as ws:
# Subscribe in a task so we can mutate concurrently
task = asyncio.create_task(
gql_ws_flow(ws, token, query, {"channelId": "ch-1"})
)
await asyncio.sleep(0.1) # let subscribe land

# Trigger the mutation via HTTP
async with AsyncClient(base_url="http://localhost:8000") as http:
await http.post(
"/graphql",
json={
"query": '''
mutation($channelId: ID!, $body: String!) {
sendMessage(channelId: $channelId, body: $body) {
id body
}
}
''',
"variables": {"channelId": "ch-1", "body": "hello"},
},
headers={"Authorization": f"Bearer {token}"},
)

data = await asyncio.wait_for(task, timeout=2.0)
assert data["messageAdded"]["body"] == "hello"

Enter fullscreen mode Exit fullscreen mode

This test runs against the real ASGI app with InMemoryBroker. The pattern-subscribe, mutate, assert event-mirrors how a real client behaves. Integration tests like this catch the bugs that unit tests on individual resolvers miss.

Cost Considerations

  • Single small instance + Redis: $20-40/month for ~5,000 concurrent connections. Fine for most apps.
  • Dedicated WS tier (5 instances, 2 vCPU each): ~$200-400/month for ~50,000 connections.
  • Redis (managed, smallest): ~$15/month. Use ElastiCache or Upstash for managed.
  • Bandwidth: pub/sub messages are tiny, but at 1K messages/sec to 10K subscribers, that's 10MB/sec out. Cloud egress adds up. Consider compressing payloads or batching.

The cost ceiling for subscriptions is connection count, not message rate. A chat app with 100K users online is much more expensive than an analytics dashboard pushing 100 updates/sec to 50 users.

Alternatives

  • SSE for one-way updates. If clients only receive (never send over the same channel), SSE is simpler. GraphQL-over-SSE exists but is less common.
  • Plain WebSocket with a custom protocol. Drop GraphQL for the real-time part, use GraphQL only for queries/mutations. Sometimes the right call-GraphQL subscriptions add protocol overhead.
  • Pusher / Ably / PubNub. Managed real-time services. Offload all the connection management. Pricey at scale, but you skip a lot of infrastructure work.
  • Phoenix Channels (Elixir) / Action Cable (Rails). If you're not on Python, these are battle-tested. Elixir's BEAM VM is genuinely the best runtime for massive connection counts.

Real-World Use Cases I've Shipped

  • Collaborative document editing. Subscriptions for cursor positions and presence. ~500 concurrent users, Redis pub/sub, single FastAPI instance. Worked fine.
  • Live auction bidding. High-stakes real-time. Used Redis Streams instead of pub/sub for durability and replay. Subscriptions consumed the stream.
  • Notifications panel. Trivial case, but I still see teams polling every 5s. Switched to subscriptions, server load dropped 80%.
  • Trading dashboard. Price ticks at 10Hz for 50 symbols per user. Hit backpressure issues immediately-added client-side throttling and dropped ticks older than 2s.

Wrapping Up

GraphQL subscriptions are a powerful tool that gets misused in two directions. Some teams treat them as the only way to do real-time, ending up with massive connection counts for things that should be polled. Other teams avoid them entirely and live with stale dashboards because "WebSockets are scary."

The truth is in the middle. Subscriptions are right when you need real-time updates to specific GraphQL queries, when you already have a GraphQL API, and when you can invest in the connection lifecycle. They're wrong when polling every 30 seconds would do.

If you take one thing from this: the broker is the system. The Strawberry resolvers, the Apollo Client setup, the auth flow-those are easy. The broker (and its scaling properties) is what decides whether your real-time feature survives launch day. Pick Redis, test it with multiple instances, and don't ship an in-memory broker to prod.


Originally published on Mango Developer.

Top comments (0)