
Design Doc Mermaid
- 30.5k installs
- 140 repo stars
- Updated December 29, 2025
- spillwavesolutions/design-doc-mermaid
design-doc-mermaid is a Claude Code skill that converts plain-text specs or source code into professional Mermaid diagrams for activity, sequence, deployment, and architecture documentation.
About
design-doc-mermaid is a hierarchical Mermaid diagram and documentation skill. It generates activity, deployment, sequence, and architecture diagrams from natural-language descriptions or existing code, with on-demand guide loading and Python utilities for diagram extraction.
- Generates activity, sequence, deployment, class, and architecture diagrams from text or code
- Hierarchical on-demand guide loading for specialized diagram types
- Unicode semantic symbols and high-contrast styling support
Design Doc Mermaid by the numbers
- 30,532 all-time installs (skills.sh)
- +2,677 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #18 of 1,879 Documentation skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
What design-doc-mermaid says it does
Create Mermaid diagrams (activity, deployment, sequence, architecture) from text descriptions or source code
npx skills add https://github.com/spillwavesolutions/design-doc-mermaid --skill design-doc-mermaidAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 30.5k |
|---|---|
| repo stars | ★ 140 |
| Security audit | 2 / 3 scanners passed |
| Last updated | December 29, 2025 |
| Repository | spillwavesolutions/design-doc-mermaid ↗ |
How do you generate Mermaid architecture diagrams from code?
Instantly turn plain text specs, architecture ideas, or existing code into clean, professional Mermaid diagrams for activity flows, sequences, deployments, and system architecture.
Who is it for?
Developers documenting system flows, deployments, and service interactions who want diagrams generated from specs or code rather than manual drawing.
Skip if: Pixel-perfect UI mockups or teams standardized exclusively on non-Mermaid tools like PlantUML without conversion needs.
When should I use this skill?
User asks to create a diagram, generate mermaid, document architecture, convert code to diagram, or produce a design doc with flows.
What you get
Mermaid diagram source files, architecture documentation, and optional rendered diagram images
- Mermaid diagram files
- architecture design docs
- diagram images
By the numbers
- Supports four Mermaid diagram families: activity, deployment, sequence, architecture
Files
Mermaid Architect - Hierarchical Diagram and Documentation Skill
Mermaid diagram and documentation system with specialized guides and code-to-diagram capabilities.
Table of Contents
- Decision Tree
- Available Guides and Resources
- Usage Patterns
- Resilient Workflow
- Unicode Semantic Symbols
- Python Utilities
- Decision Tree Examples
- High-Contrast Styling
- File Organization
- Workflow Summary
- When to Use What
- Best Practices
- Learning Path
Decision Tree
How this skill works:
1. User makes a request → Skill analyzes intent 2. Skill determines diagram/document type → Loads appropriate guide(s) 3. AI reads specialized guide → Generates diagram/document using templates 4. Result delivered → With validation and export options
User Intent Analysis:
flowchart TD
Start([User Request]) --> Analyze{Analyze Intent}
Analyze -->|"workflow, process, business logic"| Activity[Load Activity Diagram Guide<br/>references/guides/diagrams/activity-diagrams.md]
Analyze -->|"infrastructure, deployment, cloud"| Deploy[Load Deployment Diagram Guide<br/>references/guides/diagrams/deployment-diagrams.md]
Analyze -->|"system architecture, components"| Arch[Load Architecture Guide<br/>references/guides/diagrams/architecture-diagrams.md]
Analyze -->|"API flow, interactions"| Sequence[Load Sequence Diagram Guide<br/>references/guides/diagrams/sequence-diagrams.md]
Analyze -->|"code to diagram"| CodeToDiag[Load Code-to-Diagram Guide<br/>references/guides/code-to-diagram/ + examples/]
Analyze -->|"design document, full docs"| DesignDoc[Load Design Document Template<br/>assets/*-design-template.md]
Analyze -->|"unicode symbols, icons"| Unicode[Load Unicode Symbols Guide<br/>references/guides/unicode-symbols/guide.md]
Analyze -->|"extract, validate, convert"| Scripts[Use Python Scripts<br/>scripts/extract_mermaid.py<br/>scripts/mermaid_to_image.py]
Activity --> Generate[Generate Diagram]
Deploy --> Generate
Arch --> Generate
Sequence --> Generate
CodeToDiag --> Generate
DesignDoc --> Generate
Unicode --> Generate
Scripts --> Execute[Execute Script]
Generate --> Validate{Validate?}
Validate -->|Yes| RunValidation[Run mmdc validation]
Validate -->|No| Output
RunValidation --> Output[Output Result]
Execute --> Output
classDef decision fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef guide fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef action fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
class Analyze,Validate decision
class Activity,Deploy,Arch,Sequence,CodeToDiag,DesignDoc,Unicode,Scripts guide
class Generate,Execute,RunValidation,Output actionAvailable Guides and Resources
Diagram Type Guides (references/guides/diagrams/)
| Guide | Full Path | Load When User Wants | Examples |
|---|---|---|---|
| Activity Diagrams | references/guides/diagrams/activity-diagrams.md | Workflows, processes, business logic, user flows, decision trees | "Show checkout flow", "Document ETL pipeline", "Create approval workflow" |
| Deployment Diagrams | references/guides/diagrams/deployment-diagrams.md | Infrastructure, cloud architecture, K8s, serverless, network topology | "Show AWS architecture", "Document GCP deployment", "Create K8s diagram" |
| Architecture Diagrams | references/guides/diagrams/architecture-diagrams.md | System architecture, component design, high-level structure | "Show system components", "Document microservices", "Architecture overview" |
| Sequence Diagrams | references/guides/diagrams/sequence-diagrams.md | API interactions, service communication, request/response flows | "Show API call sequence", "Document auth flow", "Service interactions" |
Code-to-Diagram Guide & Examples
| Resource | Full Path | What It Provides |
|---|---|---|
| Master Guide | references/guides/code-to-diagram/README.md | Complete workflow for analyzing any codebase and extracting diagrams |
| Spring Boot | examples/spring-boot/README.md | Controller→Service→Repository architecture, deployment config, sequence from methods, activity from business logic |
| FastAPI | examples/fastapi/README.md | Python async patterns, Pydantic models, dependency injection, cloud deployment |
| React | examples/react/README.md | Component hierarchy, state management, data flow, build pipeline |
| Python ETL | examples/python-etl/README.md | Data pipeline, transformation steps, error handling, scheduling |
| Node/Express | examples/node-webapp/README.md | Middleware chain, route handlers, async patterns, deployment |
| Java Web App | examples/java-webapp/README.md | Traditional MVC, servlet containers, WAR deployment |
Design Document Templates
| Template | Full Path | Use For | Load When |
|---|---|---|---|
| Architecture Design | assets/architecture-design-template.md | System-wide architecture | "Create architecture doc", "Document system design" |
| API Design | assets/api-design-template.md | API specifications | "API design doc", "Document REST API" |
| Feature Design | assets/feature-design-template.md | Feature planning | "Feature design", "Plan new feature" |
| Database Design | assets/database-design-template.md | Database schema | "Database design", "Document schema" |
| System Design | assets/system-design-template.md | Complete system | "System design doc", "Full system documentation" |
Unicode Symbols Guide
Full Path: references/guides/unicode-symbols/guide.md
Load when user mentions: "unicode symbols", "emoji in diagrams", "semantic icons", "add symbols"
Quick Reference:
- 📦 Infrastructure: ☁️ 🌐 🔌 📡 🗄️
- ⚙️ Compute: ⚙️ ⚡ 🔄 ♻️ 🚀 💨
- 💾 Data: 💾 📦 📊 📈 🗃️ 🧊
- 📨 Messaging: 📨 📬 📤 📥 🐰 📢
- 🔐 Security: 🔐 🔑 🛡️ 🚪 👤 🎫
- 📝 Monitoring: 📝 📊 🚨 ⚠️ ✅ ❌
Python Scripts (scripts/)
| Script | Use For | Load When |
|---|---|---|
extract_mermaid.py | Extract diagrams from Markdown, validate syntax, replace with images | "extract diagrams", "validate mermaid", "find all diagrams" |
mermaid_to_image.py | Convert .mmd to PNG/SVG, batch conversion, custom themes | "convert to image", "render diagram", "create PNG" |
resilient_diagram.py | Full workflow: save .mmd, generate image, validate, error recovery | "generate diagram", "create diagram with validation", "resilient diagram" |
Usage Patterns
Common request patterns and guide selection. See When to Use What for complete mapping.
| Pattern | Example Request | Guides to Load |
|---|---|---|
| Single Diagram | "Create activity diagram for login flow" | Diagram type guide + Unicode symbols |
| Code-to-Diagram | "Generate deployment from application.yml" | Framework example + Deployment guide |
| Design Document | "Create API design document" | Template from assets/ + Relevant diagram guides |
| Extract/Validate | "Extract diagrams from design.md" | Use scripts/extract_mermaid.py |
| Batch Convert | "Convert all .mmd to PNG" | Use scripts/mermaid_to_image.py |
Resilient Workflow
CRITICAL: This is the recommended approach for ALL diagram generation. It ensures validation, error recovery, and consistent file organization.
Full Guide: references/guides/resilient-workflow.md
Workflow Overview
flowchart LR
A[1. Identify Type] --> B[2. Save .mmd + Image]
B --> C{3. Valid?}
C -->|Yes| D[4. Add to Markdown]
C -->|No| E[5. Error Recovery]
E --> F{Fix Found?}
F -->|Yes| A
F -->|No| G[Search External]
G --> A
classDef step fill:#90EE90,stroke:#333,color:darkgreen
classDef decision fill:#FFD700,stroke:#333,color:black
class A,B,D,E,G step
class C,F decisionKey Principle
NEVER add a diagram to markdown until it passes validation. This prevents broken diagrams in documentation.
Using the Script (Recommended)
# Generate with full error recovery
python scripts/resilient_diagram.py \
--code "flowchart TD; A-->B" \
--markdown-file design_doc \
--diagram-num 1 \
--title "process_flow" \
--format png \
--jsonOutput: Both .mmd and .png files in ./diagrams/ directory.
File Naming Convention
./diagrams/<markdown_file>_<num>_<type>_<title>.mmd
./diagrams/<markdown_file>_<num>_<type>_<title>.pngExample: ./diagrams/api_design_01_sequence_auth_flow.png
Error Recovery Priority
When validation fails, the workflow automatically:
1. Check troubleshooting guide - references/guides/troubleshooting.md (28 documented errors) 2. Search with perplexity - perplexity_ask MCP for syntax questions 3. Search with brave - brave_web_search MCP for recent solutions 4. Ask gemini - gemini skill for alternative perspective 5. General search - WebSearch tool as fallback
Manual Fallback Steps
If the script is unavailable:
1. Identify diagram type from first line (flowchart, sequence, etc.) 2. Load reference guide from references/guides/diagrams/ 3. Save to ./diagrams/<markdown_file>_<num>_<type>_<title>.mmd 4. Validate: mmdc -i file.mmd -o file.png -b transparent 5. On error: Search references/guides/troubleshooting.md for matching error 6. If not found: Use search tools in priority order above 7. Add reference: 
Pattern 6: Resilient Diagram Generation
User: "Create a sequence diagram and add it to the design doc"
Skill Actions: 1. Identify intent: diagram generation + markdown integration 2. Load workflow guide: references/guides/resilient-workflow.md 3. Identify diagram type: sequence 4. Load diagram guide: references/guides/diagrams/sequence-diagrams.md 5. Generate Mermaid code using templates 6. Execute resilient workflow:
python scripts/resilient_diagram.py \
--code "[generated code]" \
--markdown-file design_doc \
--diagram-num 1 \
--title "api_sequence" \
--json7. If validation fails → Apply troubleshooting fix → Retry 8. On success → Add  to markdown
Unicode Semantic Symbols
Always use Unicode symbols to enhance diagram clarity. Common patterns:
Infrastructure & Deployment
graph TB
Client[👤 User] --> LB[🌐 Load Balancer]
LB --> App1[⚙️ App Server 1]
LB --> App2[⚙️ App Server 2]
App1 --> DB[(💾 Database)]
App1 --> Cache[(⚡ Redis)]Activity Flow with States
flowchart TD
Start([🚀 Start]) --> Process[⚙️ Process Data]
Process --> Check{✓ Valid?}
Check -->|Yes| Save[💾 Save]
Check -->|No| Error[❌ Error]
Save --> Complete([✅ Complete])Microservices Architecture
graph TB
API[🌐 API Gateway] --> Auth[🔐 Auth Service]
API --> Orders[📋 Order Service]
Orders --> Queue[📬 Message Queue]
Queue --> Worker[⚙️ Background Worker]
Worker --> Storage[📦 Object Storage]For complete symbol reference, load: references/guides/unicode-symbols/guide.md
Python Utilities
Extract Mermaid Diagrams
# List all diagrams
python scripts/extract_mermaid.py document.md --list-only
# Extract to separate files
python scripts/extract_mermaid.py document.md --output-dir diagrams/
# Validate all diagrams
python scripts/extract_mermaid.py document.md --validate
# Replace with image references (for Confluence upload)
python scripts/extract_mermaid.py document.md --replace-with-images \
--image-format png --output-markdown output.mdConvert to Images
# Single conversion
python scripts/mermaid_to_image.py diagram.mmd output.png
# With custom settings
python scripts/mermaid_to_image.py diagram.mmd output.svg \
--theme dark --background white --width 1200
# Batch convert directory
python scripts/mermaid_to_image.py diagrams/ output/ --format png --recursive
# From stdin
echo "graph TD; A-->B" | python scripts/mermaid_to_image.py - output.pngDecision Tree Examples
Example 1: User Asks for Workflow Diagram
Input: "Show the checkout process workflow"
Skill Decision Path:
1. Analyze: workflow, process → ACTIVITY DIAGRAM
2. Load guide: guides/diagrams/activity-diagrams.md
3. Find pattern: E-commerce checkout (template exists in guide)
4. Generate using template + Unicode symbols
5. Output activity diagram with decision pointsOutput: Complete activity diagram with Unicode symbols for cart, payment, order states.
Example 2: User Provides Spring Boot Code
Input: "Here's my Spring Boot controller, create diagrams"
Skill Decision Path:
1. Analyze: Spring Boot, code provided → CODE-TO-DIAGRAM + SPRING BOOT
2. Load guides:
- examples/spring-boot/README.md
- guides/diagrams/architecture-diagrams.md (for structure)
- guides/diagrams/sequence-diagrams.md (for method calls)
- guides/diagrams/activity-diagrams.md (for business logic)
3. Generate multiple diagrams:
a. Architecture diagram from @RestController/@Service/@Repository annotations
b. Sequence diagram from method call chain
c. Activity diagram from business logic flow
4. Output all diagrams with explanationsOutput: 3-4 diagrams showing different views of the Spring Boot application.
Example 3: User Wants Infrastructure Documentation
Input: "Document my GCP Cloud Run deployment with AlloyDB"
Skill Decision Path:
1. Analyze: infrastructure, GCP, Cloud Run → DEPLOYMENT DIAGRAM
2. Load guides:
- guides/diagrams/deployment-diagrams.md
- examples/spring-boot/ or examples/fastapi/ (if code provided)
3. Check for IaC files (Pulumi, Terraform, docker-compose)
4. Generate deployment diagram with:
- Cloud Run services with specs
- VPC connector
- AlloyDB cluster
- Security (IAM, Secret Manager)
- Monitoring
5. Apply Unicode symbols for clarity
6. Output with resource specificationsOutput: Complete GCP deployment diagram with all resources labeled.
High-Contrast Styling
ALL diagrams MUST use high-contrast colors:
graph TB
classDef primary fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef secondary fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef error fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:black
%% Every classDef MUST have color: propertyRules:
- Light background → Dark text color
- Dark background → Light text color
- Always specify
color:in everyclassDef
File Organization
design-doc-mermaid/
├── SKILL.md # This file - Main orchestrator
├── README.md # User documentation
├── CLAUDE.md # Claude Code instructions
│
├── references/ # Reference materials
│ ├── mermaid-diagram-guide.md # Legacy general guide
│ └── guides/ # Specialized guides (load on-demand)
│ ├── diagrams/
│ │ ├── activity-diagrams.md # Workflows, processes
│ │ ├── deployment-diagrams.md # Infrastructure, cloud
│ │ ├── architecture-diagrams.md # System architecture
│ │ └── sequence-diagrams.md # API interactions
│ ├── code-to-diagram/
│ │ └── README.md # Master guide for code analysis
│ ├── unicode-symbols/
│ │ └── guide.md # Complete symbol reference
│ └── troubleshooting.md # Common syntax errors & fixes
│
├── assets/ # Design document templates
│ ├── architecture-design-template.md
│ ├── api-design-template.md
│ ├── feature-design-template.md
│ ├── database-design-template.md
│ └── system-design-template.md
│
├── scripts/ # Python utilities
│ ├── extract_mermaid.py # Extract & validate diagrams
│ └── mermaid_to_image.py # Convert to PNG/SVG
│
├── examples/ # Language-specific patterns
│ ├── spring-boot/ # Spring Boot patterns
│ ├── fastapi/ # FastAPI patterns
│ ├── react/ # React patterns
│ ├── python-etl/ # Data pipeline patterns
│ ├── node-webapp/ # Express.js patterns
│ └── java-webapp/ # Traditional Java patterns
│
└── references/ # General Mermaid reference
└── mermaid-diagram-guide.md # Complete Mermaid syntax guideWorkflow Summary
1. Analyze user intent → Determine diagram type, document type, or action needed 2. Load appropriate guide(s) → Read only what's needed (token efficient) 3. Apply templates and patterns → Use examples from guides 4. Generate output → Create diagram or document 5. Validate (optional) → Use scripts to verify 6. Convert (optional) → Export to images if needed
When to Use What
| User Request | Load This |
|---|---|
| "activity diagram", "workflow", "process flow" | references/guides/diagrams/activity-diagrams.md |
| "deployment", "infrastructure", "cloud", "k8s" | references/guides/diagrams/deployment-diagrams.md |
| "architecture", "system design", "components" | references/guides/diagrams/architecture-diagrams.md + design template |
| "API", "sequence", "interactions", "flow" | references/mermaid-diagram-guide.md (sequence section) |
| "Spring Boot code" | examples/spring-boot/ + relevant diagram guides |
| "FastAPI code", "Python API" | examples/fastapi/ + relevant diagram guides |
| "React app", "frontend" | examples/react/ + architecture guide |
| "ETL", "data pipeline", "Python batch" | examples/python-etl/ + activity guide |
| "symbols", "unicode", "emoji" | references/guides/unicode-symbols/guide.md |
| "syntax error", "diagram won't render", "troubleshoot" | references/guides/troubleshooting.md |
| "extract diagrams" | scripts/extract_mermaid.py |
| "convert to image", "PNG", "SVG" | scripts/mermaid_to_image.py |
| "create diagram", "generate diagram", "add diagram to markdown" | scripts/resilient_diagram.py + references/guides/resilient-workflow.md |
| "design document", "full docs" | assets/*-design-template.md + diagram guides |
Best Practices
1. Single Responsibility: One diagram = One concept 2. Unicode Enhancement: Always use semantic symbols for clarity 3. High Contrast: Never skip the color: property in styles 4. Validate Early: Use scripts to catch syntax errors 5. Template Reuse: Leverage existing templates and examples 6. Load On-Demand: Only read guides needed for the specific request 7. Token Efficiency: Use hierarchical loading instead of reading everything
Learning Path
New to Mermaid? Start here: 1. Read references/guides/unicode-symbols/guide.md for symbol meanings 2. Read references/guides/diagrams/activity-diagrams.md for basic patterns 3. Try examples in examples/spring-boot/ or examples/fastapi/ 4. Use scripts/extract_mermaid.py --validate to check your work
Need to document code? Follow this: 1. Identify your framework → Load relevant examples/{framework}/ 2. Match code pattern to diagram type 3. Use templates from guide 4. Validate with scripts
Creating design docs? Follow this: 1. Choose document type → Load template from assets/ 2. Fill in text sections 3. Load diagram guides as needed for each section 4. Use Unicode symbols throughout 5. Save to docs/design/ with timestamp
---
Version: 2.0 (Hierarchical Architecture) Last Updated: 2025-01-13 Maintained by: Claude Code Skills
[API Name] - API Design Document
Author: [Name] Date: [YYYY-MM-DD] Status: Draft | In Review | Approved Version: 1.0 API Version: v1
---
1. Executive Summary
Purpose: [What this API does]
Target Audience:
- Internal services
- External partners
- Public developers
Key Features:
- Feature 1
- Feature 2
- Feature 3
---
2. API Overview
2.1 Base URL
Production: https://api.example.com/v1
Staging: https://api-staging.example.com/v1
Development: http://localhost:8000/v12.2 Authentication
Method: [OAuth 2.0 | API Key | JWT | etc.]
sequenceDiagram
participant Client
participant AuthServer
participant APIGateway
participant ResourceServer
Client->>AuthServer: POST /oauth/token
AuthServer-->>Client: access_token
Client->>APIGateway: GET /resource<br/>Authorization: Bearer {token}
APIGateway->>AuthServer: Validate Token
AuthServer-->>APIGateway: Valid
APIGateway->>ResourceServer: Get Resource
ResourceServer-->>APIGateway: Resource Data
APIGateway-->>Client: 200 OK---
3. API Endpoints
3.1 Endpoint Overview
graph LR
subgraph "Authentication"
Auth1[POST /auth/login]
Auth2[POST /auth/refresh]
end
subgraph "Users"
User1[GET /users]
User2[GET /users/:id]
User3[POST /users]
User4[PUT /users/:id]
User5[DELETE /users/:id]
end
subgraph "Resources"
Res1[GET /resources]
Res2[GET /resources/:id]
Res3[POST /resources]
Res4[PUT /resources/:id]
Res5[DELETE /resources/:id]
end3.2 Detailed Endpoints
POST /auth/login
Authenticate a user and receive access token.
Request:
{
"email": "user@example.com",
"password": "securePassword123"
}Response (200 OK):
{
"access_token": "eyJhbGc...",
"refresh_token": "dGhpc2lz...",
"token_type": "Bearer",
"expires_in": 3600
}Errors:
400 Bad Request- Invalid credentials429 Too Many Requests- Rate limit exceeded
---
GET /users/:id
Retrieve user details by ID.
Parameters:
id(path, required): User ID
Response (200 OK):
{
"id": "123",
"email": "user@example.com",
"name": "John Doe",
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-01T00:00:00Z"
}Errors:
401 Unauthorized- Missing or invalid token404 Not Found- User not found
---
POST /resources
Create a new resource.
Request:
{
"name": "Resource Name",
"description": "Resource description",
"type": "type_a",
"metadata": {
"key": "value"
}
}Response (201 Created):
{
"id": "res_123",
"name": "Resource Name",
"description": "Resource description",
"type": "type_a",
"metadata": {
"key": "value"
},
"created_at": "2025-01-01T00:00:00Z"
}Errors:
400 Bad Request- Validation errors401 Unauthorized- Missing or invalid token422 Unprocessable Entity- Invalid data
---
4. Data Models
4.1 Entity Relationships
erDiagram
USER ||--o{ RESOURCE : owns
USER {
string id PK
string email UK
string name
datetime created_at
datetime updated_at
}
RESOURCE ||--o{ RESOURCE_TAG : has
RESOURCE {
string id PK
string user_id FK
string name
string description
string type
json metadata
datetime created_at
}
TAG ||--o{ RESOURCE_TAG : tagged_in
TAG {
string id PK
string name UK
}
RESOURCE_TAG {
string resource_id FK
string tag_id FK
}4.2 User Model
{
"id": "string (UUID)",
"email": "string (email format, unique)",
"name": "string (1-255 chars)",
"role": "enum (admin, user, guest)",
"created_at": "ISO 8601 datetime",
"updated_at": "ISO 8601 datetime"
}---
5. Request/Response Flow
5.1 Typical Request Flow
sequenceDiagram
participant Client
participant Gateway
participant Auth
participant Service
participant Database
participant Cache
Client->>Gateway: HTTP Request
Gateway->>Auth: Validate Token
Auth-->>Gateway: Valid
Gateway->>Cache: Check Cache
alt Cache Hit
Cache-->>Gateway: Cached Data
else Cache Miss
Gateway->>Service: Process Request
Service->>Database: Query
Database-->>Service: Result
Service->>Cache: Update Cache
Service-->>Gateway: Response Data
end
Gateway-->>Client: HTTP Response5.2 Error Handling Flow
stateDiagram-v2
[*] --> ValidateRequest
ValidateRequest --> ProcessRequest: Valid
ValidateRequest --> Return400: Invalid
ProcessRequest --> CheckAuth
CheckAuth --> ExecuteLogic: Authorized
CheckAuth --> Return401: Unauthorized
ExecuteLogic --> Return200: Success
ExecuteLogic --> Return500: Server Error
ExecuteLogic --> Return404: Not Found
Return200 --> [*]
Return400 --> [*]
Return401 --> [*]
Return404 --> [*]
Return500 --> [*]---
6. Rate Limiting
6.1 Rate Limit Policy
| Tier | Requests/Minute | Requests/Hour | Burst |
|---|---|---|---|
| Free | 60 | 1000 | 10 |
| Basic | 300 | 10000 | 50 |
| Premium | 1000 | 100000 | 200 |
Headers:
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1640995200---
7. Error Responses
7.1 Error Format
{
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "The requested resource was not found",
"details": {
"resource_id": "res_123"
},
"timestamp": "2025-01-01T00:00:00Z",
"request_id": "req_abc123"
}
}7.2 Error Codes
| HTTP Status | Error Code | Description |
|---|---|---|
| 400 | INVALID_REQUEST | Request validation failed |
| 401 | UNAUTHORIZED | Missing or invalid authentication |
| 403 | FORBIDDEN | Insufficient permissions |
| 404 | NOT_FOUND | Resource not found |
| 422 | VALIDATION_ERROR | Data validation failed |
| 429 | RATE_LIMIT_EXCEEDED | Too many requests |
| 500 | INTERNAL_ERROR | Server error |
| 503 | SERVICE_UNAVAILABLE | Service temporarily unavailable |
---
8. Pagination
Request:
GET /resources?page=2&per_page=20&sort=created_at&order=descResponse:
{
"data": [...],
"pagination": {
"page": 2,
"per_page": 20,
"total_pages": 10,
"total_count": 200,
"has_next": true,
"has_prev": true
},
"links": {
"self": "/resources?page=2&per_page=20",
"first": "/resources?page=1&per_page=20",
"prev": "/resources?page=1&per_page=20",
"next": "/resources?page=3&per_page=20",
"last": "/resources?page=10&per_page=20"
}
}---
9. Filtering & Search
9.1 Filter Parameters
GET /resources?type=type_a&status=active&created_after=2025-01-019.2 Search
GET /resources?q=search+term&fields=name,description---
10. Webhooks
10.1 Webhook Events
sequenceDiagram
participant Service
participant WebhookQueue
participant ClientEndpoint
Service->>WebhookQueue: Event Occurred
WebhookQueue->>ClientEndpoint: POST /webhook
alt Success
ClientEndpoint-->>WebhookQueue: 200 OK
else Failure
ClientEndpoint-->>WebhookQueue: Error
WebhookQueue->>WebhookQueue: Retry (3 attempts)
endEvent Types:
resource.createdresource.updatedresource.deleteduser.created
Webhook Payload:
{
"event": "resource.created",
"timestamp": "2025-01-01T00:00:00Z",
"data": {
"id": "res_123",
"name": "Resource Name"
}
}---
11. Versioning Strategy
Strategy: URL-based versioning
Deprecation Policy:
- New version announced 6 months in advance
- Old version supported for 12 months after new version release
- Sunset notices sent via email and API headers
Version Headers:
API-Version: 1.0
API-Deprecated: false
API-Sunset-Date: null---
12. Security Considerations
12.1 Security Checklist
- [x] HTTPS only (TLS 1.2+)
- [x] Authentication required
- [x] Authorization checks on all endpoints
- [x] Input validation
- [x] SQL injection prevention
- [x] XSS prevention
- [x] CSRF protection
- [x] Rate limiting
- [x] Request size limits
- [x] Audit logging
---
13. Performance Targets
| Metric | Target | Current |
|---|---|---|
| Response Time (p95) | < 200ms | 150ms |
| Response Time (p99) | < 500ms | 350ms |
| Throughput | > 1000 req/s | 1200 req/s |
| Uptime | 99.9% | 99.95% |
---
14. Testing Strategy
14.1 Test Coverage
graph TB
subgraph "API Testing Layers"
Unit[Unit Tests]
Integration[Integration Tests]
Contract[Contract Tests]
E2E[End-to-End Tests]
Load[Load Tests]
end
Unit --> Integration
Integration --> Contract
Contract --> E2E
E2E --> Load---
15. API Client Examples
15.1 cURL
curl -X POST https://api.example.com/v1/resources \
-H "Authorization: Bearer {token}" \
-H "Content-Type: application/json" \
-d '{
"name": "Resource Name",
"type": "type_a"
}'15.2 Python
import requests
headers = {
"Authorization": "Bearer {token}",
"Content-Type": "application/json"
}
data = {
"name": "Resource Name",
"type": "type_a"
}
response = requests.post(
"https://api.example.com/v1/resources",
headers=headers,
json=data
)
print(response.json())---
16. Changelog
v1.0.0 (2025-01-01)
Added:
- Initial API release
- Authentication endpoints
- User management endpoints
- Resource CRUD operations
---
17. Appendices
A. Glossary
| Term | Definition |
|---|---|
| JWT | JSON Web Token |
| CRUD | Create, Read, Update, Delete |
B. References
[System Name] - Architecture Design Document
Author: [Name] Date: [YYYY-MM-DD] Status: Draft | In Review | Approved Version: 1.0
---
1. Executive Summary
[Brief overview of the system and key architectural decisions]
Business Context:
- Problem being solved
- Target users
- Key business requirements
Key Decisions:
- Major architectural choice 1
- Major architectural choice 2
- Major architectural choice 3
---
2. System Context
2.1 System Overview
[High-level description of what the system does]
C4Context
title System Context Diagram for [System Name]
Person(user, "User", "A user of the system")
System(systemName, "[System Name]", "Description of the system")
System_Ext(externalSystem, "External System", "Description")
Rel(user, systemName, "Uses", "HTTPS")
Rel(systemName, externalSystem, "Integrates with", "REST API")2.2 Stakeholders
| Stakeholder | Role | Interest |
|---|---|---|
| [Name/Group] | [Role] | [What they care about] |
---
3. Requirements
3.1 Functional Requirements
| ID | Requirement | Priority |
|---|---|---|
| FR-1 | [Requirement description] | High/Medium/Low |
3.2 Non-Functional Requirements
| Category | Requirement | Target |
|---|---|---|
| Performance | [Description] | [Metric] |
| Scalability | [Description] | [Metric] |
| Availability | [Description] | [Metric] |
| Security | [Description] | [Standard] |
---
4. Architecture Overview
4.1 Architectural Style
[Description of the architectural pattern: microservices, layered, event-driven, etc.]
Why this style:
- Reason 1
- Reason 2
- Reason 3
4.2 High-Level Architecture
graph TB
subgraph "Client Layer"
WebApp[Web Application]
MobileApp[Mobile App]
end
subgraph "API Gateway Layer"
Gateway[API Gateway]
end
subgraph "Service Layer"
AuthService[Auth Service]
DataService[Data Service]
NotificationService[Notification Service]
end
subgraph "Data Layer"
DB[(Database)]
Cache[(Cache)]
end
WebApp --> Gateway
MobileApp --> Gateway
Gateway --> AuthService
Gateway --> DataService
Gateway --> NotificationService
AuthService --> DB
DataService --> DB
DataService --> Cache
NotificationService --> Cache---
5. Component Design
5.1 Component Overview
graph LR
subgraph "Component A"
A1[Module A1]
A2[Module A2]
end
subgraph "Component B"
B1[Module B1]
B2[Module B2]
end
A1 --> B1
A2 --> B25.2 Component Descriptions
Component A
- Purpose: [What it does]
- Responsibilities: [Key responsibilities]
- Technologies: [Tech stack]
- Dependencies: [What it depends on]
---
6. Data Architecture
6.1 Data Model
erDiagram
USER ||--o{ ORDER : places
USER {
int id PK
string email
string name
datetime created_at
}
ORDER ||--|{ ORDER_ITEM : contains
ORDER {
int id PK
int user_id FK
datetime order_date
decimal total
}
PRODUCT ||--o{ ORDER_ITEM : "ordered in"
ORDER_ITEM {
int id PK
int order_id FK
int product_id FK
int quantity
decimal price
}
PRODUCT {
int id PK
string name
decimal price
int stock
}6.2 Data Flow
flowchart LR
A[User Input] --> B[Validation]
B --> C[Business Logic]
C --> D[Data Persistence]
D --> E[Cache Update]
E --> F[Response]---
7. Integration Points
7.1 External Dependencies
| System | Purpose | Protocol | SLA |
|---|---|---|---|
| [System] | [Purpose] | [REST/gRPC/etc] | [99.9%] |
7.2 API Design
sequenceDiagram
participant Client
participant Gateway
participant AuthService
participant DataService
participant Database
Client->>Gateway: POST /api/resource
Gateway->>AuthService: Validate Token
AuthService-->>Gateway: Token Valid
Gateway->>DataService: Create Resource
DataService->>Database: INSERT
Database-->>DataService: Success
DataService-->>Gateway: Resource Created
Gateway-->>Client: 201 Created---
8. Security Architecture
8.1 Security Layers
graph TB
subgraph "Security Layers"
WAF[Web Application Firewall]
TLS[TLS/SSL Encryption]
Auth[Authentication]
Authz[Authorization]
Encryption[Data Encryption]
end
Internet --> WAF
WAF --> TLS
TLS --> Auth
Auth --> Authz
Authz --> Encryption8.2 Authentication Flow
stateDiagram-v2
[*] --> Unauthenticated
Unauthenticated --> Authenticating: Login Request
Authenticating --> Authenticated: Success
Authenticating --> Unauthenticated: Failure
Authenticated --> Unauthenticated: Logout
Authenticated --> TokenRefresh: Token Expiring
TokenRefresh --> Authenticated: Refresh Success
TokenRefresh --> Unauthenticated: Refresh Failure---
9. Deployment Architecture
9.1 Infrastructure
graph TB
subgraph "Production Environment"
subgraph "Region 1"
LB1[Load Balancer]
App1[App Server 1]
App2[App Server 2]
DB1[(Primary DB)]
end
subgraph "Region 2"
LB2[Load Balancer]
App3[App Server 3]
App4[App Server 4]
DB2[(Replica DB)]
end
end
DNS --> LB1
DNS --> LB2
LB1 --> App1
LB1 --> App2
LB2 --> App3
LB2 --> App4
App1 --> DB1
App2 --> DB1
App3 --> DB2
App4 --> DB2
DB1 -.Replication.-> DB2---
10. Scalability & Performance
10.1 Scaling Strategy
| Component | Strategy | Trigger | Max Scale |
|---|---|---|---|
| [Component] | [Horizontal/Vertical] | [Metric > Threshold] | [N instances] |
10.2 Performance Targets
| Operation | Target | Current | Strategy |
|---|---|---|---|
| [Operation] | [< X ms] | [Y ms] | [Optimization approach] |
---
11. Monitoring & Observability
11.1 Key Metrics
graph LR
subgraph "Metrics"
M1[Request Rate]
M2[Error Rate]
M3[Response Time]
M4[Resource Usage]
end
subgraph "Alerts"
A1[High Error Rate]
A2[Slow Response]
A3[Resource Exhaustion]
end
M2 --> A1
M3 --> A2
M4 --> A3---
12. Disaster Recovery
12.1 Backup Strategy
| Data Type | Frequency | Retention | RTO | RPO |
|---|---|---|---|---|
| [Type] | [Frequency] | [Period] | [Time] | [Time] |
---
13. Technical Debt & Future Work
13.1 Known Limitations
1. [Limitation description] 2. [Limitation description]
13.2 Future Enhancements
gantt
title Planned Enhancements
dateFormat YYYY-MM-DD
section Phase 1
Enhancement 1 :2025-01-01, 30d
Enhancement 2 :2025-02-01, 45d
section Phase 2
Enhancement 3 :2025-03-15, 60d---
14. Decision Log
ADR-001: [Decision Title]
Date: [YYYY-MM-DD] Status: Accepted
Context: [What led to this decision]
Decision: [What was decided]
Consequences:
- Positive: [Benefits]
- Negative: [Costs/Trade-offs]
Alternatives Considered: 1. [Alternative 1] - Rejected because [reason] 2. [Alternative 2] - Rejected because [reason]
---
15. Appendices
Glossary
| Term | Definition |
|---|---|
| [Term] | [Definition] |
References
1. [Document/Link] 2. [Document/Link]
[Database Name] - Database Design Document
Author: [Name] Date: [YYYY-MM-DD] Status: Draft | In Review | Approved Version: 1.0
---
1. Executive Summary
Database Type: [PostgreSQL | MySQL | MongoDB | etc.]
Purpose: [What this database stores and why]
Scale:
- Expected records: [Number]
- Expected growth: [Rate]
- Expected queries/sec: [Number]
---
2. Requirements
2.1 Functional Requirements
| Requirement | Description | Priority |
|---|---|---|
| FR-1 | [Requirement] | High/Medium/Low |
2.2 Non-Functional Requirements
| Category | Requirement | Target |
|---|---|---|
| Performance | Query response time | < 100ms |
| Availability | Uptime | 99.9% |
| Scalability | Max records | 10M |
| Backup | Recovery time | < 1 hour |
---
3. Data Model
3.1 Entity Relationship Diagram
erDiagram
USER ||--o{ ORDER : places
USER ||--o{ PAYMENT_METHOD : has
USER {
uuid id PK
varchar email UK "Unique email"
varchar password_hash "Bcrypt hash"
varchar name
enum role "admin, user, guest"
timestamp created_at
timestamp updated_at
timestamp last_login
boolean is_active "Soft delete flag"
}
ORDER ||--|{ ORDER_ITEM : contains
ORDER ||--|| PAYMENT : "paid by"
ORDER {
uuid id PK
uuid user_id FK
enum status "pending, processing, shipped, delivered, cancelled"
decimal total_amount "Total with tax"
decimal tax_amount
text shipping_address
timestamp order_date
timestamp shipped_date
timestamp delivered_date
}
PRODUCT ||--o{ ORDER_ITEM : "ordered in"
PRODUCT ||--o{ PRODUCT_CATEGORY : "belongs to"
PRODUCT ||--o{ INVENTORY : "has stock in"
PRODUCT {
uuid id PK
varchar sku UK "Stock keeping unit"
varchar name
text description
decimal price
decimal cost
text image_url
boolean is_active
timestamp created_at
timestamp updated_at
}
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal unit_price "Price at time of order"
decimal discount_amount
decimal line_total
}
PAYMENT_METHOD {
uuid id PK
uuid user_id FK
enum type "credit_card, debit_card, paypal, bank_account"
varchar last_four "Last 4 digits"
varchar provider "Stripe, PayPal"
text encrypted_data
boolean is_default
timestamp created_at
}
PAYMENT {
uuid id PK
uuid order_id FK
uuid payment_method_id FK
decimal amount
enum status "pending, completed, failed, refunded"
varchar transaction_id
text metadata
timestamp created_at
}
CATEGORY {
uuid id PK
varchar name UK
varchar slug UK
text description
uuid parent_id FK "Self-referencing"
int display_order
}
PRODUCT_CATEGORY {
uuid product_id FK
uuid category_id FK
}
WAREHOUSE {
uuid id PK
varchar name
text address
varchar manager_email
}
INVENTORY {
uuid id PK
uuid product_id FK
uuid warehouse_id FK
int quantity
int reserved_quantity
timestamp last_updated
}
WAREHOUSE ||--o{ INVENTORY : "stores"
CATEGORY ||--o{ CATEGORY : "has subcategory"
CATEGORY ||--o{ PRODUCT_CATEGORY : categorizes3.2 Cardinality Explanation
| Relationship | Cardinality | Explanation |
|---|---|---|
| USER - ORDER | 1:N | One user can place many orders |
| ORDER - ORDER_ITEM | 1:N | One order contains many items |
| PRODUCT - ORDER_ITEM | 1:N | One product can be in many order items |
| ORDER - PAYMENT | 1:1 | One order has one payment |
---
4. Table Specifications
4.1 Users Table
Purpose: Store user account information
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL DEFAULT 'user'
CHECK (role IN ('admin', 'user', 'guest')),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP,
is_active BOOLEAN NOT NULL DEFAULT true
);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_created_at ON users(created_at);
CREATE INDEX idx_users_is_active ON users(is_active) WHERE is_active = true;Column Details:
| Column | Type | Constraints | Description |
|---|---|---|---|
| id | UUID | PK | Unique identifier |
| VARCHAR(255) | UNIQUE, NOT NULL | User email | |
| password_hash | VARCHAR(255) | NOT NULL | Bcrypt password hash |
| role | VARCHAR(50) | CHECK, DEFAULT 'user' | User role |
| is_active | BOOLEAN | DEFAULT true | Soft delete flag |
Indexes:
- Primary key on
id(B-tree) - Unique index on
email(B-tree) - Index on
created_atfor sorting (B-tree) - Partial index on
is_activefor active users only
---
4.2 Orders Table
Purpose: Store order information
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
status VARCHAR(50) NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'cancelled')),
total_amount DECIMAL(10, 2) NOT NULL,
tax_amount DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
shipping_address TEXT NOT NULL,
order_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
shipped_date TIMESTAMP,
delivered_date TIMESTAMP
);
CREATE INDEX idx_orders_user_id ON orders(user_id);
CREATE INDEX idx_orders_status ON orders(status);
CREATE INDEX idx_orders_order_date ON orders(order_date DESC);---
5. Constraints & Business Rules
5.1 Check Constraints
-- Ensure order total is positive
ALTER TABLE orders ADD CONSTRAINT check_total_positive
CHECK (total_amount > 0);
-- Ensure quantity is positive
ALTER TABLE order_items ADD CONSTRAINT check_quantity_positive
CHECK (quantity > 0);
-- Ensure prices are non-negative
ALTER TABLE products ADD CONSTRAINT check_price_non_negative
CHECK (price >= 0);5.2 Foreign Key Constraints
| Table | Foreign Key | References | On Delete | On Update |
|---|---|---|---|---|
| orders | user_id | users(id) | RESTRICT | CASCADE |
| order_items | order_id | orders(id) | CASCADE | CASCADE |
| order_items | product_id | products(id) | RESTRICT | CASCADE |
---
6. Indexes Strategy
6.1 Index Overview
graph TB
subgraph "Index Types"
PK[Primary Keys<br/>B-tree]
UK[Unique Indexes<br/>B-tree]
FK[Foreign Key Indexes<br/>B-tree]
Partial[Partial Indexes<br/>Filtered]
Composite[Composite Indexes<br/>Multi-column]
end
subgraph "Query Patterns"
Q1[Lookup by ID]
Q2[Search by email]
Q3[Filter by status]
Q4[Sort by date]
Q5[Join tables]
end
PK --> Q1
UK --> Q2
FK --> Q5
Partial --> Q3
Composite --> Q46.2 Critical Indexes
| Table | Index | Type | Purpose | Estimated Size |
|---|---|---|---|---|
| users | idx_users_email | B-tree | Login queries | 10MB |
| orders | idx_orders_user_id | B-tree | User order history | 50MB |
| orders | idx_orders_status | Partial | Active orders only | 20MB |
| products | idx_products_sku | Unique B-tree | Product lookup | 5MB |
---
7. Data Access Patterns
7.1 Query Patterns
Pattern 1: User Login
SELECT id, email, password_hash, role
FROM users
WHERE email = ? AND is_active = true;Indexes Used: idx_users_email
Pattern 2: Order History
SELECT o.*, oi.*, p.*
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.user_id = ?
ORDER BY o.order_date DESC
LIMIT 20;Indexes Used: idx_orders_user_id, idx_orders_order_date
7.2 Query Flow
sequenceDiagram
participant App
participant Cache
participant DB
participant Index
App->>Cache: Check cache
alt Cache Hit
Cache-->>App: Return data
else Cache Miss
App->>DB: Execute query
DB->>Index: Lookup in index
Index-->>DB: Return row IDs
DB->>DB: Fetch rows
DB-->>App: Return result
App->>Cache: Update cache
end---
8. Partitioning Strategy
8.1 Partitioning Plan
Table: orders
Strategy: Range partitioning by order_date
-- Create partitioned table
CREATE TABLE orders (
...
) PARTITION BY RANGE (order_date);
-- Create partitions
CREATE TABLE orders_2024_q1 PARTITION OF orders
FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
CREATE TABLE orders_2024_q2 PARTITION OF orders
FOR VALUES FROM ('2024-04-01') TO ('2024-07-01');Benefits:
- Faster queries on recent orders
- Easier archival of old data
- Improved maintenance (VACUUM, ANALYZE)
---
9. Normalization Level
9.1 Current Normalization
Level: Third Normal Form (3NF)
Why:
- Eliminates data redundancy
- Maintains data integrity
- Allows efficient updates
9.2 Denormalization Decisions
| Table | Denormalized Field | Reason | Trade-off |
|---|---|---|---|
| order_items | unit_price | Historical price at time of order | Duplicates product price |
| orders | total_amount | Avoid recalculating sum | Must update on item changes |
---
10. Data Migration & Evolution
10.1 Migration Strategy
graph LR
V1[Schema v1.0] -->|Migration| V2[Schema v1.1]
V2 -->|Migration| V3[Schema v2.0]
V1 -.->|Backward Compatible| V2
V2 -.->|Breaking Change| V310.2 Migration Example
-- Add new column (backward compatible)
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
-- Create index concurrently (no downtime)
CREATE INDEX CONCURRENTLY idx_users_phone ON users(phone);
-- Backfill data
UPDATE users SET phone = '000-000-0000' WHERE phone IS NULL;
-- Add NOT NULL constraint
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;---
11. Backup & Recovery
11.1 Backup Strategy
| Backup Type | Frequency | Retention | RTO | RPO |
|---|---|---|---|---|
| Full Backup | Daily | 30 days | 4 hours | 24 hours |
| Incremental | Hourly | 7 days | 1 hour | 1 hour |
| Transaction Logs | Continuous | 7 days | 15 minutes | 5 minutes |
11.2 Recovery Flow
flowchart TD
Incident[Incident Detected]
Assess{Assess Damage}
PointInTime[Point-in-time Recovery]
FullRestore[Full Restore]
Verify[Verify Data Integrity]
Resume[Resume Operations]
Incident --> Assess
Assess -->|Recent| PointInTime
Assess -->|Critical| FullRestore
PointInTime --> Verify
FullRestore --> Verify
Verify --> Resume---
12. Performance Optimization
12.1 Query Optimization
Slow Query Example:
-- SLOW: Full table scan
SELECT * FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2024;
-- OPTIMIZED: Index-friendly
SELECT * FROM orders
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01';12.2 Caching Strategy
graph TB
App[Application]
Redis[Redis Cache]
DB[Database]
App -->|1. Check cache| Redis
Redis -->|Hit| App
Redis -->|Miss| DB
DB -->|2. Query| App
App -->|3. Update cache| Redis---
13. Security
13.1 Access Control
-- Create read-only role
CREATE ROLE readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
-- Create application role
CREATE ROLE app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
-- Create admin role
CREATE ROLE admin WITH SUPERUSER;13.2 Data Encryption
| Data Type | Encryption | Key Management |
|---|---|---|
| Passwords | Bcrypt hash | N/A |
| Payment Data | AES-256 | AWS KMS |
| PII | Column-level encryption | HashiCorp Vault |
---
14. Monitoring & Maintenance
14.1 Key Metrics
graph LR
subgraph "Performance Metrics"
M1[Query Response Time]
M2[Transactions/sec]
M3[Connection Pool Usage]
end
subgraph "Health Metrics"
M4[Replication Lag]
M5[Disk Usage]
M6[Table Bloat]
end14.2 Maintenance Tasks
| Task | Frequency | Purpose |
|---|---|---|
| VACUUM | Weekly | Reclaim space, update statistics |
| ANALYZE | Daily | Update query planner statistics |
| REINDEX | Monthly | Rebuild fragmented indexes |
| Backup Verification | Weekly | Ensure backups are valid |
---
15. Scaling Strategy
15.1 Vertical vs Horizontal
graph TB
subgraph "Vertical Scaling"
V1[Single Server]
V2[Larger Server]
V1 --> V2
end
subgraph "Horizontal Scaling"
H1[Primary]
H2[Read Replica 1]
H3[Read Replica 2]
H1 --> H2
H1 --> H3
end15.2 Replication Architecture
graph TB
Primary[(Primary DB<br/>Read/Write)]
Replica1[(Replica 1<br/>Read Only)]
Replica2[(Replica 2<br/>Read Only)]
App[Application] -->|Writes| Primary
App -->|Reads| Replica1
App -->|Reads| Replica2
Primary -.Async Replication.-> Replica1
Primary -.Async Replication.-> Replica2---
16. Appendices
A. Data Dictionary
| Table | Column | Type | Description |
|---|---|---|---|
| users | id | UUID | Unique identifier |
| users | VARCHAR(255) | User email address |
B. Reserved Keywords
Avoid using these as column names:
user,order,select,from,where, etc.
C. References
1. Database Design Best Practices 2. PostgreSQL Performance Tuning
[Feature Name] - Feature Design Document
Author: [Name] Date: [YYYY-MM-DD] Status: Draft | In Review | Approved Version: 1.0 JIRA Ticket: [TICKET-ID]
---
1. Feature Overview
1.1 Executive Summary
What: [One sentence describing the feature]
Why: [Business value and problem being solved]
Who: [Target users]
When: [Expected delivery timeline]
---
2. Background & Context
2.1 Problem Statement
[Detailed description of the problem this feature solves]
Current State:
- [Pain point 1]
- [Pain point 2]
- [Pain point 3]
Desired State:
- [Goal 1]
- [Goal 2]
- [Goal 3]
2.2 Business Goals
| Goal | Metric | Target |
|---|---|---|
| [Goal] | [How to measure] | [Value] |
2.3 User Stories
As a [user type] I want [goal] So that [reason]
Acceptance Criteria:
- [x] Criterion 1
- [x] Criterion 2
- [x] Criterion 3
---
3. User Experience
3.1 User Journey
journey
title User Journey for [Feature Name]
section Discovery
User realizes need: 5: User
Searches for feature: 4: User
Finds feature: 5: User
section Usage
Initiates action: 5: User
Provides input: 4: User
Reviews results: 5: User
section Completion
Confirms action: 5: User
Receives feedback: 5: User
Completes task: 5: User3.2 User Flow
flowchart TD
Start([User starts])
Input[User provides input]
Validate{Valid input?}
Process[System processes]
Display[Display results]
Confirm{Confirm action?}
Execute[Execute action]
Success[Show success]
Error[Show error]
End([Complete])
Start --> Input
Input --> Validate
Validate -->|Yes| Process
Validate -->|No| Error
Process --> Display
Display --> Confirm
Confirm -->|Yes| Execute
Confirm -->|No| End
Execute --> Success
Success --> End
Error --> Input3.3 UI/UX Mockups
[Include wireframes, mockups, or screenshots]
Key UI Elements: 1. [Element 1] - [Purpose] 2. [Element 2] - [Purpose] 3. [Element 3] - [Purpose]
---
4. Technical Design
4.1 System Architecture
graph TB
subgraph "Frontend"
UI[User Interface]
State[State Management]
end
subgraph "Backend"
API[API Layer]
Service[Business Logic]
Data[Data Layer]
end
subgraph "External"
Ext1[External Service 1]
Ext2[External Service 2]
end
UI --> State
State --> API
API --> Service
Service --> Data
Service --> Ext1
Service --> Ext24.2 Component Design
classDiagram
class FeatureController {
+createResource()
+updateResource()
+deleteResource()
+listResources()
}
class FeatureService {
-validator: Validator
-repository: Repository
+processRequest()
+validateInput()
+executeBusinessLogic()
}
class Repository {
+save()
+findById()
+findAll()
+delete()
}
class Model {
+id: string
+name: string
+status: Status
+createdAt: Date
}
FeatureController --> FeatureService
FeatureService --> Repository
Repository --> Model4.3 Sequence Diagram
sequenceDiagram
participant User
participant Frontend
participant API
participant Service
participant Database
participant ExternalAPI
User->>Frontend: Trigger Action
Frontend->>Frontend: Validate Input
Frontend->>API: POST /feature/action
API->>Service: Process Request
Service->>Database: Query Data
Database-->>Service: Return Data
Service->>ExternalAPI: Call External Service
ExternalAPI-->>Service: Return Result
Service->>Database: Save Result
Service-->>API: Return Response
API-->>Frontend: 200 OK
Frontend-->>User: Display Result---
5. Data Model
5.1 Entity Relationship
erDiagram
FEATURE ||--o{ FEATURE_ITEM : contains
FEATURE {
string id PK
string name
string user_id FK
string status
datetime created_at
datetime updated_at
}
FEATURE_ITEM {
string id PK
string feature_id FK
string data
int order
}
USER ||--o{ FEATURE : owns
USER {
string id PK
string email
string name
}5.2 Database Schema
Table: features
CREATE TABLE features (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
user_id VARCHAR(36) NOT NULL,
status VARCHAR(50) DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);---
6. API Specification
6.1 Endpoints
POST /api/v1/features
Create a new feature instance.
Request:
{
"name": "Feature Name",
"config": {
"option1": "value1"
}
}Response (201):
{
"id": "feat_123",
"name": "Feature Name",
"status": "active",
"created_at": "2025-01-01T00:00:00Z"
}---
7. State Management
7.1 State Machine
stateDiagram-v2
[*] --> Draft
Draft --> Pending: Submit
Pending --> Active: Approve
Pending --> Draft: Reject
Active --> Paused: Pause
Paused --> Active: Resume
Active --> Completed: Complete
Active --> Cancelled: Cancel
Paused --> Cancelled: Cancel
Completed --> [*]
Cancelled --> [*]7.2 State Transitions
| From State | To State | Trigger | Validation |
|---|---|---|---|
| Draft | Pending | User submits | Required fields complete |
| Pending | Active | Admin approves | Passes review |
| Active | Completed | System/User | All tasks done |
---
8. Business Logic
8.1 Processing Flow
flowchart TD
Start([Receive Request])
Validate{Valid?}
CheckAuth{Authorized?}
CheckQuota{Within Quota?}
Process[Execute Business Logic]
SaveData[Persist Data]
Notify[Send Notifications]
Return[Return Response]
ErrorAuth[Return 401]
ErrorValidation[Return 400]
ErrorQuota[Return 429]
ErrorServer[Return 500]
Start --> Validate
Validate -->|No| ErrorValidation
Validate -->|Yes| CheckAuth
CheckAuth -->|No| ErrorAuth
CheckAuth -->|Yes| CheckQuota
CheckQuota -->|No| ErrorQuota
CheckQuota -->|Yes| Process
Process -->|Success| SaveData
Process -->|Failure| ErrorServer
SaveData --> Notify
Notify --> Return---
9. Security & Privacy
9.1 Security Requirements
- [x] Authentication required
- [x] Authorization checks
- [x] Input validation
- [x] Output sanitization
- [x] Rate limiting
- [x] Audit logging
9.2 Data Privacy
| Data Type | Sensitivity | Encryption | Retention |
|---|---|---|---|
| User PII | High | At rest & in transit | 7 years |
| Usage Data | Medium | In transit | 1 year |
---
10. Error Handling
10.1 Error Scenarios
| Scenario | Error Code | Message | Action |
|---|---|---|---|
| Invalid input | 400 | "Invalid request data" | Show validation errors |
| Not authenticated | 401 | "Authentication required" | Redirect to login |
| Insufficient permissions | 403 | "Access denied" | Show error page |
| Resource not found | 404 | "Resource not found" | Show 404 page |
| Rate limit exceeded | 429 | "Too many requests" | Show retry message |
| Server error | 500 | "Internal error" | Log & show generic error |
---
11. Performance Requirements
11.1 Targets
| Metric | Target | Measurement |
|---|---|---|
| Response Time | < 200ms | p95 |
| Throughput | > 100 req/s | Sustained |
| Availability | 99.9% | Monthly |
| Error Rate | < 0.1% | Per request |
11.2 Load Testing
Expected Load:
- Peak: 1000 concurrent users
- Average: 200 concurrent users
- Requests per user: 10 per session
---
12. Testing Strategy
12.1 Test Coverage
graph TB
subgraph "Testing Pyramid"
Unit[Unit Tests<br/>70%]
Integration[Integration Tests<br/>20%]
E2E[E2E Tests<br/>10%]
end
Unit --> Integration
Integration --> E2E12.2 Test Cases
| Test Case | Type | Expected Result |
|---|---|---|
| Valid input submission | Positive | Feature created successfully |
| Invalid input | Negative | Validation error returned |
| Unauthorized access | Security | 401 error |
| Rate limit exceeded | Performance | 429 error |
---
13. Deployment Plan
13.1 Rollout Strategy
gantt
title Feature Rollout Timeline
dateFormat YYYY-MM-DD
section Development
Implementation :2025-01-01, 14d
Unit Tests :2025-01-08, 7d
section Testing
Integration Tests :2025-01-15, 5d
UAT :2025-01-20, 5d
section Release
Deploy to Staging :2025-01-25, 2d
Deploy to Prod :2025-01-27, 3d
Monitor :2025-01-30, 7d13.2 Feature Flags
Flag: feature_[name]_enabled
Rollout: 1. 0% - Internal testing 2. 10% - Beta users 3. 50% - General availability 4. 100% - Full rollout
---
14. Monitoring & Metrics
14.1 Key Metrics
graph LR
subgraph "User Metrics"
M1[Adoption Rate]
M2[Usage Frequency]
M3[User Satisfaction]
end
subgraph "Technical Metrics"
M4[Response Time]
M5[Error Rate]
M6[Availability]
end
subgraph "Business Metrics"
M7[Conversion Rate]
M8[Revenue Impact]
end14.2 Alerts
| Metric | Threshold | Alert Level |
|---|---|---|
| Error rate | > 1% | Critical |
| Response time | > 500ms | Warning |
| Availability | < 99.5% | Critical |
---
15. Dependencies
15.1 External Dependencies
| Dependency | Type | Impact if Down | Mitigation |
|---|---|---|---|
| External API | Service | Feature unavailable | Implement circuit breaker |
| Database | Infrastructure | Complete failure | Read replicas |
15.2 Internal Dependencies
| Team/Service | Dependency | Timeline |
|---|---|---|
| Platform Team | API updates | Week 1 |
| Data Team | Schema changes | Week 2 |
---
16. Risks & Mitigation
| Risk | Probability | Impact | Mitigation |
|---|---|---|---|
| Performance degradation | Medium | High | Load testing, caching |
| Security vulnerability | Low | Critical | Security review, penetration testing |
| User adoption low | Medium | Medium | User research, feedback loops |
---
17. Success Criteria
17.1 Launch Criteria
- [x] All unit tests passing
- [x] Integration tests passing
- [x] Security review complete
- [x] Performance targets met
- [x] Documentation complete
- [x] Rollback plan documented
17.2 Post-Launch Success
Week 1:
- [ ] Zero critical bugs
- [ ] < 0.1% error rate
- [ ] Positive user feedback
Month 1:
- [ ] 20% user adoption
- [ ] 90% feature completion rate
- [ ] NPS score > 7
---
18. Open Questions
1. [Question 1] 2. [Question 2] 3. [Question 3]
---
19. Appendices
A. Glossary
| Term | Definition |
|---|---|
| [Term] | [Definition] |
B. References
1. [Document/Link] 2. [Document/Link]
[System Name] - System Design Document
Author: [Name] Date: [YYYY-MM-DD] Status: Draft | In Review | Approved Version: 1.0
---
1. Executive Summary
System Purpose: [One sentence describing what the system does]
Scale:
- Users: [Number of users]
- Requests/Day: [Volume]
- Data Volume: [Size]
Key Challenges: 1. [Challenge 1] 2. [Challenge 2] 3. [Challenge 3]
---
2. Requirements
2.1 Functional Requirements
1. [Requirement Category]
- FR-1: [Specific requirement]
- FR-2: [Specific requirement]
2.2 Non-Functional Requirements
| Category | Requirement | Target | Priority |
|---|---|---|---|
| Availability | Uptime | 99.99% | Critical |
| Performance | Response time | < 100ms | High |
| Scalability | Concurrent users | 100k | High |
| Consistency | Data consistency | Eventual | Medium |
| Security | Data encryption | At rest & transit | Critical |
---
3. System Context
3.1 High-Level Overview
C4Context
title System Context Diagram
Person(user, "User", "End user of the system")
Person(admin, "Admin", "System administrator")
System(mainSystem, "[System Name]", "Core system providing [functionality]")
System_Ext(authSystem, "Auth System", "Authentication provider")
System_Ext(paymentSystem, "Payment Gateway", "Payment processing")
System_Ext(emailSystem, "Email Service", "Email notifications")
SystemDb_Ext(analytics, "Analytics Platform", "Usage analytics")
Rel(user, mainSystem, "Uses", "HTTPS")
Rel(admin, mainSystem, "Manages", "HTTPS")
Rel(mainSystem, authSystem, "Authenticates with", "OAuth 2.0")
Rel(mainSystem, paymentSystem, "Processes payments", "REST API")
Rel(mainSystem, emailSystem, "Sends emails", "SMTP")
Rel(mainSystem, analytics, "Sends events", "Streaming")---
4. High-Level Architecture
4.1 Architecture Overview
graph TB
subgraph "Client Layer"
Web[Web App]
Mobile[Mobile App]
API_Client[API Clients]
end
subgraph "Edge Layer"
CDN[CDN]
WAF[Web Application Firewall]
LB[Load Balancer]
end
subgraph "API Gateway Layer"
Gateway[API Gateway]
RateLimit[Rate Limiter]
end
subgraph "Application Layer"
Auth[Auth Service]
User[User Service]
Order[Order Service]
Payment[Payment Service]
Notification[Notification Service]
end
subgraph "Data Layer"
PrimaryDB[(Primary DB)]
ReplicaDB[(Read Replica)]
Cache[(Redis Cache)]
Queue[Message Queue]
end
subgraph "Storage Layer"
ObjectStore[Object Storage]
SearchIndex[Search Index]
end
Web --> CDN
Mobile --> CDN
API_Client --> CDN
CDN --> WAF
WAF --> LB
LB --> Gateway
Gateway --> RateLimit
RateLimit --> Auth
RateLimit --> User
RateLimit --> Order
RateLimit --> Payment
RateLimit --> Notification
Auth --> PrimaryDB
User --> ReplicaDB
Order --> PrimaryDB
Payment --> PrimaryDB
Notification --> Queue
Auth --> Cache
User --> Cache
Order --> Cache
User --> ObjectStore
Order --> SearchIndex---
5. Component Design
5.1 Service Architecture
graph TB
subgraph "User Service"
US_API[REST API]
US_Logic[Business Logic]
US_Data[Data Layer]
US_Cache[Cache Layer]
end
subgraph "Order Service"
OS_API[REST API]
OS_Logic[Business Logic]
OS_Data[Data Layer]
OS_Queue[Queue Publisher]
end
subgraph "Payment Service"
PS_API[REST API]
PS_Logic[Business Logic]
PS_Data[Data Layer]
PS_External[External Gateway]
end
Client --> US_API
Client --> OS_API
Client --> PS_API
US_API --> US_Logic
US_Logic --> US_Data
US_Logic --> US_Cache
OS_API --> OS_Logic
OS_Logic --> OS_Data
OS_Logic --> OS_Queue
PS_API --> PS_Logic
PS_Logic --> PS_Data
PS_Logic --> PS_External---
6. Data Flow
6.1 Write Path
sequenceDiagram
participant User
participant LB as Load Balancer
participant API as API Gateway
participant Service as Application Service
participant DB as Primary Database
participant Cache as Cache
participant Queue as Message Queue
User->>LB: Write Request
LB->>API: Forward Request
API->>API: Authenticate & Authorize
API->>Service: Process Request
Service->>DB: Write to Database
DB-->>Service: Write Confirmed
Service->>Cache: Invalidate Cache
Service->>Queue: Publish Event
Service-->>API: Return Response
API-->>LB: Return Response
LB-->>User: Success Response6.2 Read Path
sequenceDiagram
participant User
participant CDN
participant LB as Load Balancer
participant API as API Gateway
participant Cache as Redis Cache
participant Service as Application Service
participant DB as Read Replica
User->>CDN: Read Request
alt Static Content
CDN-->>User: Return Cached Content
else Dynamic Content
CDN->>LB: Forward Request
LB->>API: Forward Request
API->>Cache: Check Cache
alt Cache Hit
Cache-->>API: Return Cached Data
else Cache Miss
API->>Service: Process Request
Service->>DB: Query Database
DB-->>Service: Return Data
Service->>Cache: Update Cache
Service-->>API: Return Data
end
API-->>LB: Return Response
LB-->>CDN: Return Response
CDN-->>User: Return Response
end---
7. Database Design
7.1 Data Model
erDiagram
USER ||--o{ SESSION : has
USER ||--o{ ORDER : places
USER {
uuid id PK
string email UK
string name
enum role
timestamp created_at
}
SESSION {
uuid id PK
uuid user_id FK
string token UK
timestamp expires_at
timestamp created_at
}
ORDER ||--|{ ORDER_ITEM : contains
ORDER ||--|| PAYMENT : has
ORDER {
uuid id PK
uuid user_id FK
decimal total
enum status
timestamp created_at
}
PRODUCT ||--o{ ORDER_ITEM : "ordered in"
PRODUCT {
uuid id PK
string sku UK
string name
decimal price
int stock
}
ORDER_ITEM {
uuid id PK
uuid order_id FK
uuid product_id FK
int quantity
decimal price
}
PAYMENT {
uuid id PK
uuid order_id FK
decimal amount
enum status
string transaction_id
}7.2 Sharding Strategy
graph TB
App[Application]
Router[Shard Router]
Shard1[(Shard 1<br/>Users A-M)]
Shard2[(Shard 2<br/>Users N-Z)]
App --> Router
Router -->|user_id hash % 2 == 0| Shard1
Router -->|user_id hash % 2 == 1| Shard2Sharding Key: user_id
Rationale:
- Even distribution of data
- Enables user-centric queries
- Allows independent scaling
---
8. API Design
8.1 API Architecture
sequenceDiagram
participant Client
participant Gateway
participant Auth
participant Service
participant DB
Client->>Gateway: POST /api/v1/resource
Gateway->>Auth: Validate Token
Auth-->>Gateway: Valid + Claims
Gateway->>Service: Forward Request + User Context
Service->>Service: Business Logic
Service->>DB: Persist Data
DB-->>Service: Success
Service-->>Gateway: 201 Created
Gateway-->>Client: 201 Created + Resource8.2 Key Endpoints
| Endpoint | Method | Purpose | Rate Limit |
|---|---|---|---|
/api/v1/users | GET | List users | 100/min |
/api/v1/users/:id | GET | Get user | 300/min |
/api/v1/orders | POST | Create order | 30/min |
/api/v1/orders/:id | GET | Get order | 300/min |
---
9. Scaling Strategy
9.1 Horizontal Scaling
graph TB
subgraph "Auto Scaling Group"
App1[App Instance 1]
App2[App Instance 2]
App3[App Instance 3]
AppN[App Instance N]
end
LB[Load Balancer]
Metrics[CloudWatch Metrics]
LB --> App1
LB --> App2
LB --> App3
LB --> AppN
App1 --> Metrics
App2 --> Metrics
App3 --> Metrics
AppN --> Metrics
Metrics -->|CPU > 70%| AutoScale[Auto Scaling Policy]
AutoScale -->|Add Instances| App19.2 Database Scaling
graph TB
subgraph "Database Cluster"
Primary[(Primary<br/>Read + Write)]
Replica1[(Replica 1<br/>Read Only)]
Replica2[(Replica 2<br/>Read Only)]
Replica3[(Replica 3<br/>Read Only)]
end
AppWrite[Write Operations]
AppRead[Read Operations]
AppWrite --> Primary
AppRead --> Replica1
AppRead --> Replica2
AppRead --> Replica3
Primary -.Replication.-> Replica1
Primary -.Replication.-> Replica2
Primary -.Replication.-> Replica3---
10. Caching Strategy
10.1 Multi-Layer Cache
graph TB
User[User Request]
CDN[CDN Cache<br/>Static Assets]
AppCache[Application Cache<br/>Redis]
DB[(Database)]
User --> CDN
CDN -->|Miss| AppCache
AppCache -->|Miss| DB
DB -->|Data| AppCache
AppCache -->|Update| CDN
AppCache -->|Response| User10.2 Cache Invalidation
Strategy: Write-through with TTL
| Data Type | TTL | Invalidation Trigger |
|---|---|---|
| User Profile | 1 hour | On user update |
| Product Catalog | 15 minutes | On product change |
| Order Status | 5 minutes | On order update |
| Static Assets | 30 days | On deployment |
---
11. Message Queue Architecture
11.1 Event-Driven Architecture
graph LR
OrderService[Order Service]
Queue[Message Queue]
PaymentService[Payment Service]
NotificationService[Notification Service]
InventoryService[Inventory Service]
OrderService -->|OrderCreated| Queue
Queue -->|Consume| PaymentService
Queue -->|Consume| NotificationService
Queue -->|Consume| InventoryService
PaymentService -->|PaymentProcessed| Queue
Queue -->|Consume| OrderService
Queue -->|Consume| NotificationService11.2 Message Flow
sequenceDiagram
participant OrderService
participant Queue
participant PaymentService
participant EmailService
OrderService->>Queue: Publish: OrderCreated
Queue->>PaymentService: Deliver: OrderCreated
PaymentService->>PaymentService: Process Payment
PaymentService->>Queue: Publish: PaymentCompleted
Queue->>OrderService: Deliver: PaymentCompleted
Queue->>EmailService: Deliver: PaymentCompleted
EmailService->>EmailService: Send Confirmation Email---
12. Security Architecture
12.1 Security Layers
graph TB
Internet[Internet]
WAF[WAF + DDoS Protection]
TLS[TLS Termination]
AuthN[Authentication]
AuthZ[Authorization]
Validation[Input Validation]
Encryption[Data Encryption]
Audit[Audit Logging]
Internet --> WAF
WAF --> TLS
TLS --> AuthN
AuthN --> AuthZ
AuthZ --> Validation
Validation --> Encryption
Encryption --> Audit12.2 Authentication Flow
sequenceDiagram
participant User
participant Client
participant AuthServer
participant ResourceServer
User->>Client: Login
Client->>AuthServer: POST /oauth/token
AuthServer->>AuthServer: Validate Credentials
AuthServer-->>Client: Access Token + Refresh Token
Client->>ResourceServer: GET /resource<br/>Authorization: Bearer {token}
ResourceServer->>AuthServer: Validate Token
AuthServer-->>ResourceServer: Token Valid + Claims
ResourceServer-->>Client: Protected Resource---
13. Monitoring & Observability
13.1 Monitoring Architecture
graph TB
subgraph "Application"
App[Application]
Metrics[Metrics Exporter]
Logs[Log Shipper]
Traces[Trace Collector]
end
subgraph "Monitoring Stack"
Prometheus[Prometheus]
Loki[Loki]
Jaeger[Jaeger]
Grafana[Grafana]
end
subgraph "Alerting"
AlertManager[Alert Manager]
PagerDuty[PagerDuty]
Slack[Slack]
end
App --> Metrics
App --> Logs
App --> Traces
Metrics --> Prometheus
Logs --> Loki
Traces --> Jaeger
Prometheus --> Grafana
Loki --> Grafana
Jaeger --> Grafana
Prometheus --> AlertManager
AlertManager --> PagerDuty
AlertManager --> Slack13.2 Key Metrics
| Metric | Type | Threshold | Alert Level |
|---|---|---|---|
| Request Rate | Gauge | - | Info |
| Error Rate | Gauge | > 1% | Warning |
| Response Time (p99) | Histogram | > 500ms | Warning |
| CPU Usage | Gauge | > 80% | Critical |
| Memory Usage | Gauge | > 85% | Warning |
| Database Connections | Gauge | > 80% pool | Warning |
---
14. Disaster Recovery
14.1 Backup Strategy
graph TB
Production[(Production DB)]
Snapshot[Daily Snapshots]
Backup[(Backup Storage)]
DR[(DR Site)]
Production -->|Daily| Snapshot
Snapshot --> Backup
Production -.Replication.-> DR14.2 Recovery Procedures
| Scenario | RTO | RPO | Procedure |
|---|---|---|---|
| Service Outage | 5 minutes | 0 | Auto-failover to healthy instances |
| Database Failure | 1 hour | 15 minutes | Promote read replica |
| Region Failure | 4 hours | 1 hour | Failover to DR region |
| Data Corruption | 24 hours | 24 hours | Restore from backup |
---
15. Deployment Architecture
15.1 Infrastructure
graph TB
subgraph "Production - Region 1"
subgraph "AZ1"
LB1[Load Balancer]
App1[App Server]
DB1[(Database Primary)]
end
subgraph "AZ2"
App2[App Server]
DB2[(Database Standby)]
end
end
subgraph "Production - Region 2 (DR)"
subgraph "AZ3"
LB2[Load Balancer]
App3[App Server]
DB3[(Database Replica)]
end
end
DNS[Route 53]
DNS --> LB1
DNS -.Failover.-> LB2
LB1 --> App1
LB1 --> App2
App1 --> DB1
App2 --> DB1
DB1 -.Sync Replication.-> DB2
DB1 -.Async Replication.-> DB3---
16. Cost Optimization
16.1 Cost Breakdown
| Component | Monthly Cost | Optimization Opportunity |
|---|---|---|
| Compute | $10,000 | Reserved instances, spot instances |
| Database | $5,000 | Right-sizing, read replicas |
| Data Transfer | $2,000 | CDN, compression |
| Storage | $1,000 | Lifecycle policies, compression |
---
17. Trade-offs & Alternatives
17.1 Key Decisions
Decision 1: Eventual Consistency vs Strong Consistency
- Chosen: Eventual consistency
- Rationale: Better availability and performance
- Trade-off: Temporary inconsistency acceptable for this use case
- Alternative: Strong consistency - rejected due to performance impact
Decision 2: Monolith vs Microservices
- Chosen: Microservices
- Rationale: Independent scaling, fault isolation
- Trade-off: Increased operational complexity
- Alternative: Modular monolith - might revisit for smaller features
---
18. Future Enhancements
18.1 Roadmap
gantt
title System Evolution Roadmap
dateFormat YYYY-MM-DD
section Phase 1
Multi-region deployment :2025-01-01, 90d
Advanced caching :2025-02-01, 60d
section Phase 2
ML-based recommendations :2025-04-01, 120d
Real-time analytics :2025-05-01, 90d
section Phase 3
Global CDN expansion :2025-07-01, 60d
Edge computing :2025-08-01, 90d---
19. Appendices
A. Glossary
| Term | Definition |
|---|---|
| CDN | Content Delivery Network |
| WAF | Web Application Firewall |
| TTL | Time To Live |
B. References
FastAPI to Mermaid Diagrams
This directory contains examples of generating Mermaid diagrams from FastAPI applications.
Diagram Types
1. Architecture Diagram (from async structure and dependencies)
2. Deployment Diagram (from Docker/K8s configuration)
3. Sequence Diagram (from async endpoint handlers)
4. Activity Diagram (from async business logic)
Example Application Structure
app/
├── main.py # FastAPI app entry point
├── config.py # Pydantic settings
├── dependencies.py # Dependency injection
├── routers/
│ ├── __init__.py
│ ├── contacts.py # Contact endpoints
│ └── auth.py # Authentication endpoints
├── services/
│ ├── __init__.py
│ ├── contact_service.py # Business logic
│ └── auth_service.py # Auth logic
├── models/
│ ├── __init__.py
│ ├── contact.py # Pydantic models
│ └── user.py # User models
├── db/
│ ├── __init__.py
│ ├── database.py # SQLAlchemy async setup
│ └── repositories/
│ ├── contact_repo.py # Database operations
│ └── user_repo.py
└── core/
├── security.py # JWT, password hashing
└── cache.py # Redis cacheGenerated Diagrams
Architecture Diagram
From: Application structure, dependency injection, async patterns
graph TB
subgraph "FastAPI Application"
subgraph "API Layer"
Main[⚙️ FastAPI App<br/>main.py<br/>Async ASGI]
ContactRouter[🌐 Contact Router<br/>@router.get/post<br/>Async Endpoints]
AuthRouter[🔐 Auth Router<br/>@router.post<br/>JWT Auth]
end
subgraph "Service Layer"
ContactSvc[⚙️ Contact Service<br/>Async Business Logic<br/>Dependency Injection]
AuthSvc[🔐 Auth Service<br/>JWT Generation<br/>Password Hashing]
end
subgraph "Repository Layer"
ContactRepo[💾 Contact Repository<br/>SQLAlchemy Async<br/>CRUD Operations]
UserRepo[💾 User Repository<br/>SQLAlchemy Async]
end
subgraph "Dependencies"
DBDep[🔌 Database Dependency<br/>AsyncSession]
CacheDep[⚡ Cache Dependency<br/>Redis Client]
AuthDep[🔐 Auth Dependency<br/>OAuth2PasswordBearer]
end
subgraph "Core"
Security[🔐 Security<br/>bcrypt, JWT]
Cache[⚡ Redis Cache<br/>aioredis]
end
end
subgraph "External Services"
PostgreSQL[(💾 PostgreSQL<br/>AsyncPG Driver)]
Redis[(⚡ Redis<br/>Async Client)]
end
Main --> ContactRouter
Main --> AuthRouter
ContactRouter --> ContactSvc
AuthRouter --> AuthSvc
ContactSvc --> ContactRepo
AuthSvc --> UserRepo
ContactSvc --> CacheDep
ContactRouter --> AuthDep
ContactRouter --> DBDep
ContactRepo --> PostgreSQL
UserRepo --> PostgreSQL
CacheDep --> Redis
Cache --> Redis
Security -.provides.-> AuthSvc
Security -.provides.-> AuthDep
classDef api fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef service fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef repository fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef dependency fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
class Main,ContactRouter,AuthRouter api
class ContactSvc,AuthSvc service
class ContactRepo,UserRepo repository
class DBDep,CacheDep,AuthDep,Security,Cache dependency
class PostgreSQL,Redis databaseDeployment Diagram
From: Docker Compose, Kubernetes manifests, or cloud configuration
graph TB
subgraph "Docker Compose Deployment"
subgraph "Application Services"
FastAPI1[⚙️ fastapi-app-1<br/>uvicorn --workers 4<br/>Port: 8000<br/>replicas: 3]
FastAPI2[⚙️ fastapi-app-2<br/>uvicorn --workers 4<br/>Port: 8000]
FastAPI3[⚙️ fastapi-app-3<br/>uvicorn --workers 4<br/>Port: 8000]
end
subgraph "Reverse Proxy"
Nginx[🌐 nginx:alpine<br/>Port: 80<br/>Load Balancer]
end
subgraph "Data Services"
Postgres[(💾 postgres:15<br/>Port: 5432<br/>volumes: pgdata<br/>env: POSTGRES_DB)]
Redis[(⚡ redis:7-alpine<br/>Port: 6379<br/>maxmemory: 512mb)]
end
subgraph "Background Workers"
Celery1[⚙️ celery-worker-1<br/>--concurrency 4<br/>-Q default]
Celery2[⚙️ celery-worker-2<br/>--concurrency 4<br/>-Q high_priority]
end
subgraph "Message Broker"
RabbitMQ[🐰 rabbitmq:3-management<br/>Port: 5672, 15672<br/>env: RABBITMQ_DEFAULT_VHOST]
end
subgraph "Monitoring"
Prometheus[📊 prom/prometheus<br/>Port: 9090]
Grafana[📈 grafana/grafana<br/>Port: 3000]
end
end
Client[👤 Client] --> Nginx
Nginx --> FastAPI1
Nginx --> FastAPI2
Nginx --> FastAPI3
FastAPI1 --> Postgres
FastAPI2 --> Postgres
FastAPI3 --> Postgres
FastAPI1 --> Redis
FastAPI2 --> Redis
FastAPI3 --> Redis
FastAPI1 --> RabbitMQ
FastAPI2 --> RabbitMQ
FastAPI3 --> RabbitMQ
RabbitMQ --> Celery1
RabbitMQ --> Celery2
Celery1 --> Postgres
Celery2 --> Postgres
FastAPI1 --> Prometheus
FastAPI2 --> Prometheus
FastAPI3 --> Prometheus
Prometheus --> Grafana
classDef client fill:#FFE4B5,stroke:#333,stroke-width:2px,color:black
classDef frontend fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef backend fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef monitoring fill:#F0E68C,stroke:#333,stroke-width:2px,color:black
class Client client
class Nginx frontend
class FastAPI1,FastAPI2,FastAPI3,Celery1,Celery2 backend
class Postgres,Redis,RabbitMQ database
class Prometheus,Grafana monitoringSequence Diagram (Async Flow)
From: FastAPI async endpoint handlers
# routers/contacts.py
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
router = APIRouter()
@router.post("/contacts", response_model=ContactResponse)
async def create_contact(
contact: ContactCreate,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
cache: Redis = Depends(get_cache)
):
# Create contact with async operations
service = ContactService(db, cache)
new_contact = await service.create_contact(contact, current_user.id)
return new_contact
# services/contact_service.py
class ContactService:
def __init__(self, db: AsyncSession, cache: Redis):
self.db = db
self.cache = cache
self.repo = ContactRepository(db)
async def create_contact(self, contact_data: ContactCreate, user_id: int):
# Check cache
cached = await self.cache.get(f"user:{user_id}:contacts:count")
# Create in database
contact = await self.repo.create(contact_data, user_id)
# Invalidate cache
await self.cache.delete(f"user:{user_id}:contacts")
# Publish event (background task)
await self._publish_event("contact.created", contact.id)
return contactGenerated Sequence Diagram:
sequenceDiagram
participant Client as 👤 Client
participant Router as 🌐 Contact Router
participant Auth as 🔐 Auth Middleware
participant Service as ⚙️ Contact Service
participant Cache as ⚡ Redis Cache
participant Repo as 💾 Contact Repository
participant DB as 💾 PostgreSQL
participant Queue as 📬 Message Queue
Client->>+Router: POST /api/contacts<br/>{ContactCreate}
Note over Router: @router.post<br/>async def create_contact()
Router->>+Auth: await get_current_user(token)
Auth->>Auth: Verify JWT Token
Auth-->>-Router: User object
Router->>+Service: await create_contact(data, user_id)
Note over Service: Async Business Logic
Service->>+Cache: await cache.get(key)
Cache-->>-Service: None (cache miss)
Service->>+Repo: await repo.create(contact)
Repo->>+DB: async with session.begin():<br/>INSERT INTO contacts
DB-->>-Repo: Contact created
Repo-->>-Service: Contact object
Service->>+Cache: await cache.delete(key)
Cache-->>-Service: OK
Service->>+Queue: await publish_event()<br/>(background task)
Queue-->>-Service: Queued
Service-->>-Router: Contact object
Router-->>-Client: 201 Created<br/>{ContactResponse}
Note over Queue: Async background<br/>processing continues
classDef client fill:#FFE4B5,stroke:#333,stroke-width:2px,color:black
classDef api fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef service fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblueActivity Diagram (Async Workflow)
From: Async business logic with error handling
# services/contact_service.py
async def update_contact(self, contact_id: int, data: ContactUpdate, user_id: int):
# Fetch existing contact
existing = await self.repo.get_by_id(contact_id)
if not existing:
raise HTTPException(404, "Contact not found")
# Check ownership
if existing.user_id != user_id:
raise HTTPException(403, "Not authorized")
# Check email uniqueness if changed
if data.email and data.email != existing.email:
email_exists = await self.repo.exists_by_email(data.email, user_id)
if email_exists:
raise HTTPException(400, "Email already in use")
# Update in database (transaction)
async with self.db.begin():
updated = await self.repo.update(contact_id, data)
# Invalidate cache
await self.cache.delete(f"contact:{contact_id}")
# Create audit log
await self.audit_repo.create_log(
user_id=user_id,
action="update_contact",
contact_id=contact_id
)
# Publish event (async, non-blocking)
asyncio.create_task(
self.event_publisher.publish("contact.updated", updated.id)
)
return updatedGenerated Activity Diagram:
flowchart TD
Start([📥 Update Contact Request]) --> FetchContact[💾 await repo.get_by_id]
FetchContact --> Exists{Contact Exists?}
Exists -->|No| NotFound[❌ HTTPException 404<br/>Contact not found]
NotFound --> End1([End])
Exists -->|Yes| CheckOwner{Owner Match?}
CheckOwner -->|No| Forbidden[❌ HTTPException 403<br/>Not authorized]
Forbidden --> End2([End])
CheckOwner -->|Yes| EmailChanged{Email Changed?}
EmailChanged -->|No| BeginTx[🔄 Begin Transaction<br/>async with db.begin]
EmailChanged -->|Yes| CheckEmail[🔍 await exists_by_email]
CheckEmail --> EmailExists{Email In Use?}
EmailExists -->|Yes| BadRequest[❌ HTTPException 400<br/>Email already in use]
BadRequest --> End3([End])
EmailExists -->|No| BeginTx
BeginTx --> UpdateDB[💾 await repo.update]
UpdateDB --> UpdateSuccess{Update Success?}
UpdateSuccess -->|No| Rollback[🔄 Rollback Transaction]
Rollback --> Error[❌ Database Error]
Error --> End4([End])
UpdateSuccess -->|Yes| InvalidateCache[⚡ await cache.delete]
InvalidateCache --> CreateAudit[📝 await audit_repo.create_log]
CreateAudit --> CommitTx[✅ Commit Transaction]
CommitTx --> PublishEvent[📨 asyncio.create_task<br/>publish event]
PublishEvent --> Success([✅ Return Updated Contact])
classDef startEnd fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef process fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef decision fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef error fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:black
classDef async fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
class Start,Success,End1,End2,End3,End4 startEnd
class FetchContact,UpdateDB,InvalidateCache,CreateAudit,CheckEmail process
class Exists,CheckOwner,EmailChanged,EmailExists,UpdateSuccess decision
class NotFound,Forbidden,BadRequest,Rollback,Error error
class BeginTx,CommitTx,PublishEvent asyncAsync Patterns
Dependency Injection with FastAPI
# dependencies.py
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession
from redis.asyncio import Redis
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
async def get_cache() -> Redis:
return await get_redis_client()
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db)
) -> User:
# Verify JWT and fetch user
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user = await user_repo.get_by_id(payload["user_id"])
return userDependency Injection Diagram:
graph TB
subgraph "FastAPI Dependency Injection"
Endpoint[🌐 Endpoint Handler<br/>async def create_contact()]
subgraph "Injected Dependencies"
DB[🔌 get_db()<br/>yields AsyncSession]
Cache[🔌 get_cache()<br/>returns Redis]
Auth[🔌 get_current_user()<br/>returns User]
end
subgraph "Resolved Dependencies"
DBSession[(💾 AsyncSession<br/>SQLAlchemy)]
RedisClient[(⚡ Redis Client<br/>aioredis)]
UserObj[👤 User Object<br/>from JWT]
end
end
Endpoint --> DB
Endpoint --> Cache
Endpoint --> Auth
DB --> DBSession
Cache --> RedisClient
Auth --> DBSession
Auth --> UserObj
classDef endpoint fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef dependency fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef resolved fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
class Endpoint endpoint
class DB,Cache,Auth dependency
class DBSession,RedisClient,UserObj resolvedBackground Tasks with Celery
# tasks.py (Celery)
from celery import Celery
celery_app = Celery(
"tasks",
broker="amqp://rabbitmq:5672",
backend="redis://redis:6379/0"
)
@celery_app.task
def send_welcome_email(user_id: int):
# Send email asynchronously
user = get_user(user_id)
send_email(user.email, "Welcome!", template="welcome")
@celery_app.task
def generate_report(contact_ids: list[int]):
# Long-running report generation
contacts = get_contacts(contact_ids)
report = create_pdf_report(contacts)
store_in_s3(report)
# In FastAPI endpoint
from fastapi import BackgroundTasks
@router.post("/contacts/batch-export")
async def batch_export(
contact_ids: list[int],
background_tasks: BackgroundTasks
):
# Queue background task
task = generate_report.delay(contact_ids)
return {"task_id": task.id, "status": "queued"}Background Task Diagram:
flowchart TD
API[🌐 FastAPI Endpoint] --> Queue[📬 RabbitMQ Queue]
Queue --> Worker1[⚙️ Celery Worker 1]
Queue --> Worker2[⚙️ Celery Worker 2]
Worker1 --> Task1[📧 Send Email Task]
Worker1 --> Task2[📊 Generate Report Task]
Worker2 --> Task3[📧 Send Email Task]
Task1 --> SMTP[📨 SMTP Server]
Task2 --> S3[📦 S3 Storage]
Task3 --> SMTP
Result[💾 Redis Backend] -.stores.-> Task1
Result -.stores.-> Task2
Result -.stores.-> Task3
classDef api fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef queue fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef worker fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef storage fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
class API api
class Queue queue
class Worker1,Worker2,Task1,Task2,Task3 worker
class Result,S3,SMTP storageConfiguration Mapping
From Pydantic Settings
# config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# Database
DATABASE_URL: str = "postgresql+asyncpg://user:pass@localhost/db"
DATABASE_POOL_SIZE: int = 10
# Redis
REDIS_URL: str = "redis://localhost:6379/0"
REDIS_MAX_CONNECTIONS: int = 50
# Security
SECRET_KEY: str
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
# Celery
CELERY_BROKER_URL: str = "amqp://rabbitmq:5672"
CELERY_RESULT_BACKEND: str = "redis://localhost:6379/0"
# Monitoring
PROMETHEUS_PORT: int = 9090
LOG_LEVEL: str = "INFO"
class Config:
env_file = ".env"Configuration Diagram:
graph TB
subgraph "FastAPI Configuration"
Settings[⚙️ Pydantic Settings<br/>BaseSettings]
subgraph "Database Config"
DBUrl[💾 DATABASE_URL<br/>postgresql+asyncpg://...]
PoolSize[💾 POOL_SIZE: 10]
end
subgraph "Cache Config"
RedisUrl[⚡ REDIS_URL<br/>redis://localhost:6379]
MaxConn[⚡ MAX_CONNECTIONS: 50]
end
subgraph "Security Config"
SecretKey[🔐 SECRET_KEY<br/>from env]
Algorithm[🔐 ALGORITHM: HS256]
TokenExp[🔐 TOKEN_EXPIRE: 30min]
end
subgraph "Worker Config"
BrokerUrl[📬 CELERY_BROKER<br/>amqp://rabbitmq:5672]
Backend[💾 RESULT_BACKEND<br/>redis://...]
end
subgraph "Monitoring Config"
PrometheusPort[📊 PROMETHEUS_PORT: 9090]
LogLevel[📝 LOG_LEVEL: INFO]
end
end
Settings --> DBUrl
Settings --> PoolSize
Settings --> RedisUrl
Settings --> MaxConn
Settings --> SecretKey
Settings --> Algorithm
Settings --> TokenExp
Settings --> BrokerUrl
Settings --> Backend
Settings --> PrometheusPort
Settings --> LogLevel
DBUrl --> PostgreSQL[(💾 PostgreSQL)]
RedisUrl --> Redis[(⚡ Redis)]
BrokerUrl --> RabbitMQ[🐰 RabbitMQ]
classDef config fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef security fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:black
class Settings,DBUrl,PoolSize,RedisUrl,MaxConn,BrokerUrl,Backend,PrometheusPort,LogLevel config
class PostgreSQL,Redis,RabbitMQ database
class SecretKey,Algorithm,TokenExp securityAsync SQLAlchemy Pattern
# db/database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
engine = create_async_engine(
DATABASE_URL,
echo=True,
pool_size=10,
max_overflow=20
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False
)
# Usage in repository
class ContactRepository:
def __init__(self, db: AsyncSession):
self.db = db
async def create(self, contact: ContactCreate) -> Contact:
async with self.db.begin():
db_contact = Contact(**contact.dict())
self.db.add(db_contact)
await self.db.flush()
await self.db.refresh(db_contact)
return db_contactKubernetes Deployment (Alternative to Docker Compose)
See deployment-diagrams.md for full Kubernetes microservices pattern with FastAPI.
Generating Diagrams
Automated Generation
1. Architecture Diagram: Analyze file structure, decorators, dependency injection 2. Deployment Diagram: Extract from docker-compose.yml or K8s manifests 3. Sequence Diagram: Trace async function calls from endpoints 4. Activity Diagram: Document business logic flows from service methods
Manual Creation Guidelines
1. Use async/await annotations in diagrams 2. Show dependency injection clearly 3. Indicate background tasks with async symbols 4. Document transaction boundaries
See Also
- Spring Boot Example - Java synchronous patterns
- React Example - Frontend component architecture
- Python ETL Example - Data pipeline patterns
Node.js/Express to Mermaid Diagrams
This directory contains examples of generating Mermaid diagrams from Node.js/Express applications.
Diagram Types
1. Architecture Diagram (from layered structure)
2. Middleware Chain (from Express middleware)
3. Deployment Diagram (from Docker/PM2 setup)
4. Sequence Diagram (from async request flow)
Example Application Structure
src/
├── server.js # App entry point
├── app.js # Express app configuration
├── config/
│ ├── database.js # MongoDB/PostgreSQL config
│ ├── redis.js # Redis client setup
│ └── environment.js # Environment variables
├── routes/
│ ├── index.js # Route registry
│ ├── auth.routes.js # Authentication routes
│ ├── user.routes.js # User CRUD routes
│ └── product.routes.js # Product routes
├── controllers/
│ ├── auth.controller.js # Auth business logic
│ ├── user.controller.js # User operations
│ └── product.controller.js
├── services/
│ ├── auth.service.js # Auth service layer
│ ├── user.service.js # User service layer
│ ├── email.service.js # Email notifications
│ └── cache.service.js # Redis caching
├── models/
│ ├── user.model.js # Mongoose/Sequelize model
│ ├── product.model.js
│ └── order.model.js
├── middleware/
│ ├── auth.middleware.js # JWT validation
│ ├── validator.middleware.js # Request validation
│ ├── rateLimit.middleware.js # Rate limiting
│ ├── error.middleware.js # Error handler
│ └── logger.middleware.js # Request logging
├── utils/
│ ├── jwt.utils.js # JWT helpers
│ ├── hash.utils.js # Bcrypt helpers
│ └── logger.js # Winston logger
└── tests/
├── unit/
└── integration/Generated Diagrams
Express Architecture Diagram
From: Three-layer architecture pattern
graph TB
subgraph "Node.js Express Application"
subgraph "Entry Point"
Server[⚙️ server.js<br/>HTTP Server<br/>Port: 3000]
App[⚙️ app.js<br/>Express App<br/>Middleware Setup]
end
subgraph "Route Layer"
Router[🌐 Route Registry<br/>index.js]
AuthRoutes[🔐 Auth Routes<br/>/api/auth/*]
UserRoutes[👤 User Routes<br/>/api/users/*]
ProductRoutes[📦 Product Routes<br/>/api/products/*]
end
subgraph "Controller Layer"
AuthController[⚙️ Auth Controller<br/>login, signup, refresh]
UserController[⚙️ User Controller<br/>CRUD operations]
ProductController[⚙️ Product Controller<br/>Inventory management]
end
subgraph "Service Layer"
AuthService[⚙️ Auth Service<br/>JWT generation<br/>Token validation]
UserService[⚙️ User Service<br/>Business logic<br/>Validation rules]
EmailService[📧 Email Service<br/>Nodemailer<br/>Templates]
CacheService[⚡ Cache Service<br/>Redis client<br/>Get/Set/Delete]
end
subgraph "Model Layer"
UserModel[💾 User Model<br/>Mongoose Schema<br/>Hooks & Virtuals]
ProductModel[💾 Product Model<br/>Mongoose Schema]
OrderModel[💾 Order Model<br/>Mongoose Schema]
end
subgraph "Middleware Chain"
AuthMW[🔐 Auth Middleware<br/>JWT validation<br/>User injection]
ValidatorMW[✓ Validator<br/>Joi/express-validator]
RateLimitMW[⏱️ Rate Limiter<br/>express-rate-limit]
ErrorMW[❌ Error Handler<br/>Global catch]
LoggerMW[📝 Logger<br/>Morgan + Winston]
end
subgraph "External Services"
MongoDB[(💾 MongoDB<br/>Database<br/>Replica Set)]
Redis[(⚡ Redis<br/>Cache & Sessions<br/>Pub/Sub)]
SMTP[📧 SMTP Server<br/>SendGrid/SES]
end
end
Server --> App
App --> LoggerMW
LoggerMW --> RateLimitMW
RateLimitMW --> Router
Router --> AuthRoutes
Router --> UserRoutes
Router --> ProductRoutes
AuthRoutes --> AuthMW
UserRoutes --> AuthMW
ProductRoutes --> AuthMW
AuthMW --> ValidatorMW
ValidatorMW --> AuthController
ValidatorMW --> UserController
ValidatorMW --> ProductController
AuthController --> AuthService
UserController --> UserService
ProductController --> UserService
UserService --> UserModel
ProductController --> ProductModel
AuthService --> CacheService
UserService --> EmailService
UserModel --> MongoDB
ProductModel --> MongoDB
OrderModel --> MongoDB
CacheService --> Redis
EmailService --> SMTP
ErrorMW -.catches.-> AuthController
ErrorMW -.catches.-> UserController
ErrorMW -.catches.-> ProductController
classDef entry fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef route fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef controller fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef service fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef model fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef middleware fill:#F0E68C,stroke:#333,stroke-width:2px,color:black
classDef external fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:black
class Server,App entry
class Router,AuthRoutes,UserRoutes,ProductRoutes route
class AuthController,UserController,ProductController controller
class AuthService,UserService,EmailService,CacheService service
class UserModel,ProductModel,OrderModel model
class AuthMW,ValidatorMW,RateLimitMW,ErrorMW,LoggerMW middleware
class MongoDB,Redis,SMTP externalMiddleware Chain Flow
From: Express middleware stack
// app.js
const express = require('express');
const app = express();
// Global middleware (applied to all routes)
app.use(helmet()); // Security headers
app.use(cors()); // CORS policy
app.use(morgan('combined')); // HTTP logging
app.use(express.json()); // Body parser
app.use(express.urlencoded({ extended: true }));
// Custom middleware
app.use(requestId()); // Add request ID
app.use(rateLimiter); // Rate limiting
// Routes with route-specific middleware
app.use('/api/auth', authRoutes);
app.use('/api/users', authenticate, userRoutes);
app.use('/api/products', authenticate, authorize('admin'), productRoutes);
// Error handling (must be last)
app.use(notFoundHandler);
app.use(errorHandler);Generated Middleware Chain Diagram:
flowchart TD
Request([📥 HTTP Request]) --> Helmet[🛡️ Helmet<br/>Security Headers<br/>X-Frame-Options, CSP]
Helmet --> CORS[🌐 CORS<br/>Access-Control-*<br/>Preflight handling]
CORS --> Morgan[📝 Morgan<br/>HTTP Logging<br/>combined format]
Morgan --> BodyParser[📄 Body Parser<br/>express.json()<br/>express.urlencoded()]
BodyParser --> RequestID[🏷️ Request ID<br/>Add unique ID<br/>X-Request-ID header]
RequestID --> RateLimit{⏱️ Rate Limiter<br/>Check limit}
RateLimit -->|Exceeded| RateLimitError[❌ 429 Too Many Requests]
RateLimitError --> ErrorHandler
RateLimit -->|OK| Router{🗺️ Route Matching}
Router -->|/api/auth| AuthRoute[🔐 Auth Routes<br/>No auth required]
Router -->|/api/users| AuthMiddleware[🔐 Authenticate<br/>Verify JWT]
Router -->|/api/products| AuthMiddleware2[🔐 Authenticate<br/>Verify JWT]
Router -->|No match| NotFound[❌ 404 Not Found]
AuthRoute --> Controller1[⚙️ Auth Controller]
AuthMiddleware --> UserCheck{Valid Token?}
UserCheck -->|No| AuthError[❌ 401 Unauthorized]
UserCheck -->|Yes| UserController[⚙️ User Controller]
AuthMiddleware2 --> AdminCheck{Admin Role?}
AdminCheck -->|No| ForbiddenError[❌ 403 Forbidden]
AdminCheck -->|Yes| Authorize[✓ Authorize<br/>Check admin role]
Authorize --> ProductController[⚙️ Product Controller]
Controller1 --> Success{Success?}
UserController --> Success
ProductController --> Success
Success -->|Yes| Response([📤 HTTP Response])
Success -->|No| ControllerError[❌ Application Error]
AuthError --> ErrorHandler[❌ Error Handler<br/>Format error response<br/>Log error]
ForbiddenError --> ErrorHandler
ControllerError --> ErrorHandler
NotFound --> ErrorHandler
ErrorHandler --> ErrorResponse([📤 Error Response])
classDef middleware fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef decision fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef controller fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef error fill:#FFB6C1,stroke:#DC143C,stroke-width:2px,color:black
classDef success fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
class Helmet,CORS,Morgan,BodyParser,RequestID,AuthMiddleware,AuthMiddleware2,Authorize middleware
class RateLimit,Router,UserCheck,AdminCheck,Success decision
class Controller1,UserController,ProductController controller
class RateLimitError,AuthError,ForbiddenError,ControllerError,NotFound,ErrorHandler error
class Request,Response,ErrorResponse successSequence Diagram (Async Request Flow)
From: Async/await controller and service calls
// controllers/user.controller.js
const userController = {
async createUser(req, res, next) {
try {
// 1. Validate request
const { error, value } = userSchema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.message });
}
// 2. Check if user exists
const existing = await User.findOne({ email: value.email });
if (existing) {
return res.status(409).json({ error: 'User already exists' });
}
// 3. Hash password
const hashedPassword = await bcrypt.hash(value.password, 10);
// 4. Create user
const user = await User.create({
...value,
password: hashedPassword
});
// 5. Cache user
await cacheService.set(`user:${user.id}`, user, 3600);
// 6. Send welcome email (async, non-blocking)
emailService.sendWelcome(user.email).catch(err => {
logger.error('Failed to send welcome email', err);
});
// 7. Return response
res.status(201).json({
id: user.id,
email: user.email,
createdAt: user.createdAt
});
} catch (error) {
next(error);
}
}
};Generated Sequence Diagram:
sequenceDiagram
participant Client as 👤 Client
participant MW as 🔐 Middleware Chain
participant Ctrl as ⚙️ User Controller
participant Validator as ✓ Joi Validator
participant Model as 💾 User Model
participant MongoDB as 💾 MongoDB
participant Cache as ⚡ Redis
participant Email as 📧 Email Service
participant SMTP as 📧 SMTP Server
Client->>+MW: POST /api/users<br/>{email, password}
Note over MW: Auth, Rate Limit,<br/>Body Parser
MW->>+Ctrl: createUser(req, res, next)
Note over Ctrl: async function
Ctrl->>+Validator: validate(req.body)
Validator-->>-Ctrl: {error: null, value: data}
Ctrl->>+Model: findOne({email})
Model->>+MongoDB: db.users.findOne()
MongoDB-->>-Model: null (not found)
Model-->>-Ctrl: null
Ctrl->>Ctrl: await bcrypt.hash(password)
Note over Ctrl: Hash password<br/>10 rounds
Ctrl->>+Model: create(userData)
Model->>+MongoDB: db.users.insertOne()
MongoDB-->>-Model: {_id, email, ...}
Model-->>-Ctrl: User document
Ctrl->>+Cache: set('user:123', user, 3600)
Cache-->>-Ctrl: OK
Ctrl->>Email: sendWelcome(email)<br/>(fire and forget)
Note over Email: Async,<br/>non-blocking
Ctrl-->>-MW: res.status(201).json(user)
MW-->>-Client: 201 Created<br/>{id, email, createdAt}
Note over Email,SMTP: Background<br/>processing continues
Email->>+SMTP: Send email via Nodemailer
SMTP-->>-Email: Email sent
classDef client fill:#FFE4B5,stroke:#333,stroke-width:2px,color:black
classDef middleware fill:#F0E68C,stroke:#333,stroke-width:2px,color:black
classDef controller fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef database fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblueDeployment Diagram (PM2 Cluster + Docker)
From: ecosystem.config.js, Dockerfile, docker-compose.yml
graph TB
subgraph "Production Deployment"
subgraph "Load Balancer"
NGINX[🌐 NGINX<br/>Reverse Proxy<br/>SSL Termination<br/>Port: 80, 443]
end
subgraph "Application Tier (PM2 Cluster)"
PM2[⚙️ PM2 Process Manager<br/>Cluster Mode<br/>4 instances<br/>Auto-restart]
App1[⚙️ Node.js Instance 1<br/>Port: 3000<br/>PID: 1234]
App2[⚙️ Node.js Instance 2<br/>Port: 3001<br/>PID: 1235]
App3[⚙️ Node.js Instance 3<br/>Port: 3002<br/>PID: 1236]
App4[⚙️ Node.js Instance 4<br/>Port: 3003<br/>PID: 1237]
end
subgraph "Data Layer"
MongoDB[(💾 MongoDB<br/>Replica Set<br/>3 nodes<br/>27017)]
Redis[(⚡ Redis<br/>Master-Slave<br/>6379<br/>maxmemory: 2GB)]
end
subgraph "Background Workers"
BullQueue[📬 Bull Queue<br/>Redis-backed<br/>Job processing]
Worker1[⚙️ Worker 1<br/>Email jobs]
Worker2[⚙️ Worker 2<br/>Report jobs]
end
subgraph "Monitoring"
PM2Plus[📊 PM2 Plus<br/>Monitoring<br/>Metrics]
Prometheus[📊 Prometheus<br/>prom-client<br/>Port: 9090]
Grafana[📈 Grafana<br/>Dashboards<br/>Port: 3001]
end
subgraph "Logging"
Winston[📝 Winston Logger<br/>File + Console<br/>Error tracking]
LogStash[📝 LogStash<br/>Log aggregation]
Elastic[📊 Elasticsearch<br/>Log storage]
end
end
Client[👤 Client] --> NGINX
NGINX --> PM2
PM2 -.manages.-> App1
PM2 -.manages.-> App2
PM2 -.manages.-> App3
PM2 -.manages.-> App4
App1 --> MongoDB
App2 --> MongoDB
App3 --> MongoDB
App4 --> MongoDB
App1 --> Redis
App2 --> Redis
App3 --> Redis
App4 --> Redis
App1 --> BullQueue
App2 --> BullQueue
BullQueue --> Worker1
BullQueue --> Worker2
PM2 --> PM2Plus
App1 --> Prometheus
App2 --> Prometheus
Prometheus --> Grafana
App1 --> Winston
App2 --> Winston
Winston --> LogStash
LogStash --> Elastic
classDef loadbalancer fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblue
classDef app fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef data fill:#E6E6FA,stroke:#333,stroke-width:2px,color:darkblue
classDef worker fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef monitoring fill:#F0E68C,stroke:#333,stroke-width:2px,color:black
class NGINX loadbalancer
class PM2,App1,App2,App3,App4 app
class MongoDB,Redis data
class BullQueue,Worker1,Worker2 worker
class PM2Plus,Prometheus,Grafana,Winston,LogStash,Elastic monitoringNode.js Patterns
1. Error Handling Pattern
// middleware/error.middleware.js
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
const errorHandler = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (process.env.NODE_ENV === 'development') {
res.status(err.statusCode).json({
status: err.status,
error: err,
message: err.message,
stack: err.stack
});
} else {
// Production: don't leak error details
if (err.isOperational) {
res.status(err.statusCode).json({
status: err.status,
message: err.message
});
} else {
// Programming errors: log and send generic message
console.error('ERROR 💥', err);
res.status(500).json({
status: 'error',
message: 'Something went wrong'
});
}
}
};
// Usage
app.get('/users/:id', async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
throw new AppError('User not found', 404);
}
res.json(user);
} catch (error) {
next(error);
}
});2. Async Handler Wrapper
// utils/async-handler.js
const asyncHandler = (fn) => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
// Usage - cleaner controllers
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.find();
res.json(users);
// No try-catch needed!
}));3. Service Layer Pattern
// services/user.service.js
class UserService {
constructor() {
this.cache = new CacheService();
this.email = new EmailService();
}
async createUser(userData) {
// Business logic encapsulated in service
const existing = await User.findOne({ email: userData.email });
if (existing) {
throw new AppError('User already exists', 409);
}
const hashedPassword = await bcrypt.hash(userData.password, 10);
const user = await User.create({
...userData,
password: hashedPassword
});
// Cache user
await this.cache.set(`user:${user.id}`, user, 3600);
// Send welcome email (async)
this.email.sendWelcome(user.email).catch(console.error);
return user;
}
async getUserById(id, useCache = true) {
if (useCache) {
const cached = await this.cache.get(`user:${id}`);
if (cached) return cached;
}
const user = await User.findById(id);
if (!user) {
throw new AppError('User not found', 404);
}
await this.cache.set(`user:${id}`, user, 3600);
return user;
}
}
module.exports = new UserService();4. Dependency Injection Pattern
// config/container.js (using awilix)
const { createContainer, asClass, asFunction, asValue } = require('awilix');
const container = createContainer();
container.register({
// Services
userService: asClass(UserService).singleton(),
authService: asClass(AuthService).singleton(),
emailService: asClass(EmailService).singleton(),
// Repositories
userRepository: asClass(UserRepository).singleton(),
// External clients
database: asFunction(createDatabase).singleton(),
redis: asFunction(createRedisClient).singleton(),
// Config
config: asValue(require('./environment'))
});
// Usage in controller
class UserController {
constructor({ userService, authService }) {
this.userService = userService;
this.authService = authService;
}
async createUser(req, res) {
const user = await this.userService.createUser(req.body);
res.status(201).json(user);
}
}
module.exports = container.resolve('userController');5. Background Job Processing with Bull
// services/queue.service.js
const Queue = require('bull');
const emailQueue = new Queue('email', {
redis: { host: 'localhost', port: 6379 }
});
// Producer: Add jobs to queue
exports.sendEmail = async (to, subject, body) => {
await emailQueue.add({
to,
subject,
body
}, {
attempts: 3,
backoff: {
type: 'exponential',
delay: 2000
}
});
};
// Consumer: Process jobs
emailQueue.process(async (job) => {
const { to, subject, body } = job.data;
await transporter.sendMail({
from: process.env.EMAIL_FROM,
to,
subject,
html: body
});
job.progress(100);
});
// Event handlers
emailQueue.on('completed', (job) => {
console.log(`Email job ${job.id} completed`);
});
emailQueue.on('failed', (job, err) => {
console.error(`Email job ${job.id} failed:`, err);
});PM2 Ecosystem Configuration
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'api',
script: './src/server.js',
instances: 4,
exec_mode: 'cluster',
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
},
{
name: 'worker',
script: './src/worker.js',
instances: 2,
exec_mode: 'cluster',
watch: false,
env: {
NODE_ENV: 'production'
}
}
]
};
// Start: pm2 start ecosystem.config.js
// Monitor: pm2 monit
// Logs: pm2 logsDocker Deployment
# Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
USER node
CMD ["node", "src/server.js"]See Also
- FastAPI Example - Python async patterns
- Spring Boot Example - Java enterprise patterns
- React Example - Frontend patterns
- Python ETL Example - Data pipeline patterns
High-Contrast Mermaid Diagram Update ✅
Date: 2025-11-07 Skill Updated: design-doc-mermaid Version: 1.1 (High-Contrast)
---
Summary
The design-doc-mermaid skill has been updated with MANDATORY high-contrast requirements for all Mermaid diagrams to ensure accessibility and readability.
---
Changes Made
1. SKILL.md Updates
Location: /Users/richardhightower/.claude/skills/design-doc-mermaid/SKILL.md
Section 4: "Use Consistent Styling" → "Use Consistent Styling with High Contrast"
Added:
- CRITICAL heading emphasizing mandatory high-contrast colors
- Contrast rules: light backgrounds → dark text, dark backgrounds → light text
- ✅ Good examples with explicit
color:properties - ❌ Bad examples showing missing
color:properties - High-Contrast Color Combinations Table with 9 common use cases
Key Example:
classDef primaryService fill:#90EE90,stroke:#333,stroke-width:2px,color:darkgreen
classDef secondaryService fill:#FFD700,stroke:#333,stroke-width:2px,color:black
classDef database fill:#87CEEB,stroke:#333,stroke-width:2px,color:darkblueSection 6: New "Ensure Accessibility with High-Contrast Colors"
Added:
- MANDATORY requirement for
color:property in allclassDefstyles - Quick test: "Can you easily read the text on the background color?"
- ✅ Correct vs ❌ Incorrect examples
---
2. mermaid-diagram-guide.md Updates
Location: /Users/richardhightower/.claude/skills/design-doc-mermaid/references/mermaid-diagram-guide.md
Color Coding Section → "Color Coding with High Contrast"
Added:
- CRITICAL heading emphasizing accessibility requirement
- ✅ Correct examples using both
styleandclassDefwithcolor:properties - ❌ Incorrect examples showing missing
color:properties - High-Contrast Color Palette Table with 8 states (Normal, Success, Warning, Error, Info, Public, Private, Dark)
Table Added:
| State | Background Fill | Text Color | Stroke |
|---|---|---|---|
| Normal | #F0F0F0 | color:black | #333 |
| Success | #90EE90 | color:darkgreen | #2E7D2E |
| Warning | #FFD700 | color:black | #B8860B |
| Error | #FFB6C1 | color:black | #DC143C |
| Info | #87CEEB | color:darkblue | #4682B4 |
| Public | #FFE4B5 | color:black | #FF8C00 |
| Private | #E6E6FA | color:darkblue | #8A2BE2 |
| Dark | #2C3E50 | color:white | #34495E |
Best Practices Section 6: New "CRITICAL - Ensure High-Contrast Accessibility"
Added:
- MANDATORY heading for ALL diagrams
- Complete example with 3 components using different contrast styles
- Quick Accessibility Test (3 questions)
- Common Mistakes to Avoid (3 ❌ examples)
- Always Include checklist (3 ✅ requirements)
Syntax Validation Checklist
Added 3 new checklist items:
- [ ] All `classDef` statements include `color:` property for high contrast
- [ ] All `style` statements include `color:` property for high contrast
- [ ] Text is readable on all background colors (accessibility test)
---
Impact
Before Update
- Mermaid diagrams could have poor contrast
- No guidance on text color selection
- Risk of unreadable diagrams
- WCAG accessibility issues
After Update
- All diagrams MUST have high-contrast colors
- Clear guidance with good/bad examples
- Explicit
color:property requirement - WCAG 2.1 Level AA compliant
- Readable in print and grayscale
---
Examples
Before (Poor Contrast)
graph LR
A[Component]
B[Service]
classDef myStyle fill:#FFD700,stroke:#333,stroke-width:2px
%% Missing color: property - may be unreadable!
class A myStyleAfter (High Contrast)
graph LR
A[Component]
B[Service]
classDef myStyle fill:#FFD700,stroke:#333,stroke-width:2px,color:black
%% Explicit dark text on light background - readable!
class A myStyle---
Skill Usage
When users invoke the design-doc-mermaid skill, they will now automatically receive:
1. Templates with high-contrast classDef examples 2. Reference guide with accessibility requirements 3. Validation checklist including contrast verification 4. Best practices emphasizing mandatory high-contrast colors
Agent Behavior:
- Will include
color:property in ALL generatedclassDefstatements - Will use high-contrast color combinations from provided palette
- Will validate diagrams against accessibility checklist
---
Validation
To verify high-contrast compliance in any diagram:
1. Check for `color:` property: Every classDef or style statement must include it 2. Visual test: Can you easily read the text on each background? 3. Grayscale test: Would it be readable if printed in black and white?
Quick grep check:
grep "classDef" yourfile.md | grep -v "color:"
# If this returns results, contrast is NOT ensured!---
Related Updates
This update aligns with parallel updates to:
/Users/richardhightower/articles/CLAUDE.md(Phase 3: Diagram Creation)- All article Mermaid diagrams now use high-contrast colors
Consistency: The same high-contrast requirements and examples are now documented across: 1. Article workflow (CLAUDE.md) 2. Design-doc skill (SKILL.md) 3. Mermaid reference guide (mermaid-diagram-guide.md)
---
Files Updated
1. ✅ SKILL.md - Added Section 4 high-contrast requirements, Section 6 accessibility 2. ✅ references/mermaid-diagram-guide.md - Updated Color Coding section, added Best Practice #6, updated checklist 3. ✅ HIGH_CONTRAST_UPDATE.md (this file) - Documentation of all changes
---
Future Enforcement
All Mermaid diagrams generated by this skill will now:
- Include explicit
color:properties in allclassDefstatements - Use high-contrast color combinations from the provided palette
- Pass the 3-question accessibility test
- Be validated against the enhanced checklist
Users will be guided to:
- Reference the high-contrast color palette table
- Test readability before finalizing diagrams
- Use the syntax validation checklist with accessibility items
---
Status: ✅ Skill updated with mandatory high-contrast requirements Version: 1.1 (High-Contrast) Last Updated: 2025-11-07
Related skills
How it compares
Choose design-doc-mermaid when agents should infer diagrams from code or prose; use raw Mermaid snippets for hand-authored one-off charts.
FAQ
Which diagram types does design-doc-mermaid support?
design-doc-mermaid produces Mermaid activity, deployment, sequence, and architecture diagrams. Inputs can be plain-text specifications or existing source code, with specialized guides loaded on demand for each diagram style.
Can design-doc-mermaid render diagrams as images?
design-doc-mermaid includes Python utilities for diagram extraction and image conversion alongside Mermaid source output. Developers get editable .mmd-style diagrams plus optional rendered images for docs and RFCs.
Is Design Doc Mermaid safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.