---
name: mermaid-diagrams
description: Generate beautiful Mermaid diagrams with architecture best practices. Covers flowcharts, sequence diagrams, ERDs, class diagrams, state machines, C4, XY charts, and more. Includes anti-patterns (master diagrams, fan traps, conveyor belt syndrome), styling, 15+ themes, and dual CLI rendering (SVG + ASCII).
---

# Mermaid Diagram Generation

This skill teaches you to create professional, beautiful Mermaid diagrams using both the standard `mmdc` CLI and the stunning `beautiful-mermaid` renderer.

---

## Two Renderers: Choose Your Weapon

### 1. beautiful-mermaid (Recommended for Beautiful Output)

Ultra-fast, fully themeable, zero DOM dependencies. Built for the AI era.

```bash
# Install globally (if not already)
npm install -g beautiful-mermaid

# Render to SVG with a theme
npx beautiful-mermaid render diagram.mmd -o diagram.svg --theme tokyo-night

# Render to ASCII for terminal output
npx beautiful-mermaid render diagram.mmd --ascii

# Use programmatically
node -e "
const { renderMermaidSVG, THEMES } = require('beautiful-mermaid');
const fs = require('fs');
const svg = renderMermaidSVG(fs.readFileSync('diagram.mmd', 'utf8'), THEMES['tokyo-night']);
fs.writeFileSync('diagram.svg', svg);
"
```

**Key features:**
- **15 built-in themes** — tokyo-night, dracula, nord, catppuccin, github, solarized...
- **Two-color foundation** — Just `bg` + `fg` creates a beautiful mono diagram
- **ASCII output** — Perfect for terminal, CLI tools, LLM responses
- **Synchronous rendering** — No async, no flash, works with React `useMemo()`
- **CSS custom properties** — Live theme switching without re-render

### 2. mermaid-cli (Standard mmdc)

The official Mermaid CLI. More diagram types, but less beautiful defaults.

```bash
# Basic SVG render
mmdc -i diagram.mmd -o diagram.svg

# PNG with transparent background
mmdc -i diagram.mmd -o diagram.png -b transparent

# PDF output
mmdc -i diagram.mmd -o diagram.pdf --pdfFit

# Use a theme
mmdc -i diagram.mmd -o diagram.svg -t forest   # forest | dark | neutral | default

# High-resolution PNG (2x scale)
mmdc -i diagram.mmd -o diagram.png -s 2 -w 1600 -H 1200
```

---

## Theme System (beautiful-mermaid)

### The Two-Color Foundation

Every diagram needs just **two colors**: `bg` (background) and `fg` (foreground). From these, the entire diagram is derived using `color-mix()`:

```typescript
import { renderMermaidSVG } from 'beautiful-mermaid'

// Mono mode — just two colors
const svg = renderMermaidSVG(diagram, {
  bg: '#1a1b26',  // Background
  fg: '#a9b1d6',  // Foreground
})
```

The system automatically derives all other colors:

| Element | Derivation |
|---------|------------|
| Primary text | `--fg` at 100% |
| Secondary text | `--fg` at 60% into `--bg` |
| Edge labels | `--fg` at 40% into `--bg` |
| Faint text | `--fg` at 25% into `--bg` |
| Connectors | `--fg` at 50% into `--bg` |
| Arrow heads | `--fg` at 85% into `--bg` |
| Node fill | `--fg` at 3% into `--bg` |
| Node stroke | `--fg` at 20% into `--bg` |

### Enriched Mode

For richer themes, add optional enrichment colors:

```typescript
const svg = renderMermaidSVG(diagram, {
  bg: '#1a1b26',
  fg: '#a9b1d6',
  // Optional enrichment:
  line: '#3d59a1',    // Edge/connector color
  accent: '#7aa2f7',  // Arrow heads, highlights
  muted: '#565f89',   // Secondary text, labels
  surface: '#292e42', // Node fill tint
  border: '#3d59a1',  // Node stroke
})
```

### Built-in Themes

| Theme | Type | Best For |
|-------|------|----------|
| `tokyo-night` | Dark | Modern, clean, purple-blue accents |
| `tokyo-night-storm` | Dark | Slightly lighter variant |
| `tokyo-night-light` | Light | Light mode companion |
| `catppuccin-mocha` | Dark | Warm, purple accents, cozy |
| `catppuccin-latte` | Light | Light mode companion |
| `nord` | Dark | Arctic blue palette, minimal |
| `nord-light` | Light | Light mode companion |
| `dracula` | Dark | Purple-heavy, high contrast |
| `github-light` | Light | Clean, professional |
| `github-dark` | Dark | GitHub dark mode |
| `solarized-light` | Light | Warm cream background |
| `solarized-dark` | Dark | Classic dark terminal |
| `one-dark` | Dark | Atom One Dark inspired |
| `zinc-light` | Light | Pure white, minimal |
| `zinc-dark` | Dark | Pure dark, minimal |

```typescript
import { renderMermaidSVG, THEMES } from 'beautiful-mermaid'

const svg = renderMermaidSVG(diagram, THEMES['tokyo-night'])
```

### CSS Variables for Live Theme Switching

All colors are CSS custom properties. Switch themes instantly without re-rendering:

```javascript
// In browser: instant theme switch
svg.style.setProperty('--bg', '#282a36')
svg.style.setProperty('--fg', '#f8f8f2')
```

For React apps, use CSS variable references:

```typescript
const svg = renderMermaidSVG(diagram, {
  bg: 'var(--background)',
  fg: 'var(--foreground)',
  accent: 'var(--accent)',
  transparent: true,
})
```

### Shiki Theme Compatibility

Use **any VS Code theme** directly:

```typescript
import { getSingletonHighlighter } from 'shiki'
import { renderMermaidSVG, fromShikiTheme } from 'beautiful-mermaid'

const highlighter = await getSingletonHighlighter({
  themes: ['vitesse-dark', 'rose-pine', 'material-theme-darker']
})

const colors = fromShikiTheme(highlighter.getTheme('vitesse-dark'))
const svg = renderMermaidSVG(diagram, colors)
```

---

## ASCII Output

For terminal environments, CLI tools, or LLM responses:

```typescript
import { renderMermaidASCII } from 'beautiful-mermaid'

// Unicode mode (default) — prettier box drawing
const unicode = renderMermaidASCII(`graph LR; A --> B`)

// Pure ASCII mode — maximum compatibility
const ascii = renderMermaidASCII(`graph LR; A --> B`, { useAscii: true })
```

**Unicode output:**
```
┌───┐     ┌───┐
│   │     │   │
│ A │────►│ B │
│   │     │   │
└───┘     └───┘
```

**ASCII output:**
```
+---+     +---+
|   |     |   |
| A |---->| B |
|   |     |   |
+---+     +---+
```

### ASCII Options

```typescript
renderMermaidASCII(diagram, {
  useAscii: false,      // true = ASCII, false = Unicode (default)
  paddingX: 5,          // Horizontal spacing between nodes
  paddingY: 5,          // Vertical spacing between nodes
  boxBorderPadding: 1,  // Padding inside node boxes
  colorMode: 'auto',    // 'none' | 'auto' | 'ansi16' | 'ansi256' | 'truecolor' | 'html'
})
```

---

## Flowcharts

Use for process flows, decision trees, and workflows.

```mermaid
flowchart TD
    A[Start] --> B{Decision?}
    B -->|Yes| C[Action 1]
    B -->|No| D[Action 2]
    C --> E[End]
    D --> E
```

### Node Shapes

```
[Rectangle]       - Standard process
(Rounded)         - Start/end, alternate process
{Diamond}         - Decision
[[Subroutine]]    - Predefined process
[(Database)]      - Database/storage
((Circle))        - Connector
>Asymmetric]      - Input/output
{{Hexagon}}       - Preparation
[/Parallelogram/] - Input
[\Parallelogram\] - Output
```

### Direction Options

- `TD` / `TB` — Top to bottom (default, best for hierarchies)
- `LR` — Left to right (best for timelines, pipelines)
- `BT` — Bottom to top
- `RL` — Right to left

### Beauty Tips for Flowcharts

1. **Use subgraphs for grouping** — Creates visual hierarchy
   ```mermaid
   flowchart LR
       subgraph Frontend
           A[React App] --> B[API Client]
       end
       subgraph Backend
           C[Express Server] --> D[(PostgreSQL)]
       end
       B --> C
   ```

2. **Limit nodes per row** — 3-5 nodes max for readability
3. **Use consistent naming** — CamelCase or snake_case, not mixed
4. **Add link labels sparingly** — Only when the relationship isn't obvious

---

## Sequence Diagrams

Use for API flows, user interactions, and protocol documentation.

```mermaid
sequenceDiagram
    participant U as User
    participant F as Frontend
    participant B as Backend
    participant DB as Database
    
    U->>F: Click Login
    F->>B: POST /auth/login
    activate B
    B->>DB: Query user
    DB-->>B: User data
    B-->>F: JWT Token
    deactivate B
    F-->>U: Redirect to Dashboard
```

### Arrow Types

```
->>   Solid line with arrowhead (request)
-->>  Dashed line with arrowhead (response)
-x    Solid line with X (failure)
--x   Dashed line with X
-)    Solid line with open arrow (async)
--)   Dashed line with open arrow
```

### Beauty Tips for Sequence Diagrams

1. **Use participant aliases** — Short names in diagram, full names in declaration
   ```mermaid
   participant API as API Gateway
   ```

2. **Use activation boxes** — Shows when a participant is "active"
   ```mermaid
   activate Backend
   Backend->>DB: Query
   deactivate Backend
   ```

3. **Add notes for clarity**
   ```mermaid
   Note over Frontend,Backend: HTTPS encrypted
   Note right of DB: Read replica
   ```

4. **Use loops and alternatives**
   ```mermaid
   loop Every 30s
       F->>B: Heartbeat
   end
   
   alt Success
       B-->>F: 200 OK
   else Failure
       B-->>F: 500 Error
   end
   ```

5. **Group related interactions** with `rect` backgrounds
   ```mermaid
   rect rgb(200, 220, 255)
       Note over F,B: Authentication Flow
       F->>B: Login
       B-->>F: Token
   end
   ```

---

## Entity Relationship Diagrams

Use for database schemas and data modeling.

```mermaid
erDiagram
    USER ||--o{ ORDER : places
    USER {
        uuid id PK
        string email UK
        string name
        timestamp created_at
    }
    ORDER ||--|{ ORDER_LINE : contains
    ORDER {
        uuid id PK
        uuid user_id FK
        decimal total
        enum status
    }
    PRODUCT ||--o{ ORDER_LINE : "appears in"
    PRODUCT {
        uuid id PK
        string name
        decimal price
    }
    ORDER_LINE {
        uuid order_id PK,FK
        uuid product_id PK,FK
        int quantity
    }
```

### Relationship Cardinality

```
||--||   One to one
||--o{   One to many (zero or more)
||--|{   One to many (one or more)
o|--o{   Zero-or-one to many
```

### Beauty Tips for ERDs

1. **Always include key markers** — `PK`, `FK`, `UK` for clarity
2. **Use meaningful relationship labels** — "places", "contains", "belongs to"
3. **Group related entities** — Put parent tables on left, children on right
4. **Include data types** — Shows schema intent clearly
5. **Keep attribute lists short** — Show key fields only, not every column

---

## Class Diagrams

Use for OOP design, interfaces, and type hierarchies.

```mermaid
classDiagram
    class Animal {
        <<abstract>>
        +String name
        +int age
        +makeSound()* void
        +move() void
    }
    
    class Dog {
        +String breed
        +makeSound() void
        +fetch() void
    }
    
    class Cat {
        +bool indoor
        +makeSound() void
        +scratch() void
    }
    
    Animal <|-- Dog : extends
    Animal <|-- Cat : extends
    
    class IFeedable {
        <<interface>>
        +feed(food: String) void
    }
    
    IFeedable <|.. Dog : implements
    IFeedable <|.. Cat : implements
```

### Visibility Modifiers

```
+  Public
-  Private
#  Protected
~  Package/Internal
```

### Relationship Types

```
<|--  Inheritance (extends)
<|..  Implementation (implements)
*--   Composition (strong ownership)
o--   Aggregation (weak ownership)
-->   Association
..>   Dependency
```

### Beauty Tips for Class Diagrams

1. **Use stereotypes** — `<<interface>>`, `<<abstract>>`, `<<enum>>`, `<<service>>`
2. **Show method signatures** — Include params and return types
3. **Order members consistently** — Properties first, then methods
4. **Limit to 5-7 classes** — Split into multiple diagrams if larger
5. **Use namespaces for grouping**
   ```mermaid
   namespace Domain {
       class User
       class Order
   }
   ```

---

## State Diagrams

Use for state machines, workflows, and lifecycle documentation.

```mermaid
stateDiagram-v2
    [*] --> Draft
    
    Draft --> Review : submit()
    Review --> Draft : reject()
    Review --> Approved : approve()
    Approved --> Published : publish()
    Published --> Archived : archive()
    Archived --> [*]
    
    state Review {
        [*] --> Pending
        Pending --> InProgress : assign()
        InProgress --> Complete : finish()
        Complete --> [*]
    }
```

### Beauty Tips for State Diagrams

1. **Use nested states** — Shows complex sub-workflows
2. **Add transition labels** — Method names or event triggers
3. **Use notes for conditions**
   ```mermaid
   state "Waiting" as W
   note right of W : Timeout after 30s
   ```
4. **Mark fork/join for concurrent states**
   ```mermaid
   state fork_state <<fork>>
   state join_state <<join>>
   ```

### Inline Edge Styling (beautiful-mermaid)

```mermaid
stateDiagram-v2
    A --> B --> C
    linkStyle 0 stroke:#ff0000,stroke-width:2px
    linkStyle default stroke:#888888
```

---

## XY Charts (beautiful-mermaid)

Bar charts, line charts, and combinations.

### Bar Chart

```mermaid
xychart-beta
    title "Monthly Revenue"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    y-axis "Revenue ($K)" 0 --> 500
    bar [180, 250, 310, 280, 350, 420]
```

### Line Chart

```mermaid
xychart-beta
    title "User Growth"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    line [1200, 1800, 2500, 3100, 3800, 4500]
```

### Combined Bar + Line

```mermaid
xychart-beta
    title "Sales with Trend"
    x-axis [Jan, Feb, Mar, Apr, May, Jun]
    bar [300, 380, 280, 450, 350, 520]
    line [300, 330, 320, 353, 352, 395]
```

### Horizontal Orientation

```mermaid
xychart-beta horizontal
    title "Language Popularity"
    x-axis [Python, JavaScript, Java, Go, Rust]
    bar [30, 25, 20, 12, 8]
```

### Chart Styling Notes

beautiful-mermaid charts have a clean, minimal design:
- **Dot grid** — Subtle dot pattern instead of solid grid lines
- **Rounded bars** — All bar corners are rounded
- **Smooth curves** — Natural cubic spline interpolation for lines
- **Floating labels** — No visible axis lines or tick marks
- **Drop-shadow lines** — Subtle shadow beneath lines for depth
- **Monochromatic palette** — Series colors derived from accent color

---

## Git Graphs

Use for branch strategies and release documentation.

```mermaid
gitGraph
    commit id: "Initial"
    branch develop
    checkout develop
    commit id: "Feature A"
    branch feature/login
    commit id: "Add login UI"
    commit id: "Add auth logic"
    checkout develop
    merge feature/login
    checkout main
    merge develop tag: "v1.0.0"
    checkout develop
    commit id: "Feature B"
```

---

## Gantt Charts

Use for project timelines and sprint planning.

```mermaid
gantt
    title Project Timeline
    dateFormat YYYY-MM-DD
    
    section Planning
    Requirements    :done,    req, 2024-01-01, 7d
    Design          :done,    des, after req, 5d
    
    section Development
    Backend API     :active,  api, after des, 14d
    Frontend UI     :         ui, after des, 14d
    Integration     :         int, after api, 7d
    
    section Testing
    QA Testing      :         qa, after int, 7d
    UAT             :         uat, after qa, 5d
    
    section Release
    Deployment      :milestone, deploy, after uat, 0d
```

---

## Pie Charts

Use for simple distribution visualizations.

```mermaid
pie showData
    title Traffic Sources
    "Organic Search" : 45
    "Direct" : 25
    "Referral" : 15
    "Social" : 10
    "Email" : 5
```

---

## Mindmaps

Use for brainstorming outputs and concept hierarchies.

```mermaid
mindmap
    root((Project))
        Frontend
            React
            TypeScript
            TailwindCSS
        Backend
            Node.js
            Express
            PostgreSQL
        DevOps
            Docker
            GitHub Actions
            AWS
```

---

## Architecture Diagrams (C4)

Use for system context and container diagrams.

```mermaid
C4Context
    title System Context Diagram
    
    Person(user, "User", "A customer of the system")
    System(webapp, "Web Application", "Main user interface")
    System_Ext(payment, "Payment Gateway", "Handles payments")
    System_Ext(email, "Email Service", "Sends notifications")
    
    Rel(user, webapp, "Uses", "HTTPS")
    Rel(webapp, payment, "Processes payments", "API")
    Rel(webapp, email, "Sends emails", "SMTP")
```

---

## Global Styling

Add custom styles to any diagram:

```mermaid
flowchart LR
    A[Start]:::primary --> B[Process]:::secondary --> C[End]:::success
    
    classDef primary fill:#4F46E5,stroke:#3730A3,color:#fff
    classDef secondary fill:#6B7280,stroke:#4B5563,color:#fff
    classDef success fill:#10B981,stroke:#059669,color:#fff
```

### Link Styling

```mermaid
flowchart LR
    A --> B --> C
    linkStyle 0 stroke:#ff0000,stroke-width:2px
    linkStyle 1 stroke:#00ff00,stroke-width:2px,stroke-dasharray:5
```

---

## Configuration Files

### beautiful-mermaid (TypeScript/Node)

```typescript
import { renderMermaidSVG, THEMES } from 'beautiful-mermaid'

const options = {
  ...THEMES['tokyo-night'],
  font: 'Inter',
  transparent: false,
  padding: 40,
  nodeSpacing: 24,
  layerSpacing: 40,
  thoroughness: 3,  // 1-7, higher = better layout but slower
  interactive: true, // Enable tooltips for XY charts
}

const svg = renderMermaidSVG(diagram, options)
```

### mermaid-cli (JSON config)

Create a `mermaid.config.json` for consistent styling:

```json
{
  "theme": "neutral",
  "themeVariables": {
    "primaryColor": "#4F46E5",
    "primaryTextColor": "#ffffff",
    "primaryBorderColor": "#3730A3",
    "lineColor": "#6B7280",
    "secondaryColor": "#E5E7EB",
    "tertiaryColor": "#F3F4F6",
    "fontSize": "16px",
    "fontFamily": "Inter, system-ui, sans-serif"
  },
  "flowchart": {
    "curve": "basis",
    "padding": 20,
    "nodeSpacing": 50,
    "rankSpacing": 50
  },
  "sequence": {
    "mirrorActors": false,
    "messageMargin": 40,
    "boxMargin": 10
  }
}
```

Use with: `mmdc -i diagram.mmd -o diagram.svg -c mermaid.config.json`

---

## Technical Architecture Diagrams (Recommended Style)

For system architecture, package structure, and data flow diagrams, use this proven configuration:

### Light Theme with Hard Edges

```json
{
  "theme": "base",
  "themeVariables": {
    "primaryColor": "#e2e8f0",
    "primaryTextColor": "#1e293b",
    "primaryBorderColor": "#475569",
    "lineColor": "#475569",
    "secondaryColor": "#f1f5f9",
    "tertiaryColor": "#ffffff",
    "background": "#ffffff",
    "mainBkg": "#ffffff",
    "textColor": "#1e293b",
    "nodeBorder": "#64748b",
    "clusterBkg": "#f8fafc",
    "clusterBorder": "#94a3b8",
    "edgeLabelBackground": "#ffffff",
    "fontSize": "12px",
    "fontFamily": "'JetBrains Mono', 'SF Mono', Consolas, monospace"
  },
  "flowchart": {
    "curve": "linear",
    "padding": 48,
    "nodeSpacing": 16,
    "rankSpacing": 32,
    "useMaxWidth": false,
    "htmlLabels": true,
    "diagramPadding": 24
  }
}
```

**Key settings:**
- `"curve": "linear"` — Hard 90° edges (technical look)
- `"padding": 48` — Large padding so subgraph labels don't overlap content
- `"fontFamily": "monospace"` — Technical/code aesthetic
- Light gray backgrounds for subgraphs (`clusterBkg: #f8fafc`)

### Render Command

```bash
# Create config file
cat > mermaid.config.json << 'EOF'
{ ... config above ... }
EOF

# Render PNG (2x scale for crisp output)
mmdc -i diagram.mmd -o diagram.png -c mermaid.config.json -b white -s 2

# Render SVG
mmdc -i diagram.mmd -o diagram.svg -c mermaid.config.json -b white

# Clean up
rm mermaid.config.json
```

### Layout Best Practices

**1. Use subgraphs to show package/module boundaries:**

```mermaid
flowchart TB
    subgraph core ["@myapp/core"]
        Server["Server"]
        Router["Router"]
    end
    
    subgraph ui ["@myapp/ui"]
        App["React App"]
    end
    
    App -->|HTTP| Server
```

**2. Arrange elements to minimize edge crossings:**

- Put related nodes adjacent to each other
- Place nodes that connect to the same target near each other
- Use consistent flow direction (TB for hierarchies, LR for pipelines)

**3. Label ALL edges:**

```mermaid
flowchart TB
    A -->|HTTP| B
    B -->|query| C
    B -->|cache| D
    C -->|triples| E
```

Unlabeled edges are ambiguous. Always describe the relationship.

**4. Avoid deeply nested subgraphs:**

```mermaid
%% BAD - nested subgraphs cause layout issues
subgraph outer ["Outer"]
    subgraph inner ["Inner"]
        subgraph deep ["Deep"]
            Node["Node"]
        end
    end
end

%% GOOD - flat structure with clear grouping
subgraph group1 ["Group 1"]
    A["Node A"]
    B["Node B"]
end

subgraph group2 ["Group 2"]
    C["Node C"]
end

A --> C
```

**5. Use direction hints inside subgraphs:**

```mermaid
subgraph workers ["Workers"]
    direction LR
    W1["worker-1"]
    W2["worker-2"]
    W3["worker-3"]
end
```

### Example: System Architecture

```mermaid
flowchart TB
    User(["User"])
    
    subgraph interface ["Interface"]
        direction LR
        CLI["CLI"]
        UI["Web UI"]
    end
    
    Server["Backend Server"]
    
    subgraph agents ["AI Agents"]
        direction LR
        QueryAgent["Query Agent"]
        BuilderAgent["Builder Agent"]
    end
    
    LLM["LLM Provider"]
    
    subgraph storage ["Storage"]
        direction LR
        DB[("Database")]
        Cache[("Cache")]
    end
    
    User -->|terminal| CLI
    User -->|web| UI
    CLI -->|HTTP| Server
    UI -->|HTTP| Server
    
    Server -->|query| QueryAgent
    Server -->|build| BuilderAgent
    Server -->|cache| Cache
    
    QueryAgent -->|prompt| LLM
    BuilderAgent -->|prompt| LLM
    QueryAgent -->|SQL| DB
```

### Example: Package Dependencies

```mermaid
flowchart TB
    subgraph core ["Core Packages"]
        Types["@app/types<br/><i>interfaces</i>"]
        Shared["@app/shared<br/><i>utilities</i>"]
        Client["@app/client<br/><i>API client</i>"]
        
        Types --> Shared
        Shared --> Client
    end
    
    subgraph apps ["Applications"]
        direction LR
        Web["@app/web"]
        CLI["@app/cli"]
    end
    
    Client -->|import| Web
    Client -->|import| CLI
```

### Example: Data Pipeline

```mermaid
flowchart TB
    subgraph sources ["Data Sources"]
        direction LR
        API["REST APIs"]
        Stream["Event Streams"]
        Files["File Uploads"]
    end
    
    subgraph processing ["Processing"]
        Ingest["Ingestion"]
        Transform["Transform"]
        Validate["Validation"]
    end
    
    subgraph storage ["Storage"]
        direction LR
        DB[("Primary DB")]
        Cache[("Cache")]
    end
    
    API -->|poll| Ingest
    Stream -->|subscribe| Ingest
    Files -->|watch| Ingest
    
    Ingest -->|raw| Transform
    Transform -->|cleaned| Validate
    Validate -->|valid| DB
    Validate -->|hot| Cache
```

---

## Architecture Diagram Anti-Patterns

These mistakes cause confusion, misinterpretation, and frustration. Avoid them.

### 1. Type-Only Labels (Missing Resource Names)

**❌ Bad:** Labeling by type alone
```mermaid
flowchart LR
    A[(Database)] --> B[Lambda] --> C[(Database)]
```

**✅ Good:** Include both name AND type
```mermaid
flowchart LR
    A[(Orders DB)] --> B[ProcessOrder Lambda] --> C[(Analytics DB)]
```

**Why it matters:**
- **Types** describe *what kind* of thing a resource is (database, service, queue)
- **Names** disambiguate resources of the same type and reveal purpose

When icons already indicate type, prioritize the name in the label. Use suffixes like "Orders Table", "Results Bucket", "Auth Service" when space allows.

---

### 2. Unconnected Resources

**❌ Bad:** Floating resources with no relationships
```mermaid
flowchart LR
    A[API Gateway] --> B[Lambda]
    B --> C[(DynamoDB)]
    D[Route 53]
```
Route 53 floats alone — its role is completely unclear.

**✅ Good:** Every resource connects to something
```mermaid
flowchart LR
    D[Route 53] --> A[API Gateway] --> B[Lambda]
    B --> C[(DynamoDB)]
```

If you can't connect a resource cleanly, it probably belongs in a different diagram perspective. Don't include resources just because "they're part of the system."

---

### 3. The "Master Diagram" Trap

**❌ Bad:** Cramming everything into one diagram

Trying to show runtime dependencies, DNS config, CDN setup, source code structure, and deployment pipelines in a single diagram **overwhelms viewers**.

**✅ Good:** Split into focused perspectives

| Perspective | Shows |
|-------------|-------|
| Runtime Architecture | Services, databases, message flows |
| Deployment Pipeline | CI/CD, environments, artifacts |
| Network Topology | DNS, CDN, load balancers, VPCs |
| Data Flow | How data moves through the system |
| Security Boundaries | Auth, encryption, trust zones |

Each perspective tells a cohesive story. Create multiple diagrams that share resource definitions but show different relationships.

---

### 4. Conveyor Belt Syndrome

**❌ Bad:** Depicting everything as an assembly line
```mermaid
flowchart LR
    A[Client] --> B[API] --> C[Service] --> D[DB] --> E[Cache] --> F[Response]
```

This implies data flows neatly from one resource to the next, each augmenting and passing along. **This is almost never true.** Real systems have orchestration, round-trips, retries, and conditional paths.

**✅ Good:** Use sequence diagrams for behavioral flows
```mermaid
sequenceDiagram
    participant C as Client
    participant A as API Gateway
    participant S as Order Service
    participant D as Database
    participant Ca as Cache
    
    C->>A: POST /orders
    A->>S: CreateOrder()
    S->>Ca: Check inventory
    Ca-->>S: Cache miss
    S->>D: Query inventory
    D-->>S: Inventory data
    S->>Ca: Update cache
    S->>D: Insert order
    D-->>S: Order ID
    S-->>A: Order created
    A-->>C: 201 Created
```

**Rule of thumb:**
- **Flowcharts** = relational (what connects to what)
- **Sequence diagrams** = behavioral (what happens in what order)

Don't use flowcharts to show detailed request/response flows.

---

### 5. Fan Traps (Collapsed Relationships)

**❌ Bad:** Relationships collapse into intermediate resources
```mermaid
flowchart LR
    A[Order Service] --> Q[Message Broker]
    B[Payment Service] --> Q
    Q --> C[Notification Service]
    Q --> D[Analytics Service]
```

Which service sends to which? The message broker hides all routing information.

**✅ Good:** Add intermediate resources to show specific paths
```mermaid
flowchart LR
    subgraph Broker
        T1[orders.created]
        T2[payments.completed]
    end
    A[Order Service] --> T1
    B[Payment Service] --> T2
    T1 --> C[Notification Service]
    T1 --> D[Analytics Service]
    T2 --> C
```

---

### 6. Meaningless Decoration

**❌ Bad:** Adding visual elements that convey no information
- Animated arrows that just show "direction" (already indicated by arrowheads)
- Gradient backgrounds that don't represent anything
- Icons purely for aesthetics with no semantic meaning
- Colors that aren't explained in a legend

**✅ Good:** Every visual element carries meaning
- Colors indicate resource type, status, or environment
- Line styles distinguish sync vs async, internal vs external
- Subgraph backgrounds group by deployment boundary or team ownership

```mermaid
flowchart LR
    subgraph Production
        A[API]:::prod --> B[(DB)]:::prod
    end
    subgraph Staging
        C[API]:::stage --> D[(DB)]:::stage
    end
    
    classDef prod fill:#10B981,stroke:#059669
    classDef stage fill:#F59E0B,stroke:#D97706
```

---

### 7. Diagram Syntax Anti-Patterns

These are Mermaid-specific mistakes:

| Mistake | Problem | Fix |
|---------|---------|-----|
| **20+ nodes** | Unreadable | Split into multiple diagrams |
| **Labels > 30 chars** | Text overflows | Abbreviate, use aliases |
| **Crossing lines** | Visual noise | Reorder nodes, change direction |
| **No subgraphs** | Flat hierarchy | Group related resources |
| **Inconsistent styles** | Messy appearance | Define `classDef` once, reuse |
| **No legend** | Colors unexplained | Add a note or comment |
| **Tiny rendered text** | Illegible output | Use `-s 2` scale, increase fontSize |
| **Wrong diagram type** | Misleading | Match diagram type to purpose |

---

## Choosing the Right Diagram Type

| If you need to show... | Use |
|------------------------|-----|
| What connects to what | `flowchart` |
| Request/response sequences | `sequenceDiagram` |
| Data model relationships | `erDiagram` |
| Class/interface hierarchy | `classDiagram` |
| Lifecycle states | `stateDiagram-v2` |
| Project schedule | `gantt` |
| System context (who uses what) | `C4Context` |
| Metrics, trends, comparisons | `xychart-beta` |

**Never use a flowchart to show detailed API interactions.** That's what sequence diagrams are for.

---

## Quick Reference

| Diagram Type | When to Use | Start With |
|--------------|-------------|------------|
| `flowchart` | Processes, decisions, workflows | `flowchart TD` |
| `sequenceDiagram` | API calls, interactions over time | `sequenceDiagram` |
| `erDiagram` | Database schemas | `erDiagram` |
| `classDiagram` | OOP design, interfaces | `classDiagram` |
| `stateDiagram-v2` | State machines, lifecycles | `stateDiagram-v2` |
| `gitGraph` | Branch strategies | `gitGraph` |
| `gantt` | Timelines, schedules | `gantt` |
| `pie` | Simple distributions | `pie showData` |
| `mindmap` | Brainstorms, hierarchies | `mindmap` |
| `C4Context` | Architecture overview | `C4Context` |
| `xychart-beta` | Bar/line charts | `xychart-beta` |

---

## Workflow

### With beautiful-mermaid (Recommended)

1. **Create `.mmd` file** — Write your diagram code
2. **Preview** — Use VS Code Mermaid extension or Mermaid Live Editor
3. **Choose theme** — Pick from 15 built-in themes or create your own
4. **Render SVG** — Use programmatic API or npx
5. **Embed** — Reference the SVG in your docs

```typescript
import { renderMermaidSVG, THEMES } from 'beautiful-mermaid'
import fs from 'fs'

const diagram = fs.readFileSync('architecture.mmd', 'utf8')
const svg = renderMermaidSVG(diagram, THEMES['tokyo-night'])
fs.writeFileSync('architecture.svg', svg)
```

### With mermaid-cli

1. **Create `.mmd` file** — Write your diagram code
2. **Preview** — Use VS Code Mermaid extension or Mermaid Live Editor
3. **Iterate** — Adjust layout direction, groupings, styles
4. **Render** — `mmdc -i diagram.mmd -o diagram.svg -t neutral`
5. **Embed** — Reference the SVG/PNG in your docs

### Output Format Recommendations

- **SVG** for docs (scalable, theme-switchable)
- **PNG** for chat/email (universal)
- **ASCII** for terminal/CLI tools (beautiful-mermaid only)
- **PDF** for print

---

## React Integration (beautiful-mermaid)

Because rendering is synchronous, use `useMemo()` for zero-flash rendering:

```tsx
import { renderMermaidSVG } from 'beautiful-mermaid'
import React from 'react'

function MermaidDiagram({ code }: { code: string }) {
  const { svg, error } = React.useMemo(() => {
    try {
      return {
        svg: renderMermaidSVG(code, {
          bg: 'var(--background)',
          fg: 'var(--foreground)',
          transparent: true,
        }),
        error: null,
      }
    } catch (err) {
      return { svg: null, error: err instanceof Error ? err : new Error(String(err)) }
    }
  }, [code])

  if (error) return <pre>{error.message}</pre>
  return <div dangerouslySetInnerHTML={{ __html: svg! }} />
}
```

**Why this works well:**
- **No flash** — SVG is computed synchronously during render
- **CSS variables** — Theme switches apply instantly without re-rendering
- **Memoized** — Only re-renders when `code` changes
