Websocket Patterns
Skill Profile
(Select at least one profile to enable specific modules)
Overview
WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It enables real-time, event-driven communication between clients and servers, making it ideal for applications requiring instant updates such as chat applications, live dashboards, and collaborative tools.
Why This Matters
Core Concepts & Rules
1. Core Principles
- Follow established patterns and conventions
- Maintain consistency across codebase
- Document decisions and trade-offs
2. Implementation Guidelines
- Start with the simplest viable solution
- Iterate based on feedback and requirements
- Test thoroughly before deployment
Inputs / Outputs / Contracts
- Inputs:
- <e.g., env vars, request payload, file paths, schema>
- Entry Conditions:
- <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
- Outputs:
- <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
- Artifacts Required (Deliverables):
- <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
- Acceptance Evidence:
- <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
- Success Criteria:
- <e.g., p95 < 300ms, coverage ≥ 80%>
Skill Composition
- Depends on: api-design, nodejs-api
- Compatible with: react, vue
- Conflicts with: server-sent-events
- Related Skills: server-sent-events
Quick Start / Implementation Example
- Review requirements and constraints
- Set up development environment
- Implement core functionality following patterns
- Write tests for critical paths
- Run tests and fix issues
- Document any deviations or decisions
# Example implementation following best practices
def example_function():
# Your implementation here
pass
Assumptions / Constraints / Non-goals
- Assumptions:
- Development environment is properly configured
- Required dependencies are available
- Team has basic understanding of domain
- Constraints:
- Must follow existing codebase conventions
- Time and resource limitations
- Compatibility requirements
- Non-goals:
- This skill does not cover edge cases outside scope
- Not a replacement for formal training
Compatibility & Prerequisites
- Supported Versions:
- Python 3.8+
- Node.js 16+
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Required AI Tools:
- Code editor (VS Code recommended)
- Testing framework appropriate for language
- Version control (Git)
- Dependencies:
- Language-specific package manager
- Build tools
- Testing libraries
- Environment Setup:
.env.example keys: API_KEY, DATABASE_URL (no values)
Test Scenario Matrix (QA Strategy)
| Type |
Focus Area |
Required Scenarios / Mocks |
| Unit |
Core Logic |
Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |
| Integration |
DB / API |
All external API calls or database connections must be mocked during unit tests |
| E2E |
User Journey |
Critical user flows to test |
| Performance |
Latency / Load |
Benchmark requirements |
| Security |
Vuln / Auth |
SAST/DAST or dependency audit |
| Frontend |
UX / A11y |
Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives & Error Recovery
(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)
- Thinking Process: Analyze root cause before fixing. Do not brute-force.
- Fallback Strategy: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
- Self-Review: Check against Guardrails & Anti-patterns before finalizing.
- Output Constraints: Output ONLY the modified code block. Do not explain unless asked.
Definition of Done (DoD) Checklist
Anti-patterns / Pitfalls
- ⛔ Don't: Log PII, catch-all exception, N+1 queries
- ⚠️ Watch out for: Common symptoms and quick fixes
- 💡 Instead: Use proper error handling, pagination, and logging
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: websocket-patterns3description: WebSocket is a communication protocol that provides full-duplex communication Use when this capability is needed.4---56# Websocket Patterns78## Skill Profile9*(Select at least one profile to enable specific modules)*10- [ ] **DevOps**11- [x] **Backend**12- [ ] **Frontend**13- [ ] **AI-RAG**14- [ ] **Security Critical**1516## Overview17WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It enables real-time, event-driven communication between clients and servers, making it ideal for applications requiring instant updates such as chat applications, live dashboards, and collaborative tools.1819## Why This Matters20- **<Benefit>**: <short explanation>21- **<Benefit>**: <short explanation>22- **<Benefit>**: <short explanation>2324## Core Concepts & Rules2526### 1. Core Principles27- Follow established patterns and conventions28- Maintain consistency across codebase29- Document decisions and trade-offs3031### 2. Implementation Guidelines32- Start with the simplest viable solution33- Iterate based on feedback and requirements34- Test thoroughly before deployment353637## Inputs / Outputs / Contracts38* **Inputs**:39 - <e.g., env vars, request payload, file paths, schema>40* **Entry Conditions**:41 - <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>42* **Outputs**:43 - <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>44* **Artifacts Required (Deliverables)**:45 - <e.g., Code Diff, Unit Tests, Migration Script, API Docs>46* **Acceptance Evidence**:47 - <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>48* **Success Criteria**:49 - <e.g., p95 < 300ms, coverage ≥ 80%>5051## Skill Composition52* **Depends on**: [api-design](..\..\01-foundations\api-design/SKILL.md), [nodejs-api](..\nodejs-api/SKILL.md)53* **Compatible with**: [react](..\..\02-frontend\error-boundaries-react/SKILL.md), vue54* **Conflicts with**: [server-sent-events](..\server-sent-events/SKILL.md)55* **Related Skills**: [server-sent-events](..\server-sent-events/SKILL.md)5657## Quick Start / Implementation Example58591. Review requirements and constraints602. Set up development environment613. Implement core functionality following patterns624. Write tests for critical paths635. Run tests and fix issues646. Document any deviations or decisions6566```python67# Example implementation following best practices68def example_function():69 # Your implementation here70 pass71```727374## Assumptions / Constraints / Non-goals7576* **Assumptions**:77 - Development environment is properly configured78 - Required dependencies are available79 - Team has basic understanding of domain80* **Constraints**:81 - Must follow existing codebase conventions82 - Time and resource limitations83 - Compatibility requirements84* **Non-goals**:85 - This skill does not cover edge cases outside scope86 - Not a replacement for formal training878889## Compatibility & Prerequisites9091* **Supported Versions**:92 - Python 3.8+93 - Node.js 16+94 - Modern browsers (Chrome, Firefox, Safari, Edge)95* **Required AI Tools**:96 - Code editor (VS Code recommended)97 - Testing framework appropriate for language98 - Version control (Git)99* **Dependencies**:100 - Language-specific package manager101 - Build tools102 - Testing libraries103* **Environment Setup**:104 - `.env.example` keys: `API_KEY`, `DATABASE_URL` (no values)105106107## Test Scenario Matrix (QA Strategy)108109| Type | Focus Area | Required Scenarios / Mocks |110| :--- | :--- | :--- |111| **Unit** | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |112| **Integration** | DB / API | All external API calls or database connections must be mocked during unit tests |113| **E2E** | User Journey | Critical user flows to test |114| **Performance** | Latency / Load | Benchmark requirements |115| **Security** | Vuln / Auth | SAST/DAST or dependency audit |116| **Frontend** | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |117118119## Technical Guardrails & Security Threat Model120121### 1. Security & Privacy (Threat Model)122* **Top Threats**: Injection attacks, authentication bypass, data exposure123- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII124- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager125- [ ] **Authorization**: Validate user permissions before state changes126127### 2. Performance & Resources128- [ ] **Execution Efficiency**: Consider time complexity for algorithms129- [ ] **Memory Management**: Use streams/pagination for large data130- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks131132### 3. Architecture & Scalability133- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection134- [ ] **Modularity**: Decouple logic from UI/Frameworks135136### 4. Observability & Reliability137- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`138- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`139- [ ] **Error Handling**: Standardized error codes, no bare except140- [ ] **Observability Artifacts**:141 - **Log Fields**: timestamp, level, message, request_id142 - **Metrics**: request_count, error_count, response_time143 - **Dashboards/Alerts**: High Error Rate > 5%144145146## Agent Directives & Error Recovery147*(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)*148149- **Thinking Process**: Analyze root cause before fixing. Do not brute-force.150- **Fallback Strategy**: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.151- **Self-Review**: Check against Guardrails & Anti-patterns before finalizing.152- **Output Constraints**: Output ONLY the modified code block. Do not explain unless asked.153154155## Definition of Done (DoD) Checklist156157- [ ] Tests passed + coverage met158- [ ] Lint/Typecheck passed159- [ ] Logging/Metrics/Trace implemented160- [ ] Security checks passed161- [ ] Documentation/Changelog updated162- [ ] Accessibility/Performance requirements met (if frontend)163164165## Anti-patterns / Pitfalls166167* ⛔ **Don't**: Log PII, catch-all exception, N+1 queries168* ⚠️ **Watch out for**: Common symptoms and quick fixes169* 💡 **Instead**: Use proper error handling, pagination, and logging170171172## Reference Links & Examples173174* Internal documentation and examples175* Official documentation and best practices176* Community resources and discussions177178179## Versioning & Changelog180181* **Version**: 1.0.0182* **Changelog**:183 - 2026-02-22: Initial version with complete template structure184185---186> Converted and distributed by [TomeVault](https://tomevault.io/claim/amnadtaowsoam) — claim your Tome and manage your conversions.187<!-- tomevault:4.0:skill_md:2026-04-13 -->