MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Real-Time GraphQL Subscriptions with WebSockets0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
13.1GraphQL Fundamentals and Apollo Client Setup13.2Executing GraphQL Queries with useQuery13.3GraphQL Mutations and Optimistic UI Updates13.4Real-Time GraphQL Subscriptions with WebSockets
HomeTutorialsReact.js for AdvancedReal-Time GraphQL Subscriptions with WebSockets
WebSockets Architecture with Socket.io in React

Real-Time GraphQL Subscriptions with WebSockets

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While queries and mutations follow the classic request-response cycle, real-time enterprise features (such as live trading monitors, collaborative chat, and real-time document notifications) require bidirectional push communication. GraphQL Subscriptions maintain a persistent WebSocket connection between client and server, streaming events to React components using useSubscription.


1. GraphQL Transport Layer Architecture

Modern Apollo Client architectures use a split-link configuration:

  • HTTP Link (httpLink): Handles standard Queries and Mutations over HTTP/HTTPS.
  • WebSocket Link (wsLink): Handles persistent Subscriptions using the standard graphql-ws library.
1React Application
2 │
3 ▼
4Apollo Split Link (isSubscription?)
5 ├─── Yes ──► GraphQL-WS Link ──► wss://api.enterprise.com/graphql
6 └─── No ──► HTTP Link ──► https://api.enterprise.com/graphql

2. Setting Up Split Link with graphql-ws

1npm install graphql-ws

3. Consuming Live Events with useSubscription

1import React, { useState } from "react";
2import { gql, useSubscription } from "@apollo/client";
3 
4const LIVE_SECURITY_ALERTS = gql`
5 subscription OnSecurityAlert($clusterId: ID!) {
6 securityAlertAdded(clusterId: $clusterId) {
7 id
8 severity
9 message
10 timestamp
11 }
12 }
13`;
14 
15interface Alert {
16 id: string;
17 severity: "LOW" | "HIGH" | "CRITICAL";
18 message: string;
19 timestamp: string;
20}
21 
22export function LiveSecurityFeed({ clusterId }: { clusterId: string }) {
23 const [alerts, setAlerts] = useState<Alert[]>([]);
24 
25 // Subscribes to incoming live WebSocket events
26 useSubscription(LIVE_SECURITY_ALERTS, {
27 variables: { clusterId },
28 onData: ({ data }) => {
29 const newAlert = data.data?.securityAlertAdded;
30 if (newAlert) {
31 setAlerts((prev) => [newAlert, ...prev.slice(0, 49)]); // Keep last 50
32 }
33 },
34 });
35 
36 return (
37 <div className="p-6 bg-slate-900 border border-slate-800 rounded-xl text-white">
38 <div className="flex items-center justify-between mb-4">
39 <h2 className="font-bold text-lg">Live Telemetry & Security Alerts</h2>
40 <span className="flex items-center gap-2 text-xs text-emerald-400 font-mono">
41 <span className="h-2 w-2 rounded-full bg-emerald-400 animate-ping" />
42 WebSocket Connected
43 </span>
44 </div>
45 
46 <div className="space-y-2 max-h-80 overflow-y-auto">
47 {alerts.length === 0 ? (
48 <p className="text-xs text-slate-500 italic">Listening for cluster events...</p>
49 ) : (
50 alerts.map((alert) => (
51 <div
52 key={alert.id}
53 className="p-3 bg-slate-950 border border-slate-800 rounded flex justify-between items-center text-xs"
54 >
55 <div className="flex items-center gap-2">
56 <span
57 className={`font-bold px-1.5 py-0.5 rounded ${
58 alert.severity === "CRITICAL"
59 ? "bg-rose-950 text-rose-400 border border-rose-800"
60 : "bg-amber-950 text-amber-400"
61 }`}
62 >
63 {alert.severity}
64 </span>
65 <span className="text-slate-200">{alert.message}</span>
66 </div>
67 <span className="text-slate-500 font-mono">{alert.timestamp}</span>
68 </div>
69 ))
70 )}
71 </div>
72 </div>
73 );
74}

4. Subscriptions vs Polling

Avoid using subscriptions for data that changes infrequently. For standard status checks (e.g. tracking a background export progress), simple query polling (pollInterval: 5000) avoids the overhead of managing long-lived WebSocket connections and socket reconnections.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What protocol does Apollo Client use to maintain persistent GraphQL Subscriptions?
Question 2
What is the purpose of the split function in Apollo Client configuration?
Question 3
What is the current standard library for GraphQL WebSockets recommended over the deprecated subscriptions-transport-ws?
Question 4
How do you authenticate a WebSocket connection in graphql-ws?
Question 5
When should you prefer query polling (pollInterval) over GraphQL Subscriptions?
Next Lesson

WebSockets Architecture with Socket.io in React

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
GraphQL Mutations and Optimistic UI UpdatesWebSockets Architecture with Socket.io in React

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext