Saga Pattern
Skill Profile
(Select at least one profile to enable specific modules)
Overview
The Saga pattern manages distributed transactions by coordinating a series of local transactions across microservices with compensating actions for rollback. It avoids global locks and is a common alternative to 2PC (Two-Phase Commit) in microservice architectures, trading strong consistency for availability and scalability.
Why This Matters
Saga pattern enables building distributed systems that:
- Avoid Distributed Locks: No global locks blocking services
- Improve Availability: Services remain available during saga execution
- Handle Failures Gracefully: Compensating transactions undo partial work
- Scale Horizontally: No single coordinator bottleneck
- Provide Audit Trail: All saga steps are tracked and logged
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
Skill Composition
- Depends on: None
- Compatible with: None
- Conflicts with: None
- Related Skills: None
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
- Message broker provides at-least-once delivery
- Services can handle eventual consistency
- Compensating transactions are idempotent
- Network partitions are transient
- State persistence is reliable
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: saga-pattern3description: Use when working with the Saga pattern manages distributed transactions by coordinating a series4---56# Saga Pattern78## 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## Overview17The Saga pattern manages distributed transactions by coordinating a series of local transactions across microservices with compensating actions for rollback. It avoids global locks and is a common alternative to 2PC (Two-Phase Commit) in microservice architectures, trading strong consistency for availability and scalability.1819## Why This Matters20Saga pattern enables building distributed systems that:2122- **Avoid Distributed Locks**: No global locks blocking services23- **Improve Availability**: Services remain available during saga execution24- **Handle Failures Gracefully**: Compensating transactions undo partial work25- **Scale Horizontally**: No single coordinator bottleneck26- **Provide Audit Trail**: All saga steps are tracked and logged2728## Core Concepts & Rules2930### 1. Core Principles31- Follow established patterns and conventions32- Maintain consistency across codebase33- Document decisions and trade-offs3435### 2. Implementation Guidelines36- Start with the simplest viable solution37- Iterate based on feedback and requirements38- Test thoroughly before deployment394041## Inputs / Outputs / Contracts42#4344## Skill Composition45* **Depends on**: None46* **Compatible with**: None47* **Conflicts with**: None48* **Related Skills**: None4950## Quick Start / Implementation Example51521. Review requirements and constraints532. Set up development environment543. Implement core functionality following patterns554. Write tests for critical paths565. Run tests and fix issues576. Document any deviations or decisions5859```python60# Example implementation following best practices61def example_function():62 # Your implementation here63 pass64```656667## Assumptions68- Message broker provides at-least-once delivery69- Services can handle eventual consistency70- Compensating transactions are idempotent71- Network partitions are transient72- State persistence is reliable7374## Compatibility & Prerequisites7576* **Supported Versions**:77 - Python 3.8+78 - Node.js 16+79 - Modern browsers (Chrome, Firefox, Safari, Edge)80* **Required AI Tools**:81 - Code editor (VS Code recommended)82 - Testing framework appropriate for language83 - Version control (Git)84* **Dependencies**:85 - Language-specific package manager86 - Build tools87 - Testing libraries88* **Environment Setup**:89 - `.env.example` keys: `API_KEY`, `DATABASE_URL` (no values)909192## Test Scenario Matrix (QA Strategy)9394| Type | Focus Area | Required Scenarios / Mocks |95| :--- | :--- | :--- |96| **Unit** | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |97| **Integration** | DB / API | All external API calls or database connections must be mocked during unit tests |98| **E2E** | User Journey | Critical user flows to test |99| **Performance** | Latency / Load | Benchmark requirements |100| **Security** | Vuln / Auth | SAST/DAST or dependency audit |101| **Frontend** | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |102103104## Technical Guardrails & Security Threat Model105106### 1. Security & Privacy (Threat Model)107* **Top Threats**: Injection attacks, authentication bypass, data exposure108- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII109- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager110- [ ] **Authorization**: Validate user permissions before state changes111112### 2. Performance & Resources113- [ ] **Execution Efficiency**: Consider time complexity for algorithms114- [ ] **Memory Management**: Use streams/pagination for large data115- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks116117### 3. Architecture & Scalability118- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection119- [ ] **Modularity**: Decouple logic from UI/Frameworks120121### 4. Observability & Reliability122- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`123- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`124- [ ] **Error Handling**: Standardized error codes, no bare except125- [ ] **Observability Artifacts**:126 - **Log Fields**: timestamp, level, message, request_id127 - **Metrics**: request_count, error_count, response_time128 - **Dashboards/Alerts**: High Error Rate > 5%129130131## Agent Directives & Error Recovery132*(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)*133134- **Thinking Process**: Analyze root cause before fixing. Do not brute-force.135- **Fallback Strategy**: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.136- **Self-Review**: Check against Guardrails & Anti-patterns before finalizing.137- **Output Constraints**: Output ONLY the modified code block. Do not explain unless asked.138139140## Definition of Done (DoD) Checklist141142- [ ] Tests passed + coverage met143- [ ] Lint/Typecheck passed144- [ ] Logging/Metrics/Trace implemented145- [ ] Security checks passed146- [ ] Documentation/Changelog updated147- [ ] Accessibility/Performance requirements met (if frontend)148149150## Anti-patterns / Pitfalls151152* ⛔ **Don't**: Log PII, catch-all exception, N+1 queries153* ⚠️ **Watch out for**: Common symptoms and quick fixes154* 💡 **Instead**: Use proper error handling, pagination, and logging155156157## Reference Links & Examples158159* Internal documentation and examples160* Official documentation and best practices161* Community resources and discussions162163164## Versioning & Changelog165166* **Version**: 1.0.0167* **Changelog**:168 - 2026-02-22: Initial version with complete template structure169170---171> Converted and distributed by [TomeVault](https://tomevault.io/claim/amnadtaowsoam) — claim your Tome and manage your conversions.172<!-- tomevault:4.0:skill_md:2026-04-13 -->