Designs real-time systems with WebSocket, SignalR, and Socket.io. Covers protocol selection, message contracts, server implementation, horizontal scaling, and reconnection strategies.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
| Besoin | Solution recommandée | Raison |
|---|---|---|
| Bidirectionnel, faible latence | WebSocket natif / SignalR / Socket.io | Full-duplex sur une seule connexion TCP |
| Serveur → client uniquement | SSE (Server-Sent Events) | Plus simple, traversée proxy meilleure |
| Polling toléré, contraintes infra | Long polling | Fonctionne partout sans port spécial |
| < 1 000 connexions simultanées | WebSocket natif | Pas besoin de lib externe |
| Stack .NET | SignalR | Négociation automatique + fallback intégré |
| Stack Node.js | Socket.io | Rooms, namespaces, reconnexion built-in |
Règle décisive : si un proxy ou load balancer ne supporte pas l'upgrade HTTP→WS, préfère SSE ou assure-toi que le backplane est configuré avant de commencer.
Définis un contrat JSON structuré avant d'écrire une ligne de code.
// Enveloppe standard
{
"type": "CHAT_MESSAGE", // action discriminante
"channel": "room:42", // scope / destinataire
"payload": { "text": "..." }, // données métier
"correlationId": "uuid-v4", // pour ack / replay
"ts": 1719230400000 // timestamp epoch ms
}
Types d'événements minimum à définir :
SUBSCRIBE / UNSUBSCRIBE — gestion des canauxACK — acquittement d'un message critiqueERROR — retour d'erreur structuré { code, message }PING / PONG — heartbeat applicatif// Program.cs
builder.Services.AddSignalR(o => {
o.MaximumReceiveMessageSize = 32 * 1024; // 32 KB max
o.EnableDetailedErrors = app.Environment.IsDevelopment();
});
app.MapHub<ChatHub>("/hubs/chat");
// ChatHub.cs
[Authorize]
public class ChatHub : Hub
{
public async Task SendMessage(string channel, string text)
{
// Vérifier l'autorisation sur le canal
if (!await _authService.CanWriteAsync(Context.UserIdentifier, channel))
throw new HubException("Forbidden");
await Clients.Group(channel).SendAsync("ReceiveMessage", new {
From = Context.UserIdentifier,
Text = text,
Ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
});
}
public override async Task OnConnectedAsync()
{
// Rejoindre les canaux de l'utilisateur dès la connexion
var channels = await _channelService.GetUserChannelsAsync(Context.UserIdentifier);
foreach (var ch in channels)
await Groups.AddToGroupAsync(Context.ConnectionId, ch);
await base.OnConnectedAsync();
}
}
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
const io = new Server(httpServer, {
cors: { origin: process.env.ALLOWED_ORIGIN },
maxHttpBufferSize: 32 * 1024, // 32 KB
pingTimeout: 20_000,
pingInterval: 10_000,
});
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
const user = await verifyJwt(token); // lance une erreur si invalide
socket.data.user = user;
next();
});
io.on("connection", async (socket) => {
const { userId } = socket.data.user;
const channels = await getChannels(userId);
socket.join(channels);
socket.on("CHAT_MESSAGE", async ({ channel, text }) => {
if (!channels.includes(channel)) return socket.emit("ERROR", { code: 403 });
io.to(channel).emit("CHAT_MESSAGE", { from: userId, text, ts: Date.now() });
});
});
// Reconnexion avec exponential backoff + jitter (vanilla WS)
function createWebSocketClient(url: string) {
let ws: WebSocket;
let attempt = 0;
const MAX_DELAY = 30_000;
function connect() {
ws = new WebSocket(url);
ws.onopen = () => {
attempt = 0;
// Rejouer les messages en attente
drainQueue();
};
ws.onmessage = (e) => handleMessage(JSON.parse(e.data));
ws.onclose = (e) => {
if (e.code === 1000) return; // fermeture propre
const delay = Math.min(1_000 * 2 ** attempt + Math.random() * 500, MAX_DELAY);
attempt++;
setTimeout(connect, delay);
};
}
connect();
return { send: (msg: object) => ws.send(JSON.stringify(msg)) };
}
SignalR client : utilise withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) — les intervalles sont en ms.
builder.Services.AddSignalR()
.AddStackExchangeRedis("redis:6379,abortConnect=false", o => {
o.Configuration.ChannelPrefix = RedisChannel.Literal("myapp");
});
import { createClient } from "redis";
import { createAdapter } from "@socket.io/redis-adapter";
const pub = createClient({ url: "redis://redis:6379" });
const sub = pub.duplicate();
await Promise.all([pub.connect(), sub.connect()]);
io.adapter(createAdapter(pub, sub));
Points clés :
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";Authorization: Bearer header lors du handshake (query string acceptable mais éviter en prod — visible dans les logs).Métriques essentielles à exposer (Prometheus / OpenTelemetry) :
| Métrique | Seuil d'alerte typique |
|---|---|
ws_connections_active | > 80 % de la capacité max |
ws_messages_per_second | pic anormal × 3 |
ws_reconnect_rate | > 5 % des clients/min |
ws_message_latency_p99 | > 500 ms |
ws_errors_total | toute augmentation soudaine |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/claude-skills-collection:dev-websocket-designerfrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collection348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests".Other plugins' skills for the same job