Apollo 13: Subscriptions & Polling
easy⏱ 5 mincourseapollo
Real-time data strategies
Apollo provides three strategies for real-time data:
- useSubscription: A hook that opens a WebSocket connection and returns data as it arrives. Similar API to
useQuery but for push-based data.
- subscribeToMore: Called on a
useQuery result, it opens a subscription that updates the query's cached data. Perfect for appending new items to a list.
- pollInterval: The simplest option — pass
pollInterval: 5000 to useQuery and it re-fetches every 5 seconds. No WebSocket needed.
// Polling — simplest real-time
const { data } = useQuery(GET_MESSAGES, {
pollInterval: 3000, // refetch every 3s
});
// subscribeToMore — append new items
const { data, subscribeToMore } = useQuery(GET_MESSAGES);
useEffect(() => {
return subscribeToMore({
document: MESSAGE_ADDED,
updateQuery: (prev, { subscriptionData }) => ({
messages: [...prev.messages, subscriptionData.data.messageAdded],
}),
});
}, [subscribeToMore]);
Add polling to a query
Create a MessageFeed component that uses useQuery(GET_MESSAGES, { pollInterval: 5000 }). Add a toggle button to start/stop polling using startPolling(5000) and stopPolling(). Display the last-updated timestamp so users can see when data was refreshed. Show the message count updating in real-time.
Polling as WebSocket fallback
WebSocket subscriptions require server-side support and add infrastructure complexity. Polling is a great alternative when: data changes infrequently (every few seconds is fine), you can't set up WebSocket infrastructure, or you need to work through proxies that don't support WebSocket. Start with polling — upgrade to subscriptions only when you need sub-second latency.
When to use subscriptions vs polling
Use subscriptions for: chat messages, live notifications, collaborative editing, stock prices — anything where sub-second latency matters and events are frequent. Use polling for: dashboards, feed refreshes, status checks — anything where a few seconds of staleness is acceptable. Use subscribeToMore when you have an initial query result (e.g., last 50 messages) and want to append new items as they arrive via subscription.