Contents
GraphQL Subscriptions: Real-Time Data Synchronization
Consider a common scenario: user 1 edits a database record and their UI updates immediately, but user 2 has the same record open and sees stale data. They do not know it has changed. This is a common web-app problem: a lack of real-time synchronization between clients.
The problem: stale data in a multi-user environment
A concrete example
In a Jira- or Trello-like tool:
User A
User B
User B begins editing, unaware it is already done.
Conflict:
Other critical scenarios
E-commerce: Two users try to order the last item because one still sees it as available.
Collaborative editing: Multiple users edit a document; without synchronization changes are overwritten.
Dashboards and analytics: A manager sees metrics only on refresh and misses critical outages or traffic spikes.
Traditional solutions and their problems
1. Polling: repeatedly querying the server
The simplest, but worst, solution:
// Fetch new data every five seconds
setInterval(async () => {
const response = await fetch('/api/tasks/123');
const data = await response.json();
updateUI(data);
}, 5000);Problems: Server load from thousands of clients every five seconds; zero to five seconds' latency; many requests returning “nothing changed”; wasted bandwidth; mobile battery drain; and scaling issues.
Load calculation:
1,000 active users
× polling every five seconds
= 200 requestov/s na server
= 17,280,000 requests/dayMost of those requests are unnecessary! 🔥
2. Long polling
The client sends a request that the server holds open until it has data:
async function longPoll() {
const response = await fetch('/api/tasks/123/changes');
const data = await response.json();
updateUI(data);
longPoll(); // Immediately again
}It is better than polling but still has HTTP overhead, timeouts and proxy interruptions.
3. Server-Sent Events (SSE)
A one-way server-to-client stream:
const eventSource = new EventSource('/api/tasks/123/stream');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
updateUI(data);
};Advantages: Automatic reconnect, a built-in browser API and simpler implementation than WebSockets. Problems: server-to-client only, browser connection limits and HTTP/1.1 connection constraints.
4. WebSockets
Bidirectional, full-duplex communication:
const ws = new WebSocket('ws://localhost:4000');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
updateUI(data);
};Advantages: Bidirectional, low latency and efficient for real time. Problems: more complicated implementation, custom message formats, authentication and scaling/load balancing.
GraphQL subscriptions: best of both worlds
Subscriptions combine WebSockets with GraphQL:
subscription TaskUpdated($taskId: ID!) {
taskUpdated(taskId: $taskId) {
id
title
status
assignee {
id
name
avatar
}
updatedAt
updatedBy {
name
}
}
}Key benefits
1. Selective subscriptions: ask only for what you need
Unlike polling that fetches everything:
// Polling - Fetches everything
fetch('/api/tasks/123') // Returns 50+ fields
// GraphQL Subscription - Relevant fields only
subscription {
taskUpdated(taskId: "123") {
status // Zmena statusu
assignee { id name } // Zmena assignee
# Ignorujeme description, comments, attachments...
}
}If description and comments rarely change, omit them for less bandwidth and faster UI updates.
2. Event-driven vs polling
Polling model:
T=0s → Request → Response (no change)
T=5s → Request → Response (no change)
T=10s → Request → Response (CHANGE!)
Latencia: 0-5s (priemer 2.5s)
Subscription model:
T=0s → Subscribe
T=10s → Event occurs → Push (CHANGE!)
Latencia: ~50ms3. Intelligent filtering
Subscribe only to specific events:
subscription {
# Only tasks assigned to me
taskUpdated(assignedTo: $myUserId) {
id
title
status
}
# Len high priority tasky
taskCreated(priority: HIGH) {
id
title
}
# Only changes in a specific project
projectUpdated(projectId: $projectId) {
stats {
tasksCompleted
tasksInProgress
}
}
}Result: The client receives relevant updates, not everything that happened.
How GraphQL subscriptions work under the hood
Architecture
┌─────────────┐ WebSocket ┌─────────────┐
│ │◄──────────────────────────►│ │
│ Client │ 1. Subscribe request │ Server │
│ (Browser) │ 2. Event notifications │ (GraphQL) │
│ │ 3. Unsubscribe │ │
└─────────────┘ └──────┬──────┘
│
┌──────▼──────┐
│ PubSub │
│ System │
│ (Redis, │
│ RabbitMQ) │
└─────────────┘Subscription lifecycle
1. Client initializes a subscription
// Apollo Client
import { useSubscription, gql } from '@apollo/client';
const TASK_UPDATED = gql`
subscription OnTaskUpdated($taskId: ID!) {
taskUpdated(taskId: $taskId) {
id
status
assignee { name }
}
}
`;
function TaskDetail({ taskId }) {
const { data, loading } = useSubscription(TASK_UPDATED, {
variables: { taskId }
});
if (loading) return <p>Connecting...</p>;
return <TaskCard task={data.taskUpdated} />;
}2. Server resolver subscribes to PubSub
// Apollo Server
const resolvers = {
Subscription: {
taskUpdated: {
subscribe: (_, { taskId }, { pubsub }) => {
// Subscribe to the channel for this task
return pubsub.asyncIterator([`TASK_UPDATED_${taskId}`]);
}
}
},
Mutation: {
updateTask: async (_, { taskId, input }, { pubsub, db }) => {
// Aktualizuj task v DB
const updatedTask = await db.tasks.update(taskId, input);
// Publikuj event
await pubsub.publish(`TASK_UPDATED_${taskId}`, {
taskUpdated: updatedTask
});
return updatedTask;
}
}
};3. WebSocket connection lifecycle
// graphql-ws library (modern implementation)
import { createClient } from 'graphql-ws';
const client = createClient({
url: 'ws://localhost:4000/graphql',
// Authentication
connectionParams: async () => {
const token = await getAuthToken();
return {
authorization: token ? `Bearer ${token}` : ""
};
},
// Reconnect logic
retryAttempts: 5,
retryWait: (retries) => Math.min(1000 * 2 ** retries, 30000),
// Heartbeat (ping/pong)
keepAlive: 10000
});Implementation: practical example
Backend (Node.js + Apollo Server)
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { createServer } from 'http';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { PubSub } from 'graphql-subscriptions';
const pubsub = new PubSub();
// Schema
const typeDefs = `#graphql
type Task {
id: ID!
title: String!
status: TaskStatus!
assignee: User
updatedAt: String!
}
enum TaskStatus {
TODO
IN_PROGRESS
DONE
}
type User {
id: ID!
name: String!
}
type Query {
task(id: ID!): Task
}
type Mutation {
updateTaskStatus(id: ID!, status: TaskStatus!): Task!
}
type Subscription {
taskUpdated(taskId: ID!): Task!
taskStatusChanged(projectId: ID!): Task!
}
`;
// Resolvers
const resolvers = {
Subscription: {
taskUpdated: {
subscribe: (_, { taskId }) =>
pubsub.asyncIterator([`TASK_${taskId}`])
},
taskStatusChanged: {
subscribe: (_, { projectId }) =>
pubsub.asyncIterator([`PROJECT_${projectId}_TASKS`])
}
},
Mutation: {
updateTaskStatus: async (_, { id, status }, { db }) => {
const task = await db.tasks.update(id, { status });
// Publish to all relevant channels
await pubsub.publish(`TASK_${id}`, { taskUpdated: task });
await pubsub.publish(
`PROJECT_${task.projectId}_TASKS`,
{ taskStatusChanged: task }
);
return task;
}
}
};
// Server setup
const schema = makeExecutableSchema({ typeDefs, resolvers });
const app = express();
const httpServer = createServer(app);
// WebSocket server pre subscriptions
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql'
});
const serverCleanup = useServer({ schema }, wsServer);
const server = new ApolloServer({
schema,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
}
};
}
}
]
});
await server.start();
app.use('/graphql', cors(), json(), expressMiddleware(server));
httpServer.listen(4000, () => {
console.log(`🚀 Server ready at http://localhost:4000/graphql`);
console.log(`🔌 Subscriptions ready at ws://localhost:4000/graphql`);
});Frontend (React + Apollo Client)
import { ApolloClient, InMemoryCache, split, HttpLink } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { getMainDefinition } from '@apollo/client/utilities';
import { createClient } from 'graphql-ws';
// HTTP link pre queries a mutations
const httpLink = new HttpLink({
uri: 'http://localhost:4000/graphql'
});
// WebSocket link pre subscriptions
const wsLink = new GraphQLWsLink(
createClient({
url: 'ws://localhost:4000/graphql',
connectionParams: {
authToken: localStorage.getItem('token')
}
})
);
// Split traffic: subscriptions → WS, queries/mutations → HTTP
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache()
});
// Component
function TaskBoard({ projectId }) {
const { data: initialData } = useQuery(GET_TASKS, {
variables: { projectId }
});
const { data: subscriptionData } = useSubscription(
TASK_STATUS_CHANGED,
{ variables: { projectId } }
);
// Merge initial data + real-time updates
const tasks = subscriptionData?.taskStatusChanged
? updateTaskInList(initialData.tasks, subscriptionData.taskStatusChanged)
: initialData?.tasks;
return <TaskList tasks={tasks} />;
}Backend implementation: Java/Spring Boot
@Configuration
public class GraphQLSubscriptionConfig {
@Bean
public Executor subscriptionExecutor() {
return Executors.newCachedThreadPool();
}
}
@Component
public class TaskSubscription {
private final Sinks.Many<Task> taskSink = Sinks.many()
.multicast()
.onBackpressureBuffer();
@SubscriptionMapping
public Flux<Task> taskUpdated(@Argument String taskId) {
return taskSink.asFlux()
.filter(task -> task.getId().equals(taskId));
}
@MutationMapping
public Task updateTaskStatus(
@Argument String id,
@Argument TaskStatus status
) {
Task task = taskService.updateStatus(id, status);
// Emit event
taskSink.tryEmitNext(task);
return task;
}
}Optimization and best practices
1. Batching and deduplication
When several users edit the same record:
// Naive implementation: 10 updates = 10 broadcast messages
for (let i = 0; i < 10; i++) {
await pubsub.publish('TASK_123', { taskUpdated });
}
// Optimized: debounce + batch
const debouncedPublish = debounce(async (taskId, task) => {
await pubsub.publish(`TASK_${taskId}`, { taskUpdated: task });
}, 100);2. Connection pooling
Redis PubSub for distributed systems:
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
const options = {
host: 'localhost',
port: 6379,
retryStrategy: (times) => Math.min(times * 50, 2000)
};
const pubsub = new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options)
});3. Subscription-level authorization
const resolvers = {
Subscription: {
taskUpdated: {
subscribe: withFilter(
(_, { taskId }, { pubsub }) =>
pubsub.asyncIterator([`TASK_${taskId}`]),
// Filter: Send only if the user has permission
async (payload, variables, context) => {
const task = payload.taskUpdated;
const user = context.user;
return await hasAccess(user, task);
}
)
}
}
};4. Cleanup on disconnect
const wsServer = new WebSocketServer({ server: httpServer });
useServer({
schema,
context: (ctx) => {
// Track active subscriptions
return {
connectionId: ctx.connectionParams?.id,
cleanup: () => {
console.log(`Client ${ctx.connectionParams?.id} disconnected`);
// Cleanup resources
}
};
},
onDisconnect: (ctx) => {
ctx.cleanup?.();
}
}, wsServer);Real-world use cases
1. Collaborative text editor
subscription DocumentChanged($documentId: ID!) {
documentChanged(documentId: $documentId) {
content
cursor {
userId
position
}
version
}
}2. Live chat
subscription NewMessage($channelId: ID!) {
messageAdded(channelId: $channelId) {
id
text
author {
id
name
avatar
}
timestamp
}
}3. Stock ticker / trading platform
subscription StockPriceUpdates($symbols: [String!]!) {
stockPrices(symbols: $symbols) {
symbol
price
change
timestamp
}
}4. Multiplayer game state
subscription GameState($gameId: ID!) {
gameUpdated(gameId: $gameId) {
players {
id
position { x y }
health
}
items {
id
type
position { x y }
}
}
}5. IoT device monitoring
subscription DeviceMetrics($deviceId: ID!) {
metricsUpdated(deviceId: $deviceId) {
temperature
humidity
batteryLevel
status
timestamp
}
}GraphQL subscriptions vs alternatives
| Feature | Polling | SSE | WebSockets | GraphQL subscriptions |
|---|---|---|---|---|
| Latency | 2–5s | ~100ms | ~50ms | ~50ms |
| Server load | High | Low | Low | Low |
| Bidirectional | ❌ | ❌ | ✅ | ✅ |
| Type safety | ⚠️ | ⚠️ | ❌ | ✅ |
| Selective fields | ⚠️ | ❌ | ❌ | ✅ |
| Auto reconnect | ✅ | ✅ | ⚠️ | ✅ |
| Browser support | ✅ | ✅ | ✅ | ✅ |
| Complexity | Simple | Medium | High | Medium |
When should you use subscriptions?
✅ Use them if:
- Multiple clients need real-time updates, such as collaborative tools, project management or chat.
- Data changes unpredictably: stock prices, IoT readings or live sports scores.
- You want to reduce server load by replacing polling and sending only changes.
- You need type-safe real time and autocomplete in TypeScript/Flow projects.
❌ Avoid them if:
- A simple app has no multi-user interactions, such as a personal dashboard.
- Data changes rarely, such as configuration or static content.
- SEO/crawling is a priority: WebSockets are not crawlable; use SSR + HTTP.
- You cannot maintain the infrastructure complexity of PubSub, Redis and WebSockets.
Conclusion
GraphQL subscriptions address a fundamental question: how to efficiently synchronize data among clients in real time. Their benefits include event-driven updates instead of polling, selective data, type safety and autocomplete, bidirectional WebSockets and Redis PubSub scaling.
They make sense for multi-user collaborative tools, dashboards, chat and real-time analytics. If periodic refresh is enough, polling or server-side rendering may suffice. Subscriptions are not a silver bullet, but the right use cases can improve UX and reduce server load.
For more information visit GraphQL subscriptions.