Last updated: Aug 4, 2025, 11:26 AM UTC

Mermaid Diagram Guide for Technical Documentation

Status: Complete
Purpose: Standardize technical diagram creation using Mermaid format across all documentation
Application: NudgeCampaign and general software architecture documentation

Overview

This guide establishes standards for creating technical diagrams using Mermaid, a text-based diagramming tool that integrates seamlessly with markdown documentation. Mermaid diagrams are version-control friendly, render natively in GitHub, and maintain consistency across all technical documentation.

Why Mermaid?

Benefits

  • Version Control: Text-based format tracks changes in Git
  • Native Rendering: GitHub, GitLab, and most markdown viewers render Mermaid automatically
  • No Special Tools: Edit diagrams directly in any text editor
  • Consistency: Unified styling across all documentation
  • Accessibility: Screen reader compatible as text-based format
  • Maintainability: Easy updates without proprietary software
  • Export Options: Convert to SVG, PNG, or PDF as needed

When to Use Mermaid

  • Architecture diagrams (C4 model)
  • API sequence flows
  • Process flowcharts
  • Database schemas (ERD)
  • State machines
  • User journey maps
  • System integration diagrams
  • Deployment pipelines

Quick Start

Basic Syntax

graph TD A[Start] --> B{Decision} B -->|Yes| C[Process] B -->|No| D[End]

Renders as:

graph TD A[Start] --> B{Decision} B -->|Yes| C[Process] B -->|No| D[End]

Diagram Types for NudgeCampaign

1. C4 Model Architecture Diagrams

System Context (Level 1)

graph TB subgraph "System Boundary" NC[NudgeCampaign
Email Marketing Platform] end User[Marketing User
Person] Admin[System Admin
Person] Contact[Email Recipient
Person] Postmark[Postmark
Email Service] Stripe[Stripe
Payment Service] OpenRouter[OpenRouter
AI Service] Supabase[Supabase
Database] User --> NC Admin --> NC NC --> Contact NC --> Postmark NC --> Stripe NC --> OpenRouter NC --> Supabase style NC fill:#22C55E,color:#fff style User fill:#e1f5e1 style Admin fill:#e1f5e1 style Contact fill:#e1f5e1

Container Diagram (Level 2)

graph TB subgraph "NudgeCampaign System" WebApp[Web Application
Next.js/React] API[API Server
Node.js/Express] Worker[Background Worker
Node.js] Cache[Redis Cache
Session Storage] end subgraph "External Services" DB[(PostgreSQL
Supabase)] Email[Postmark API] AI[OpenRouter API] Pay[Stripe API] end WebApp --> API API --> DB API --> Cache API --> Worker Worker --> Email Worker --> AI API --> Pay style WebApp fill:#22C55E,color:#fff style API fill:#22C55E,color:#fff style Worker fill:#22C55E,color:#fff

Component Diagram (Level 3)

graph TB subgraph "API Server Components" Auth[Authentication
Module] Campaign[Campaign
Manager] Contact[Contact
Manager] Analytics[Analytics
Engine] Billing[Billing
Service] Maya[Maya AI
Assistant] end subgraph "Data Layer" RLS[Row Level
Security] ORM[Prisma ORM] Queue[Bull Queue] end Auth --> RLS Campaign --> ORM Contact --> ORM Analytics --> ORM Billing --> Queue Maya --> Queue style Auth fill:#4A90E2 style Campaign fill:#4A90E2 style Maya fill:#22C55E,color:#fff

2. Sequence Diagrams for API Flows

Email Campaign Send Flow

sequenceDiagram participant U as User participant W as Web App participant A as API Server participant Q as Queue participant WK as Worker participant P as Postmark participant D as Database U->>W: Create Campaign W->>A: POST /api/campaigns A->>D: Save Campaign A->>Q: Queue Send Job A-->>W: Campaign Created W-->>U: Show Success Note over Q,WK: Async Processing Q->>WK: Process Job WK->>D: Get Contacts loop For Each Batch WK->>P: Send Emails P-->>WK: Delivery Status WK->>D: Update Stats end WK->>D: Mark Complete

Authentication Flow with RLS

sequenceDiagram participant U as User participant W as Web App participant A as API Server participant S as Supabase Auth participant D as Database U->>W: Login Request W->>S: Authenticate S-->>W: JWT Token W->>A: API Request + JWT A->>S: Verify Token S-->>A: User Context A->>D: Query with RLS Note over D: RLS applies org filter D-->>A: Filtered Data A-->>W: Response W-->>U: Display Data

3. Flow Charts for Process Documentation

Contact Import Process

flowchart LR Start([User Uploads CSV]) Parse[Parse CSV File] Validate{Valid Format?} Clean[Clean Data] Check{Check Duplicates} Import[Import Contacts] Update[Update Existing] Stats[Calculate Stats] Notify[Notify User] End([Import Complete]) Start --> Parse Parse --> Validate Validate -->|No| Error1[Show Error] Validate -->|Yes| Clean Clean --> Check Check -->|Duplicates| Update Check -->|New| Import Update --> Stats Import --> Stats Stats --> Notify Notify --> End Error1 --> End style Start fill:#e1f5e1 style End fill:#e1f5e1 style Error1 fill:#ffe1e1

Maya AI Conversation Flow

flowchart TD Input([User Message]) Context[Load Context] History[Get History] Enhance{Enhance Query?} API[Call OpenRouter] Stream[Stream Response] Save[Save to DB] Display([Show Response]) Input --> Context Context --> History History --> Enhance Enhance -->|Yes| AddContext[Add Campaign Data] Enhance -->|No| API AddContext --> API API --> Stream Stream --> Save Stream --> Display style Input fill:#22C55E,color:#fff style Display fill:#22C55E,color:#fff

4. Entity Relationship Diagrams

Core Database Schema

erDiagram Organization ||--o{ User : has Organization ||--o{ Contact : owns Organization ||--o{ Campaign : creates User ||--o{ Campaign : authors Campaign ||--o{ EmailDelivery : sends Contact ||--o{ EmailDelivery : receives User ||--o{ AIConversation : has AIConversation ||--o{ AIMessage : contains Organization ||--o{ Subscription : has Organization { uuid id PK string name string slug timestamp created_at } User { uuid id PK uuid organization_id FK string email string role timestamp created_at } Contact { uuid id PK uuid organization_id FK string email string first_name string last_name jsonb custom_fields } Campaign { uuid id PK uuid organization_id FK uuid user_id FK string name string subject text content string status timestamp scheduled_at }

5. State Diagrams for Workflows

Campaign Lifecycle

stateDiagram-v2 [*] --> Draft: Create Draft --> Scheduled: Schedule Draft --> Testing: Send Test Testing --> Draft: Edit Testing --> Scheduled: Approve Scheduled --> Sending: Start Time Scheduled --> Draft: Cancel Sending --> Paused: Pause Paused --> Sending: Resume Paused --> Cancelled: Cancel Sending --> Completed: All Sent Completed --> [*] Cancelled --> [*] state Sending { [*] --> Queued Queued --> Processing Processing --> Delivered Processing --> Failed Failed --> Retry Retry --> Delivered Retry --> Bounced }

Subscription States

stateDiagram-v2 [*] --> Trial: Sign Up Trial --> Active: Add Payment Trial --> Expired: Trial Ends Expired --> Active: Add Payment Active --> PastDue: Payment Fails PastDue --> Active: Payment Success PastDue --> Cancelled: Max Retries Active --> Cancelled: User Cancels Cancelled --> Active: Reactivate Active --> Upgraded: Change Plan Upgraded --> Active: Process state Active { [*] --> Good Good --> Warning: 80% Usage Warning --> Limit: 100% Usage Limit --> Good: New Billing Cycle }

6. User Journey Diagrams

New User Onboarding Journey

journey title New User Onboarding Journey section Sign Up Visit Website: 5: User Create Account: 3: User Verify Email: 4: User section Setup Connect Email Service: 2: User, System Import Contacts: 3: User Create First Campaign: 2: User, Maya section Activation Send Test Email: 4: User Schedule Campaign: 5: User View Analytics: 5: User section Growth Create Automation: 3: User, Maya Upgrade Plan: 4: User Invite Team: 5: User

7. Deployment Pipeline Diagram

graph LR subgraph "Development" Dev[Local Dev] Test[Run Tests] end subgraph "CI/CD Pipeline" GH[GitHub Push] CI[GitHub Actions] Build[Build Docker] Security[Security Scan] end subgraph "Deployment" Stage[Staging] Smoke[Smoke Tests] Prod[Production] Monitor[Monitoring] end Dev --> Test Test --> GH GH --> CI CI --> Build Build --> Security Security --> Stage Stage --> Smoke Smoke --> Prod Prod --> Monitor style GH fill:#333,color:#fff style Prod fill:#22C55E,color:#fff

8. Integration Architecture

graph TB subgraph "NudgeCampaign Core" API[API Server] Queue[Job Queue] Worker[Workers] end subgraph "Email Services" Postmark[Postmark API] SMTP[SMTP Backup] end subgraph "AI Services" OpenRouter[OpenRouter] Claude[Claude 3] GPT[GPT-4] end subgraph "Payment" Stripe[Stripe] Webhook[Webhooks] end subgraph "Analytics" PostHog[PostHog] Sentry[Sentry] end API --> Queue Queue --> Worker Worker --> Postmark Worker --> SMTP API --> OpenRouter OpenRouter --> Claude OpenRouter --> GPT API --> Stripe Stripe --> Webhook Webhook --> API API --> PostHog API --> Sentry

NudgeCampaign Specific Examples

Multi-Tenant Architecture with RLS

graph TB subgraph "Application Layer" U1[User Org A] U2[User Org B] API[API Server] end subgraph "Security Layer" Auth[JWT Auth] RLS[Row Level Security] end subgraph "Data Layer" T1[Organization A Data] T2[Organization B Data] DB[(PostgreSQL)] end U1 --> API U2 --> API API --> Auth Auth --> RLS RLS --> DB DB --> T1 DB --> T2 RLS -.->|Filters| T1 RLS -.->|Filters| T2 style RLS fill:#ff6b6b,color:#fff style T1 fill:#e1f5e1 style T2 fill:#ffe1e1

Email Campaign Flow with Maya AI

flowchart TB Start([User Starts Campaign]) Maya{Maya AI
Assistance?} subgraph "AI Assisted" AI1[Generate Subject] AI2[Write Content] AI3[Optimize Send Time] end subgraph "Manual Creation" M1[Enter Details] M2[Design Email] M3[Select Recipients] end Review[Review Campaign] Test[Send Test] Schedule[Schedule Send] Queue[Add to Queue] Process[Process Batch] Send[Send via Postmark] Track[Track Opens/Clicks] Report[Analytics Report] End([Campaign Complete]) Start --> Maya Maya -->|Yes| AI1 AI1 --> AI2 AI2 --> AI3 AI3 --> Review Maya -->|No| M1 M1 --> M2 M2 --> M3 M3 --> Review Review --> Test Test --> Schedule Schedule --> Queue Queue --> Process Process --> Send Send --> Track Track --> Report Report --> End style Maya fill:#22C55E,color:#fff style Send fill:#4A90E2,color:#fff

Styling Guidelines

Color Palette

graph LR Primary[Primary
#22C55E] Secondary[Secondary
#4A90E2] Success[Success
#10B981] Warning[Warning
#F59E0B] Error[Error
#EF4444] Neutral[Neutral
#6B7280] style Primary fill:#22C55E,color:#fff style Secondary fill:#4A90E2,color:#fff style Success fill:#10B981,color:#fff style Warning fill:#F59E0B,color:#fff style Error fill:#EF4444,color:#fff style Neutral fill:#6B7280,color:#fff

Node Types and Styling

graph TD Start([Rounded Start/End]) Process[Rectangle Process] Decision{Diamond Decision} Data[/Parallelogram Data/] Database[(Cylinder Database)] Document[Document Shape] style Start fill:#e1f5e1 style Process fill:#e1e1ff style Decision fill:#fff4e1 style Data fill:#ffe1e1 style Database fill:#f0f0f0

Best Practices

1. Consistency Rules

  • Direction: Use TB (top-bottom) for hierarchical, LR (left-right) for process flows
  • Naming: Use descriptive labels, avoid abbreviations
  • Colors: Follow the established color palette
  • Spacing: Maintain visual balance with subgraphs
  • Arrows: Use solid for primary flow, dashed for optional/conditional

2. Documentation Integration

## Architecture Overview

The following diagram shows the high-level system architecture:

graph TB A[Component A] --> B[Component B]
**Key Points:** - Component A handles user requests - Component B processes data

3. Accessibility Considerations

  • Always provide text description before/after diagrams
  • Use high contrast colors
  • Include alternative text representations for complex diagrams
  • Ensure logical flow direction (top-to-bottom or left-to-right)

4. Version Control

  • Keep diagrams close to related documentation
  • Use meaningful commit messages when updating diagrams
  • Consider diagram versioning for major architectural changes

5. Performance

  • Limit diagram complexity (max 20-30 nodes per diagram)
  • Split large diagrams into multiple focused diagrams
  • Use subgraphs to organize related components

Export and Rendering Options

GitHub Rendering

  • Mermaid diagrams render automatically in GitHub markdown files
  • No additional configuration required
  • Preview in PR reviews shows rendered diagrams

Export to Image Formats

# Using Mermaid CLI
npm install -g @mermaid-js/mermaid-cli
mmdc -i diagram.mmd -o diagram.svg
mmdc -i diagram.mmd -o diagram.png -t dark

# Using online editor
# Visit: https://mermaid.live
# Paste diagram code and export as SVG/PNG

PDF Generation

  • Include diagrams in markdown documentation
  • Use pandoc or similar tools to convert to PDF with rendered diagrams

Integration with Documentation Tools

  • Docusaurus: Native Mermaid support with plugin
  • MkDocs: Material theme includes Mermaid support
  • Gatsby: Various Mermaid plugins available
  • VuePress: Built-in Mermaid support

Common Patterns for NudgeCampaign

API Endpoint Documentation

graph TB subgraph "System Boundary" NC[NudgeCampaign
Email Marketing Platform] end User[Marketing User
Person] Admin[System Admin
Person] Contact[Email Recipient
Person] Postmark[Postmark
Email Service] Stripe[Stripe
Payment Service] OpenRouter[OpenRouter
AI Service] Supabase[Supabase
Database] User --> NC Admin --> NC NC --> Contact NC --> Postmark NC --> Stripe NC --> OpenRouter NC --> Supabase style NC fill:#22C55E,color:#fff style User fill:#e1f5e1 style Admin fill:#e1f5e1 style Contact fill:#e1f5e1
0

Error Handling Flow

flowchart TD Request([API Request]) Validate{Validate Input} Auth{Authenticated?} RLS{RLS Check} Process[Process Request] Success[Return Success] E400[400 Bad Request] E401[401 Unauthorized] E403[403 Forbidden] E500[500 Server Error] Request --> Validate Validate -->|Invalid| E400 Validate -->|Valid| Auth Auth -->|No| E401 Auth -->|Yes| RLS RLS -->|Denied| E403 RLS -->|Allowed| Process Process -->|Error| E500 Process -->|Success| Success style E400 fill:#ff6b6b,color:#fff style E401 fill:#ff6b6b,color:#fff style E403 fill:#ff6b6b,color:#fff style E500 fill:#ff6b6b,color:#fff style Success fill:#22C55E,color:#fff

Troubleshooting

Common Issues and Solutions

  1. Diagram Not Rendering

    • Check for syntax errors (missing quotes, brackets)
    • Ensure proper markdown fence (```)
    • Verify 'mermaid' identifier after opening fence
  2. Layout Problems

    • Adjust graph direction (TB, LR, RL, BT)
    • Use subgraphs to group related nodes
    • Add invisible nodes for spacing
  3. Text Overflow

    • Use <br/> for line breaks in nodes
    • Shorten labels and add details in documentation
    • Consider splitting into multiple diagrams
  4. Color Not Applying

    • Check style syntax: style NodeID fill:#color,color:#textcolor
    • Ensure node ID matches exactly
    • Use quotes for IDs with special characters

Resources

Official Documentation

Tools and Extensions

  • VS Code: Mermaid Preview extension
  • IntelliJ: Mermaid plugin
  • Chrome: GitHub + Mermaid extension
  • CLI: @mermaid-js/mermaid-cli

Examples Repository

  • Store complex diagram examples in /docs/private/diagrams/
  • Maintain a library of reusable diagram patterns
  • Document any custom styling or themes

Conclusion

Mermaid provides a powerful, maintainable solution for technical documentation diagrams. By following these standards, NudgeCampaign documentation maintains consistency, accessibility, and version control compatibility across all technical diagrams.

Remember: The goal is clear communication. If a diagram becomes too complex, split it into multiple focused diagrams with accompanying documentation.