Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Testing and Deployment

Monitoring and Debugging Socket.IO

Debug Socket.IO with the debug module and catch-all listeners, measure connections, rooms and message rates, use the Admin UI and plan alerts for production.

Real-time bugs are hard to reproduce: they depend on who is connected, in which room, with which transport. Good debugging starts with visibility. This lesson covers three levels: turn on the library's own debug logs, instrument your handlers, and collect production metrics with the Admin UI and a metrics endpoint.

Socket.IO is not installed in the runner on this site, so the real API calls are read-only. The runnable examples are plain Node.js stand-ins for the debug namespaces matcher, a metrics collector and a rate window.

Turn on the built-in logs

Socket.IO uses the debug package. Logs are off until you set the DEBUG environment variable with the namespaces you want:

Terminal
# everything from Socket.IO and Engine.IO
DEBUG=socket.io*,engine* node server.js

# only the Socket.IO core, not the transport details
DEBUG=socket.io:socket,socket.io:client node server.js

# everything except the noisy parts
DEBUG=*,-engine:ws,-engine:polling node server.js

In the browser, set it in the console and reload:

JavaScript
localStorage.debug = "socket.io-client:*";   // or "*" for everything

Namespaces are colon-separated, * is a wildcard, and a leading - excludes. That is the same filter language you can use for your own logging.

Node.js How DEBUG namespace patterns match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Use your own namespaces with the same package: const log = debug("app:chat"); log("joined %s", room), then enable with DEBUG=app:*.

See every event with catch-all listeners

When you are unsure which events flow, the catch-all listeners print them all without editing every handler:

JavaScript
io.on("connection", (socket) => {
  socket.onAny((event, ...args) => console.log(`[in ] ${socket.id} ${event}`, args));
  socket.onAnyOutgoing((event, ...args) => console.log(`[out] ${socket.id} ${event}`, args));
});

// client side: the same methods exist
socket.onAny((event, ...args) => console.log("received", event, args));

Do not log payloads in production: they may contain passwords, tokens and private messages. Log event names, sizes and ids instead.

Look inside a running server

All of these are cheap reads, useful in a debug route or a metrics endpoint:

JavaScript
io.engine.clientsCount;                    // connections at the transport level
io.of("/").sockets.size;                   // sockets in the main namespace on this process
io.of("/").adapter.rooms;                  // Map of room -> Set of socket ids (includes one room per socket id)
io.of("/").adapter.rooms.get("lobby")?.size;
await io.fetchSockets();                   // sockets across servers if an adapter is installed
socket.conn.transport.name;                // "polling" or "websocket"
socket.rooms;                              // rooms of this socket

Remember that each socket is also in a room named after its own id, so adapter.rooms.size counts those too. To count "real" rooms, subtract the socket count or filter out ids present in sockets.

Node.js A metrics collector with a rolling rate (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Counters only go up (total connections), gauges move both ways (current connections). Rates are computed by the dashboard from counters, so prefer exposing counters; the rolling rate above is useful for a quick in-app view.

Production metrics

Wire real numbers into whatever you use for monitoring:

  • Prometheus: a community package (socket.io-prometheus-v3) exposes /metrics with connections, bytes and event counts per namespace. Or write the small endpoint yourself from the reads above.
  • Admin UI: the official @socket.io/admin-ui is a dashboard for sockets, rooms, namespaces, and the ability to emit, join and disconnect manually.
JavaScript
import { instrument } from "@socket.io/admin-ui";
import { Server } from "socket.io";

const io = new Server(httpServer, {
  cors: { origin: ["https://admin.socket.io"], credentials: true },
});

instrument(io, {
  auth: {
    type: "basic",
    username: "admin",
    password: process.env.ADMIN_UI_PASSWORD_HASH, // bcrypt hash, never plain text
  },
  mode: process.env.NODE_ENV === "production" ? "production" : "development",
});

The dashboard, hosted at admin.socket.io (or self-hosted), connects to a special /admin namespace of your server. That namespace can disconnect users and emit arbitrary events, so protect it: always set auth outside local development, serve it over HTTPS, and restrict the CORS origin.

What to watch

Four dashboards worth having

Connections Current, total, and connect/disconnect rate.
Messages Events per second and top event names.
Latency Ack round-trip time and event loop lag.
Resources Memory, CPU and open file descriptors.

Alert on trends, not single spikes.

1 / 2

Alert candidates: connection count dropping suddenly (a deploy or network problem), a surge in connect_error or ping timeout disconnects, event loop lag above 100 ms (a handler is blocking), memory growing steadily (a leak), and the ratio of polling to WebSocket transports rising (a proxy that breaks upgrades).

Measure event loop lag with perf_hooks.monitorEventLoopDelay(). Because every connection is served by one thread, a slow synchronous handler delays everyone, and lag is the clearest signal of it.

Debugging checklist

When "it works locally but not in production":

  1. Open browser DevTools, Network, WS tab: is there a WebSocket with status 101, or only polling requests?
  2. Check the connect_error event and its err.message (and err.data for middleware errors).
  3. Turn on DEBUG=socket.io*,engine* for a short window on one server.
  4. Look at proxy logs: status 400/502/504 on /socket.io/ point at upgrade headers, timeouts or sticky sessions (deploying).
  5. Reproduce with a minimal client script outside the browser.
  6. Check CORS errors in the console: they mean the server's cors.origin does not list the page's origin (security hardening).
JavaScript
socket.on("connect_error", (err) => {
  console.log(err.message);      // e.g. "xhr poll error", "websocket error", or your middleware's message
  console.log(err.description);  // underlying transport error (client)
  console.log(err.data);         // extra data from a middleware error (server's err.data)
});

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you enable the built-in Socket.IO server logs?

    Socket.IO uses the debug package, which reads the DEBUG variable (localStorage.debug in browsers).
  2. 2. What does socket.onAny((event, ...args) => ...) do?

    It is a catch-all listener for one socket, handy for tracing without editing each handler.
  3. 3. Why protect the Admin UI namespace with auth?

    The /admin namespace exposes powerful operations, so require authentication and restrict origins.
  4. 4. What does high event loop lag tell you?

    One thread serves all sockets, so a long synchronous handler delays all events.

Summary

  • Use DEBUG=socket.io*,engine* for library logs and onAny / onAnyOutgoing for event traces.
  • Read connection, room and transport info from io.engine, io.of("/") and the adapter.
  • Expose counters and gauges (connections, events, lag) to Prometheus or a similar system.
  • Use the Admin UI only with authentication, HTTPS and a restricted origin.
  • Debug production issues starting with the browser's WS tab, connect_error and proxy logs.

Next: Security Hardening