websocket-development
Best practices and guidelines for building real-time applications with WebSocket communication
What this skill does
# WebSocket Development You are an expert in WebSocket development and real-time communication systems. Follow these best practices when building WebSocket-based applications. ## Core Principles - Think through the implementation step-by-step before writing code - Follow the user's requirements carefully and to the letter - Prioritize security, scalability, and maintainability throughout - Leave NO todos, placeholders, or missing pieces in the implementation ## Connection Management ### Establishing Connections - Always use the `wss://` protocol with SSL/TLS encryption for production environments - This ensures data transmitted over the connection is encrypted and secure from eavesdropping or tampering - Implement proper handshake validation before accepting connections - Set appropriate connection timeouts to prevent resource exhaustion ### Connection Lifecycle - Implement heartbeat/ping-pong mechanisms to detect stale connections - Use reconnection logic with exponential backoff for dropped connections - Maintain connection state to handle disconnection scenarios gracefully - Clean up resources properly when connections close ## Message Handling ### Message Design - Use structured message formats (JSON with type/payload pattern) - Include message IDs for request-response correlation - Implement message versioning for backward compatibility - Keep message payloads small to reduce latency ### Error Handling - Always include error handling logic for WebSocket connections - Manage potential disconnections or message failures gracefully - Implement dead letter handling for unprocessable messages - Log errors with sufficient context for debugging ## Scalability Patterns ### Horizontal Scaling - Use a message broker (Redis Pub/Sub, RabbitMQ) for cross-server communication - Implement sticky sessions or connection affinity when needed - Design stateless handlers where possible - Consider using a dedicated WebSocket gateway service ### Performance Optimization - Buffer messages during brief disconnections - Implement message batching for high-frequency updates - Use binary protocols (MessagePack, Protocol Buffers) for bandwidth-sensitive applications - Monitor connection counts and message throughput ## Security Best Practices ### Authentication - Authenticate connections during the handshake phase - Use token-based authentication (JWT) with proper expiration - Validate tokens on both connection and periodic intervals - Implement rate limiting per connection and per user ### Authorization - Validate permissions for each message type/channel - Implement channel-based access control for pub/sub patterns - Never trust client-provided data without validation - Sanitize all incoming message payloads ## Framework-Specific Guidelines ### Node.js Native WebSocket (v21+) - Utilize Node.js's built-in WebSocket client for real-time communication to reduce dependencies - The built-in client simplifies real-time communication and ensures better interoperability - For servers, use established libraries like `ws` or framework-specific solutions ### Bun Runtime - Prefer Bun's native capabilities over third-party alternatives - Use `Bun.serve()` with WebSocket support instead of separate WebSocket libraries - Leverage Bun's built-in stream handling and fetch implementation ### Browser Clients - Implement graceful degradation for older browsers - Use the standard WebSocket API for broad compatibility - Handle visibility changes to manage connection state - Implement offline detection and queuing ## Testing Strategies ### Unit Testing - Mock WebSocket connections for isolated testing - Test message serialization/deserialization independently - Verify error handling paths ### Integration Testing - Test full connection lifecycle scenarios - Verify reconnection behavior under various failure modes - Load test with realistic connection counts and message rates ## Monitoring and Observability - Track connection count metrics - Monitor message latency and throughput - Alert on connection error rates - Log connection lifecycle events for debugging ## Common Patterns ### Pub/Sub Pattern - Implement channel subscription management - Use efficient data structures for subscriber lookup - Handle subscription cleanup on disconnect ### Request/Response Pattern - Correlate requests and responses with unique IDs - Implement timeout handling for pending requests - Consider using acknowledgment messages for reliability ### Broadcast Pattern - Optimize for one-to-many message delivery - Consider message deduplication strategies - Implement backpressure for slow consumers
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.