Implementing Real-time Features

1. Setting Up WebSocket Server

Example: graphql-ws

import { useServer } from "graphql-ws/lib/use/ws";
import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ server: httpServer, path: "/graphql" });
useServer({
  schema,
  context: async (ctx) => ({ user: await auth(ctx.connectionParams?.token), pubsub })
}, wss);

2. Managing Connection Lifecycle

HookUse
onConnectAuthenticate, build context
onSubscribePer-operation auth/validation
onCompleteCleanup per-subscription
onCloseTear down connection-scoped resources
onPing/onPongKeepalive

3. Implementing Live Queries

ApproachDetail
@live directiveServer re-pushes on change (graphql-live-query)
PollingClient refetches at interval
Subscription wrapSubscribe to entity changes, refetch

4. Using Server-sent Events

Example: graphql-sse

import { createHandler } from "graphql-sse/lib/use/express";
app.use("/graphql/stream", createHandler({ schema }));
SSE vs WebSocketDetail
DirectionServer-to-client only
ReconnectAutomatic (browser-native EventSource)
ProxiesWorks through any HTTP/1.1 proxy

5. Implementing Presence Features

PatternDetail
Online users setRedis SET per channel
HeartbeatClient emits every 30s; server expires after 60s
SubscriptionpresenceChanged(channelId)

6. Broadcasting Events

Example: Redis-backed PubSub

import { RedisPubSub } from "graphql-redis-subscriptions";
const pubsub = new RedisPubSub({
  publisher: new Redis(REDIS_URL),
  subscriber: new Redis(REDIS_URL)
});

7. Filtering Real-time Updates

WhereDetail
withFilterPer-event predicate
Topic namingInclude shard key (e.g., room:42:msg)
AuthRe-check on every event (permissions may revoke)

8. Implementing Event Sourcing

AspectDetail
Source eventsDomain events stored append-only
SubscriptionsProject events into GraphQL streams
ReplayNew subscribers can fetch from cursor

9. Handling Connection Drops

StrategyDetail
Client retryExponential backoff with jitter
Resume cursorSend lastEventId on reconnect
Idempotent eventsReplays must be safe

10. Scaling Real-time Services

LayerDetail
Pub/Sub backboneRedis, NATS, Kafka for cross-node fanout
Sticky sessionsWebSocket needs session affinity at LB
Connection limitTune ulimit, file descriptors
ShardingPartition channels across nodes