
Utility Mermaid Diagrams
- 489 installs
- 518 repo stars
- Updated August 4, 2026
- product-on-purpose/pm-skills
utility-mermaid-diagrams is an agent skill that creates syntactically valid Mermaid diagrams across 15 diagram types for developers who need flow, sequence, and architecture visuals in specs and README files.
About
utility-mermaid-diagrams is a product-on-purpose skill (v1.0.0, updated 2026-04-07) for producing valid Mermaid code in product and engineering documents. It covers all 15 Mermaid diagram types—flowchart, sequence, state, kanban, gantt, timeline, quadrant, pie, mindmap, ER, class, architecture, sankey, treemap, and XY-chart—with a dual-lens selection guide, six syntax validity principles, and five bundled reference files including diagram-catalog.md and syntax-guide.md. Developers reach for utility-mermaid-diagrams when a PRD or tech spec needs relationships, branching, or flows that prose flattens, or when broken Mermaid blocks fail to render in GitHub, VS Code, or mermaid.live previews.
- utility-mermaid-diagrams
- AI & Agent Building
- AI-coding skill
Utility Mermaid Diagrams by the numbers
- 489 all-time installs (skills.sh)
- +27 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #1,793 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/product-on-purpose/pm-skills --skill utility-mermaid-diagramsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 489 |
|---|---|
| repo stars | ★ 518 |
| Last updated | August 4, 2026 |
| Repository | product-on-purpose/pm-skills ↗ |
How do you write valid Mermaid diagrams for specs?
Helps with ai & agent building tasks.
Who is it for?
Engineers and PMs documenting system flows, architectures, or roadmaps who need render-safe Mermaid in markdown specs.
Skip if: Teams exporting PNG/SVG from Figma or Lucidchart, or content that a bullet list communicates more clearly than a diagram.
When should I use this skill?
User needs a Mermaid diagram for a PRD, spec, roadmap, or stakeholder doc, or reports Mermaid syntax that will not render.
What you get
Validated Mermaid code blocks, completed diagram planning worksheet, and embedded diagrams in target documents.
- valid Mermaid code block
- diagram planning worksheet
By the numbers
- Covers 15 Mermaid diagram types (skill v1.0.0)
- Six syntax validity principles in the skill instructions
- Five bundled reference files: TEMPLATE, EXAMPLE, diagram-catalog, pm-use-cases, syntax-guide
Files
<!-- PM-Skills | https://github.com/product-on-purpose/pm-skills | Apache 2.0 -->
Mermaid Diagrams
Create effective, syntactically valid mermaid diagrams for product documents.
When to Use
- Creating mermaid diagrams for PRDs, specs, roadmaps, or stakeholder presentations
- Choosing which of 15 diagram types fits a specific communication need
- Debugging mermaid code that won't render or renders incorrectly
- Reviewing diagrams for clarity, accuracy, and accessibility
When NOT to Use
- Exporting diagrams to image files (PNG/SVG) - that's a rendering tool concern
- Using non-mermaid diagramming tools (Figma, Lucidchart, draw.io)
- Creating purely decorative visuals with no informational purpose
The Cardinal Rule
Don't diagram what a list can say.
Diagrams earn their place when they reveal relationships, branching, or flow that prose flattens. Before creating any diagram, ask:
Does this show branching, relationships, or flow that a list or table would flatten?
- Yes → proceed with a diagram
- No → use a numbered list, bullet list, or table instead
A 5-step linear process is a list. A 5-step process with two decision points and a retry loop is a diagram.
Diagram Selection Guide
| I need to show... | Use | Also consider |
|---|---|---|
| A decision or approval process | Flowchart | State |
| Multi-service or multi-party interactions | Sequence | Flowchart |
| Feature lifecycle or status transitions | State | Flowchart |
| Work stages or pipeline status | Kanban | State |
| Release or sprint timeline with dependencies | Gantt | Timeline |
| Version history or chronological milestones | Timeline | Gantt |
| 2D prioritization (effort/impact, risk/value) | Quadrant | - |
| Allocation breakdown or composition | Pie | Treemap |
| Problem decomposition or brainstorming | Mindmap | - |
| Domain models or data relationships | ER | Class |
| API or object contracts | Class | ER |
| System topology or infrastructure | Architecture | Flowchart |
| Flow quantities or budget allocation | Sankey | Pie |
| Hierarchical proportional data | Treemap | Pie |
| Trends or time-series metrics | XY-Chart | - |
For worked examples organized by PM task, see references/pm-use-cases.md. For full syntax and options per type, see references/diagram-catalog.md.
Syntax Validity Principles
Six rules that prevent most rendering failures:
1. Quote labels - Any label containing spaces, parentheses, brackets, colons, commas, or reserved words must be quoted with double quotes 2. Escape special characters - Characters with mermaid or markdown meaning (>, <, - at line start, #) need escaping or quoting 3. Declare before referencing - Define a node before using it in an edge; referencing an undeclared node causes silent failures in some types 4. Respect limits - Each diagram type has a maximum node/participant count beyond which readability collapses (see references/diagram-catalog.md for per-type limits) 5. Comment your intent - Use %% comments to document non-obvious choices (why this layout direction, why this grouping) 6. Test before shipping - Paste into a mermaid renderer (mermaid.live, VS Code preview, or your target environment) and verify it renders correctly
For the complete syntax reference, see references/syntax-guide.md.
Instructions
1. Identify what you're communicating - What relationship, flow, hierarchy, or proportion needs to be visible? Who is the audience? 2. Apply the cardinal rule - Confirm a diagram adds value over a list or table 3. Select a diagram type - Use the selection guide above, browse references/pm-use-cases.md by task, or browse references/diagram-catalog.md by type 4. Plan the diagram - Fill out the planning worksheet in references/TEMPLATE.md: purpose, audience, node inventory, type rationale 5. Write the mermaid code - Follow references/syntax-guide.md rules; start with the minimal syntax example from references/diagram-catalog.md and expand 6. Validate - Run through the quality checklist below 7. Embed - Place the validated mermaid code block in your document
Output Contract
- Planning artifact: A completed diagram planning worksheet (
references/TEMPLATE.md) - Final output: A syntactically valid mermaid code block embedded in the target document
- Quality gate: All items in the quality checklist pass
Quality Checklist
- [ ] Diagram renders without error in target environment
- [ ] Cardinal rule satisfied - a list or table would not communicate this more clearly
- [ ] No linear sequences without branching, relationships, or hierarchy
- [ ] All labels with spaces or special characters are properly quoted
- [ ] Special characters escaped where needed
- [ ] Node/participant count within type-specific limits
- [ ] Colors are accessible (WCAG AA 3:1 contrast minimum, black text on light backgrounds)
- [ ] Color is never the sole differentiator - shapes and labels also distinguish elements
- [ ] Diagram has a descriptive title or surrounding prose context
- [ ]
%%comments document any non-obvious layout or grouping choices
References
| File | Purpose |
|---|---|
references/TEMPLATE.md | Diagram planning worksheet - fill out before writing mermaid code |
references/EXAMPLE.md | Worked example: PM creating 4 diagrams for a product launch |
references/diagram-catalog.md | All 15 diagram types: syntax, PM examples, limits, pitfalls |
references/pm-use-cases.md | PM task → diagram type mapping with mini worked examples |
references/syntax-guide.md | Complete syntax validity rules, escaping, styling, and validation checklist |
Mermaid Diagram Type Catalog
This reference catalogs all 15 Mermaid diagram types available for Product Managers. Each entry includes when to use (and when not to), minimal syntax, realistic PM examples, rendering limits, and common pitfalls. Use the table of contents to jump to the type you need.
Table of Contents
Process & Flow
1. Flowchart 2. Sequence 3. State 4. Kanban
Planning & Time
5. Gantt 6. Timeline 7. Quadrant 8. Pie
Structure & Relationships
9. Mindmap 10. Class 11. ER (Entity-Relationship) 12. Architecture
Data & Proportions
13. Sankey 14. Treemap 15. XY-Chart
---
Process & Flow
---
Flowchart
Visualizes processes with branches, decisions, and validation steps.
Use for:
- Feature approval workflows with multiple decision gates
- User journey decision points (e.g., free vs paid path)
- Bug triage and escalation processes
- Release readiness checklists with go/no-go decisions
Don't use for:
- Linear sequences with no branching -- use a numbered list or Timeline instead
- Multi-party message exchange -- use Sequence instead
- Status lifecycle tracking -- use State instead
Syntax:
flowchart TD
Start([Feature Request Received]) --> Triage{Is it a bug?}
Triage -->|Yes| BugTrack[Route to Bug Queue]
Triage -->|No| Sizing{Effort > 1 sprint?}
Sizing -->|Yes| Epic[Create Epic]
Sizing -->|No| Story[Create User Story]
Epic --> Backlog[Add to Backlog]
Story --> BacklogKey Elements:
- Directions:
TD(top-down),LR(left-right),BT(bottom-top),RL(right-left) - Node shapes: Rectangle
[text], Diamond{text}, Stadium([text]), Circle((text)), Subroutine[[text]], Cylinder[(text)] - Edges:
-->solid arrow,---solid line,-.->dotted arrow,==>thick arrow,-- label -->labeled edge - Subgraphs: Group related nodes with
subgraph Title ... end
Limits:
- Keep to 12 nodes maximum for readability
- More than 3 levels of subgraph nesting can cause rendering issues
- Long labels (over 30 characters) may overlap edges
PM Example:
flowchart TD
subgraph Readiness["Release Readiness Check"]
QA{QA Sign-off?}
QA -->|Pass| Perf{Performance Benchmarks Met?}
QA -->|Fail| Fix[Return to Dev]
Perf -->|Yes| Legal{Legal Review Complete?}
Perf -->|No| Optimize[Performance Sprint]
Legal -->|Yes| Docs{Release Notes Ready?}
Legal -->|Pending| LegalHold[Hold for Legal]
end
Docs -->|Yes| Approve([Approved for Release])
Docs -->|No| Draft[Draft Release Notes]
Draft --> Docs
Fix --> QA
Optimize --> PerfCommon Pitfalls:
- Special characters in labels: Wrap labels with special characters in quotes:
A["Label with (parens)"] - Wrong direction for content: Wide processes work better with
LR; tall decision trees work better withTD - Using flowchart for linear sequences: If there are no branches, a numbered list or Timeline is clearer
See Also:
- Sequence -- better when the focus is on messages between parties rather than decisions
- State -- better when modeling lifecycle transitions rather than process steps
---
Sequence
Shows multi-party interactions as ordered messages over time.
Use for:
- API integration specs in PRDs (request/response flows)
- Service interaction documentation for engineering handoff
- User-system message flows (login, checkout, onboarding)
- Distributed system communication patterns
Don't use for:
- Single-party decision processes -- use Flowchart instead
- Status lifecycle modeling -- use State instead
- Static hierarchy or structure -- use Mindmap or Class instead
Syntax:
sequenceDiagram
participant User as End User
participant App as Mobile App
participant Auth as Auth Service
participant DB as User Database
User ->>+ App: Enter credentials
App ->>+ Auth: POST /login
Auth ->>+ DB: Validate credentials
DB -->>- Auth: User record
Auth -->>- App: JWT token
App -->>- User: Dashboard loadedKey Elements:
- Participants:
participant X as Long Namefor aliases (quotes optional) - Arrows:
->>sync request,-->>response,--)async fire-and-forget,--xlost/failed message - Activation boxes:
+after arrow to activate,-to deactivate (shows when a participant is processing) - Notes:
Note left of X: text,Note right of X: text,Note over X,Y: text - Regions:
rect rgb(200, 255, 200)for success highlighting,rect rgb(255, 200, 200)for error - Control flow:
loop,alt/else,opt,par,critical,break
Limits:
- Keep to 6 participants maximum -- split into multiple diagrams if more are needed
- Deep nesting of
alt/loopblocks (more than 3 levels) becomes hard to read - Very long sequences (over 20 messages) should be broken into phases
PM Example:
sequenceDiagram
participant Customer
participant App as Checkout App
participant Gateway as Payment Gateway
participant Bank as Issuing Bank
participant Notify as Notification Service
Customer ->> App: Submit payment
App ->> Gateway: Charge $49.99
Gateway ->> Bank: Authorize transaction
alt Approved
Bank -->> Gateway: Authorization code
Gateway -->> App: Payment confirmed
App -) Notify: Send receipt email
Notify --) App: Email queued
App -->> Customer: Order confirmation
else Declined
Bank -->> Gateway: Decline reason
Gateway -->> App: Payment failed
App -->> Customer: Retry or use different card
endCommon Pitfalls:
- Too many participants: More than 6 makes the diagram unreadable -- split into sub-flows
- Missing activation boxes: Without
+/-, it is unclear which service is processing at any moment - No error path shown: Always include an
alt/elsefor failure scenarios -- PMs need to see both paths
See Also:
- Flowchart -- better when you need decision diamonds rather than message arrows
- Architecture -- better for showing service topology without message-level detail
---
State
Models lifecycle transitions between defined statuses.
Use for:
- Feature lifecycle (draft, review, approved, in-dev, released)
- Ticket status workflows (open, in-progress, blocked, closed)
- Entity state machines (order: placed, paid, shipped, delivered)
- Subscription lifecycle (trial, active, past-due, cancelled)
Don't use for:
- Processes with complex branching logic -- use Flowchart instead
- Multi-party message flows -- use Sequence instead
- Project timelines with dates -- use Gantt instead
Syntax:
stateDiagram-v2
[*] --> Draft
Draft --> InReview: Submit for review
InReview --> Approved: Reviewer approves
InReview --> Draft: Reviewer requests changes
Approved --> InDevelopment: Sprint planning
InDevelopment --> QA: Dev complete
QA --> Released: QA passes
QA --> InDevelopment: Bugs found
Released --> [*]Key Elements:
- State declaration:
state "Display Name" as idfor readable labels - Start/end markers:
[*]for both initial and terminal states - Transitions:
StateA --> StateB: labelfor labeled transitions - Composite states: Nest states inside a parent state for sub-workflows
- Choice/fork/join:
<<choice>>,<<fork>>,<<join>>for complex routing - Styling: Use
class StateName className-- do NOT use:::syntax
Limits:
- Keep to 10 states maximum for readability
- Composite (nested) states add complexity -- limit to one level of nesting
- Diagrams with many bidirectional transitions become tangled above 8 states
PM Example:
stateDiagram-v2
[*] --> Created: User signs up
state "Account Active" as Active {
Verified --> Subscribed: Selects plan
Subscribed --> Verified: Cancels subscription
}
Created --> Verified: Email confirmed
Created --> Abandoned: 7 days no verification
Verified --> Active
Active --> Suspended: Payment failed 3x
Suspended --> Active: Payment recovered
Suspended --> Deactivated: 30 days overdue
Deactivated --> [*]
Abandoned --> [*]Common Pitfalls:
- Using `:::` for styling: The
:::syntax is unreliable in state diagrams -- use theclasskeyword instead - Forgetting reverse transitions: Real workflows often allow going back (e.g., from review back to draft) -- show these
- Missing terminal states: Every state machine needs at least one path to
[*]or the diagram implies the entity lives forever
See Also:
- Flowchart -- better for process steps with decisions rather than entity lifecycles
- Kanban -- better for showing current work items in stages rather than transition rules
---
Kanban
Displays workflow stages with task cards for static documentation.
Use for:
- Sprint board documentation in retrospective decks
- Deployment pipeline stage visualization
- Content workflow visualization (draft, editing, published)
- Service lifecycle stages with team ownership
Don't use for:
- Live task tracking -- use Jira, Linear, or Trello instead
- Status transitions with rules -- use State instead
- Timeline-based planning -- use Gantt instead
Syntax:
kanban-beta
Drafting
Content brief for blog post
Interview questions for case study
Editing
Q3 product update article
Design Review
Landing page mockup
Published
March newsletter
API docs v2.1Key Elements:
- Columns: Defined by unindented text lines -- these are your workflow stages
- Task items: Indented under their column
- Metadata:
@{assigned: Team, priority: High, ticket: FEAT-123}on task items - Priority values: Very High, High, Low, Very Low
Limits:
- Keep to 10-15 tasks across 3-5 columns for readability
- This is a static snapshot -- it does not update automatically
- Very long task names wrap poorly in narrow renders
PM Example:
kanban-beta
Backlog
Dark mode support @{priority: Low, ticket: FEAT-201}
Export to CSV @{priority: High, ticket: FEAT-198}
In Progress
SSO integration @{assigned: Platform Team, priority: Very High, ticket: FEAT-195}
Dashboard redesign @{assigned: Design Team, priority: High, ticket: FEAT-190}
Code Review
Notification preferences @{assigned: Growth Team, ticket: FEAT-187}
Staging
Onboarding wizard v2 @{assigned: Growth Team, ticket: FEAT-182}
Done
Billing page update @{ticket: FEAT-179}
Search performance fix @{ticket: BUG-441}Common Pitfalls:
- Using for live tracking: Kanban diagrams are static documentation -- use your project management tool for real-time boards
- Too many columns: More than 5 columns compress horizontally and become unreadable
- Forgetting indentation: Task items must be indented under their column or they create new columns
See Also:
- State -- better for modeling the rules of transitions between stages
- Gantt -- better when tasks have dates and dependencies
---
Planning & Time
---
Gantt
Shows project timelines with task durations, dependencies, and milestones.
Use for:
- Release planning with task dependencies
- Sprint capacity visualization across workstreams
- Migration timelines with sequential phases
- Launch coordination across multiple teams
Don't use for:
- Past event documentation -- use Timeline instead
- Decision processes -- use Flowchart instead
- Proportional data -- use Pie or XY-Chart instead
Syntax:
gantt
title Product Launch Timeline
dateFormat YYYY-MM-DD
excludes weekends
section Planning
Market research :done, research, 2026-01-06, 2w
Requirements gathering :done, reqs, after research, 1w
section Development
MVP build :active, mvp, after reqs, 3w
QA testing :qa, after mvp, 1w
section Launch
Beta release :milestone, beta, after qa, 0d
GA launch :crit, launch, after qa, 1wKey Elements:
- Date format:
dateFormat YYYY-MM-DD - Task syntax:
TaskName :id, startDate, durationorTaskName :id, after otherId, duration - Duration units:
d(days),w(weeks),h(hours) - Task states:
done(completed),active(in progress),crit(critical path),milestone(zero duration marker) - Sections: Group tasks by phase or team
- Exclusions:
excludes weekendsorexcludes 2026-12-25
Limits:
- Keep to 20 tasks maximum for readability
- Very long timelines (over 6 months with daily granularity) compress dates into unreadable labels
- Section names cannot contain special characters
PM Example:
gantt
title Q3 Roadmap: Three Workstreams
dateFormat YYYY-MM-DD
excludes weekends
section Platform Team
API v3 design :done, api-design, 2026-07-01, 2w
API v3 build :active, api-build, after api-design, 4w
API v3 migration :crit, api-migrate, after api-build, 2w
API v3 GA :milestone, api-ga, after api-migrate, 0d
section Growth Team
Onboarding revamp :active, onboard, 2026-07-01, 3w
A/B test onboarding :ab-test, after onboard, 2w
Roll out winner :rollout, after ab-test, 1w
section Data Team
Analytics pipeline :pipeline, 2026-07-15, 3w
Dashboard build :dashboard, after pipeline, 2w
Exec review :milestone, exec, after dashboard, 0dCommon Pitfalls:
- Not marking critical path: Use
criton tasks that block the launch date so stakeholders see what cannot slip - Missing dependencies: Without
afterlinks, everything renders as parallel work -- which misleads about the real schedule - Unrealistic durations: Gantt charts create visual commitments -- round-trip these with your team before sharing
See Also:
- Timeline -- better for past events or milestones without task durations
- Kanban -- better for showing current work status without dates
---
Timeline
Displays chronological events or milestones along a time axis.
Use for:
- Product version history for onboarding docs
- Team milestones and achievements for retrospectives
- Incident postmortem event sequences
- Quarterly achievement summaries for leadership updates
Don't use for:
- Future planning with dependencies -- use Gantt instead
- Process flows with decisions -- use Flowchart instead
- Multi-party interactions over time -- use Sequence instead
Syntax:
timeline
title Product Version History
2025-Q1 : v1.0 Launch
: 500 beta users onboarded
2025-Q2 : v1.1 Mobile support
: 2,000 active users
2025-Q3 : v1.2 API access
2025-Q4 : v2.0 Platform redesign
: Series A fundingKey Elements:
- Title:
title Timeline Titleon the first line - Periods: Left-aligned text defines time periods (dates, quarters, sprints)
- Events:
: Event descriptionafter the period, one per line - Multiple events: Additional
: Eventlines under the same period - Sections: Group periods into named sections for phased timelines
Limits:
- Keep to approximately 15 events total for readability
- Very long event descriptions wrap unpredictably
- No support for dependencies or durations -- this is milestones only
PM Example:
timeline
title Incident Response: Payment Outage (March 15)
section Detection
09:00 : Monitoring alert triggered
: PagerDuty pages on-call engineer
09:05 : Confirmed: payment API returning 503s
section Response
09:10 : Incident channel opened
: Engineering lead joins
09:25 : Root cause identified: database connection pool exhausted
09:35 : Hotfix deployed to staging
section Recovery
09:50 : Hotfix deployed to production
10:05 : Payment success rate back to 99.9%
10:30 : All-clear communicated to support team
section Follow-up
March 16 : Postmortem drafted
March 18 : Action items assigned in sprintCommon Pitfalls:
- Using for future planning: Timeline has no concept of dependencies or duration -- use Gantt for planning
- Inconsistent time intervals: Mixing "Q1 2025" with "January 5" in the same diagram confuses readers
- Too many events per period: More than 3 events per period makes the timeline cluttered
See Also:
- Gantt -- better for forward-looking plans with task durations and dependencies
---
Quadrant
Places items on a 2D grid for prioritization and comparison.
Use for:
- Backlog prioritization (effort vs impact)
- Buy/build/partner decision frameworks
- Feature effort-impact analysis for roadmap planning
- Risk-likelihood mapping for launch readiness
Don't use for:
- Time-series data -- use XY-Chart instead
- Proportional breakdowns -- use Pie instead
- Process flows -- use Flowchart instead
Syntax:
quadrantChart
title Feature Prioritization
x-axis Low Effort --> High Effort
y-axis Low Impact --> High Impact
quadrant-1 Major Projects
quadrant-2 Quick Wins
quadrant-3 Deprioritize
quadrant-4 Fill-ins
SSO Integration: [0.75, 0.85]
Dark Mode: [0.25, 0.40]
Export CSV: [0.20, 0.80]
Custom Themes: [0.60, 0.30]Key Elements:
- Axes:
x-axis Low Label --> High Labelandy-axis Low Label --> High Label - Quadrant names:
quadrant-1(top-right),quadrant-2(top-left),quadrant-3(bottom-left),quadrant-4(bottom-right) - Points:
Label: [x, y]where x and y range from 0.01 to 0.99 - Positioning convention: quadrant-2 (top-left) is typically "Quick Wins" in effort/impact matrices
Limits:
- Keep to 10-12 points maximum -- more becomes unreadable
- Point labels should be under 12 characters to avoid overlap
- Values at extremes (below 0.05 or above 0.95) render at the very edge and may be cut off
PM Example:
quadrantChart
title Technical Debt Assessment
x-axis Low Dev Effort --> High Dev Effort
y-axis Low Business Impact --> High Business Impact
quadrant-1 Plan for Next Quarter
quadrant-2 Fix This Sprint
quadrant-3 Ignore for Now
quadrant-4 Schedule Later
Auth refactor: [0.70, 0.90]
DB indexing: [0.30, 0.75]
Legacy API: [0.85, 0.60]
CSS cleanup: [0.20, 0.20]
Test coverage: [0.50, 0.65]
Logging gaps: [0.35, 0.50]
Dead code: [0.15, 0.15]Common Pitfalls:
- Too many points: More than 12 points overlap and the chart becomes a blob -- group similar items
- Labels too long: Keep labels under 12 characters or they overlap adjacent points
- Forgetting axis direction labels: Without "Low --> High" on axes, readers cannot interpret which quadrant is desirable
See Also:
- XY-Chart -- better for plotting trends over time rather than comparing items on two dimensions
- Pie -- better for showing proportional breakdown rather than relative positioning
---
Pie
Shows parts of a whole as proportional slices.
Use for:
- Budget allocation breakdowns
- Survey result distributions
- Time allocation across activities
- Feature category breakdowns for portfolio reviews
Don't use for:
- Comparisons across time periods -- use XY-Chart instead
- Hierarchical proportions -- use Treemap instead
- Roughly equal-sized categories -- use a simple table instead
Syntax:
pie showData
title Sprint Time Allocation
"Feature Work" : 45
"Bug Fixes" : 20
"Tech Debt" : 15
"Meetings" : 12
"Planning" : 8Key Elements:
- Header:
pie showData-- theshowDataflag displays percentage labels on slices - Title:
title Chart Titleon the next line - Slices:
"Label" : value-- values are proportional, they do not need to sum to 100 - Ordering: List slices from largest to smallest for visual clarity
Limits:
- Keep to 3-7 slices -- more than 7 becomes visually cluttered
- Group small categories (under 5%) into an "Other" slice
- Very long labels wrap or overlap the chart
PM Example:
pie showData
title Customer Feedback Categories (Q1)
"Missing Features" : 35
"Performance Issues" : 25
"UX Confusion" : 18
"Billing Questions" : 12
"Other" : 10Common Pitfalls:
- More than 7 slices: Small slices become invisible slivers -- aggregate into "Other"
- Using for time-series comparisons: Pie charts show one moment in time -- use XY-Chart for trends
- All slices roughly equal: If categories are nearly the same size, a table communicates more clearly
See Also:
- Treemap -- better for hierarchical proportions (e.g., categories with subcategories)
- XY-Chart -- better for comparing values across time periods
---
Structure & Relationships
---
Mindmap
Displays concept hierarchies radiating from a central topic.
Use for:
- Feature breakdown and decomposition for planning
- Brainstorming session capture and organization
- Knowledge domain mapping for onboarding docs
- Stakeholder mapping by department or domain
Don't use for:
- Sequential workflows -- use Flowchart instead
- Data relationships with cardinality -- use ER instead
- Time-ordered events -- use Timeline instead
Syntax:
mindmap
((Product Features))
Core Platform
User Management
Authentication
Permissions
Growth
Onboarding Wizard
Referral Program
Analytics
Usage Dashboard
Export ReportsKey Elements:
- Root node: Double parentheses
((Root Topic)) - Node shapes: Circle
(()), Square[], Rounded(), Cloud))text((, Hexagon{{text}} - Hierarchy: Defined by indentation -- each indent level creates a child node
- Icons: Font Awesome icons with
::icon(fa fa-users)after a node - Depth: Keep to 3-4 levels maximum for readability
Limits:
- 4 levels of depth is the practical maximum before text becomes too small
- Balance branch width -- one branch with 10 children next to one with 2 looks awkward
- Very long node labels push branches apart and waste space
PM Example:
mindmap
((Competitive Landscape))
Direct Competitors
Competitor Alpha
Strong API
Enterprise focus
Weak mobile
Competitor Beta
Free tier
Developer-first
Limited analytics
Indirect Competitors
Spreadsheet tools
Excel power users
Google Sheets integrations
Internal tools
Custom-built solutions
Legacy systems
Our Differentiators
AI-powered insights
PM-specific workflows
Open ecosystemCommon Pitfalls:
- Unbalanced depth: One branch 5 levels deep while another has 1 level makes the map lopsided and hard to scan
- Using for workflows: Mindmaps show hierarchy, not sequence -- use Flowchart for processes
- Too many nodes at one level: More than 6 siblings at the same level creates clutter -- group into subcategories
See Also:
- Flowchart -- better when relationships involve flow direction or decisions
- Class -- better when you need to show attributes and methods, not just hierarchy
---
Class
Documents object structures, API contracts, and interface definitions.
Use for:
- API contract documentation between your product and partners
- Domain model visualization for PRD technical context
- Service interface specs for integration planning
- Integration point mapping across systems
Don't use for:
- Data storage relationships with cardinality -- use ER instead
- Runtime message flows -- use Sequence instead
- Feature hierarchies -- use Mindmap instead
Syntax:
classDiagram
class Product {
+String name
+String description
+Decimal price
+getAvailability() Boolean
+updatePrice(Decimal newPrice)
}
class Order {
+UUID orderId
+Date createdAt
+calculateTotal() Decimal
}
Product "1" --> "*" Order : purchased inKey Elements:
- Visibility:
+public,-private,#protected,~package - Stereotypes:
<<interface>>,<<service>>,<<enumeration>>above the class name - Relationships: Inheritance
<|--, Composition*--, Aggregationo--, Association-->, Dependency..> - Cardinality:
"1" -- "*","0..1" -- "1..*"on relationship lines - Generics:
~T~for parameterized types - Namespaces: Group related classes with
namespace GroupName { ... }
Limits:
- Keep to 8 classes maximum per diagram
- Limit methods/attributes to the most important 4-6 per class
- Complex inheritance hierarchies (more than 3 levels) become tangled
PM Example:
classDiagram
class PaymentGateway {
<<interface>>
+processPayment(amount, currency) PaymentResult
+refund(transactionId) RefundResult
+getTransactionStatus(id) Status
}
class StripeAdapter {
+processPayment(amount, currency) PaymentResult
+refund(transactionId) RefundResult
+getTransactionStatus(id) Status
}
class PayPalAdapter {
+processPayment(amount, currency) PaymentResult
+refund(transactionId) RefundResult
+getTransactionStatus(id) Status
}
class PaymentResult {
+String transactionId
+String status
+Decimal amount
+String currency
}
PaymentGateway <|.. StripeAdapter : implements
PaymentGateway <|.. PayPalAdapter : implements
StripeAdapter ..> PaymentResult : returns
PayPalAdapter ..> PaymentResult : returnsCommon Pitfalls:
- Showing implementation details: PMs should focus on interfaces and contracts, not private methods -- keep it to the public surface
- Too many methods listed: Listing every method clutters the diagram -- show only the ones relevant to your audience
- Confusing composition vs aggregation: Composition (
*--) means "cannot exist without" (e.g., Order contains OrderLines); Aggregation (o--) means "can exist independently" (e.g., Team has Members)
See Also:
- ER (Entity-Relationship) -- better for data storage relationships with foreign keys
- Architecture -- better for showing service topology without implementation detail
---
ER (Entity-Relationship)
Models data entities and their storage relationships.
Use for:
- Data model documentation for engineering handoff
- Domain entity relationships for PRD context sections
- Database migration planning and impact analysis
- Data dictionary visualization for analytics teams
Don't use for:
- API behavior and methods -- use Class instead
- Runtime message flows -- use Sequence instead
- Concept hierarchies without relationships -- use Mindmap instead
Syntax:
erDiagram
CUSTOMER ||--o{ ORDER : places
ORDER ||--|{ ORDER_LINE : contains
ORDER_LINE }o--|| PRODUCT : references
CUSTOMER {
uuid id PK
string name
string email
}
ORDER {
uuid id PK
uuid customer_id FK
date created_at
string status
}Key Elements:
- Entity attributes:
type name PK,type name FK, or justtype name - Cardinality symbols:
||--||one-to-one||--o{one-to-manyo{--o{many-to-many||--o|one-to-zero-or-one- Relationship labels: Descriptive verbs in quotes after the colon (e.g.,
: places,: contains) - Key markers:
PKfor primary key,FKfor foreign key
Limits:
- Keep to 8-10 entities maximum per diagram
- Limit attributes to key fields (3-6 per entity) -- full schemas belong in documentation, not diagrams
- Many-to-many relationships render as crossing lines when there are more than 6 entities
PM Example:
erDiagram
TENANT ||--|{ WORKSPACE : owns
WORKSPACE ||--|{ PROJECT : contains
PROJECT ||--o{ FEATURE : tracks
FEATURE }o--o{ TAG : labeled_with
TENANT ||--|{ USER : has
USER }o--o{ WORKSPACE : belongs_to
TENANT {
uuid id PK
string name
string plan
date created_at
}
WORKSPACE {
uuid id PK
uuid tenant_id FK
string name
string slug
}
PROJECT {
uuid id PK
uuid workspace_id FK
string name
string status
}
FEATURE {
uuid id PK
uuid project_id FK
string title
string priority
date target_date
}
USER {
uuid id PK
uuid tenant_id FK
string email
string role
}Common Pitfalls:
- Showing all fields: Listing every database column makes the diagram unreadable -- focus on keys and business-critical attributes
- Missing cardinality: Without
||,o{, etc., the diagram does not communicate the most important information -- how entities relate - Unlabeled relationships: A line between two entities without a verb label (
: places) forces readers to guess the relationship meaning
See Also:
- Class -- better when you need to show behavior (methods) alongside data, not just storage structure
---
Architecture
Shows service topology, infrastructure layout, and system boundaries.
Note: This is an experimental diagram type, available since Mermaid v11.1.0. Syntax may change in future releases.
Use for:
- System architecture documentation for PRDs and design docs
- Infrastructure dependency mapping for platform planning
- Service mesh visualization for microservices products
- Deployment topology documentation for ops handoff
Don't use for:
- Message-level interaction detail -- use Sequence instead
- Simple process flows with under 10 components -- use Flowchart instead
- Data storage relationships -- use ER instead
Syntax:
architecture-beta
group webapp(cloud)[Web Application]
service client(internet)[Browser Client] in webapp
service api(server)[API Gateway] in webapp
service db(database)[PostgreSQL] in webapp
client:R --> L:api
api:R --> L:dbKey Elements:
- Groups: Logical boundaries with
group name(icon)[Label] - Services:
service name(icon)[Label]optionallyin groupName - Built-in icons:
cloud,database,disk,internet,server - Edge directions:
T(top),B(bottom),L(left),R(right) -- specify connection points on each service - Nesting: Groups can be nested inside other groups for layered architecture
Limits:
- Keep to 10-20 services for readability
- Edge direction syntax (
T,B,L,R) is required -- undirected edges are not supported - Limited icon library compared to general-purpose diagramming tools
PM Example:
architecture-beta
group cloud(cloud)[Production Environment]
group frontend(cloud)[Frontend Layer] in cloud
group backend(cloud)[Backend Services] in cloud
group data(cloud)[Data Layer] in cloud
service cdn(internet)[CDN] in frontend
service spa(server)[React SPA] in frontend
service gateway(server)[API Gateway] in backend
service auth(server)[Auth Service] in backend
service core(server)[Core Service] in backend
service notify(server)[Notification Service] in backend
service pg(database)[PostgreSQL] in data
service redis(database)[Redis Cache] in data
service s3(disk)[Object Storage] in data
cdn:R --> L:spa
spa:B --> T:gateway
gateway:R --> L:auth
gateway:B --> T:core
core:R --> L:notify
core:B --> T:pg
core:B --> T:redis
notify:B --> T:s3Common Pitfalls:
- Too much detail: Keep to service boundaries -- internal component details belong in engineering docs, not PM architecture diagrams
- Missing grouping: Without groups, services float without context -- always group by logical boundary (frontend, backend, data)
- Not marking external dependencies: Clearly separate internal services from external ones (payment gateways, third-party APIs) using distinct groups
See Also:
- Flowchart -- simpler alternative for architectures with fewer than 10 components
- Sequence -- better when you need to show the order of messages between services
---
Data & Proportions
---
Sankey
Visualizes flows of quantities between nodes, showing how totals split and merge.
Note: This is an experimental diagram type, available since Mermaid v10.3.0. Syntax may change in future releases.
Use for:
- Budget flow tracking (total budget splitting across departments, then programs)
- User conversion funnels (visitors to signups to active users)
- Resource allocation flows (headcount distribution across teams and projects)
- Revenue stream mapping (total revenue by source, then by product line)
Don't use for:
- Circular flows (not supported) -- use Flowchart instead
- Simple proportions without flow -- use Pie instead
- Time-series comparisons -- use XY-Chart instead
Syntax:
sankey-beta
Marketing Budget,Digital Ads,45000
Marketing Budget,Content,30000
Marketing Budget,Events,25000
Digital Ads,Google Ads,25000
Digital Ads,Social Media,20000
Content,Blog,18000
Content,Video,12000Key Elements:
- Format: CSV-like rows with
Source,Target,Value - Flow direction: Left to right, automatically arranged
- Width: Flow width is proportional to the value
- Multi-level: Sources can be targets of other flows, creating cascading breakdowns
Limits:
- Keep to 5-15 nodes across all levels
- No circular flows -- a node cannot be both upstream and downstream of the same node
- Flows under 5% of the total become very thin lines -- aggregate them into an "Other" category
PM Example:
sankey-beta
Website Visitors,Signed Up,12000
Website Visitors,Bounced,38000
Signed Up,Completed Onboarding,8000
Signed Up,Abandoned Onboarding,4000
Completed Onboarding,Free Plan Active,5500
Completed Onboarding,Upgraded to Pro,2000
Completed Onboarding,Churned in Week 1,500
Free Plan Active,Converted to Pro,1200
Free Plan Active,Still on Free,4300Common Pitfalls:
- Circular references: Mermaid Sankey does not support cycles -- if your flow is circular, use Flowchart instead
- Too many tiny flows: Flows representing under 5% of the total become invisible lines -- aggregate small categories
- Unlabeled nodes: Node names are the only labels -- make them descriptive (e.g., "Signed Up" not "Step 2")
See Also:
- Pie -- better for simple proportional breakdowns without flow direction
- Flowchart -- better when you need decision logic, not just quantity flows
---
Treemap
Displays hierarchical data as nested rectangles sized by value.
Note: This is an experimental diagram type, available since Mermaid v10.3.0. Syntax may change in future releases.
Use for:
- Error distribution by service and error type
- Feature usage broken down by category and subcategory
- Cost breakdown by department and line item
- Content inventory by section and page count
Don't use for:
- Flat (non-hierarchical) proportions -- use Pie instead
- Flow between categories -- use Sankey instead
- Time-series comparisons -- use XY-Chart instead
Syntax:
treemap-beta
Root
Platform
API Errors 450
Auth Failures 120
Timeout Issues 80
Frontend
Rendering Bugs 200
Form Validation 90
Mobile
Crash Reports 310
UI Glitches 60Key Elements:
- Hierarchy: Defined by indentation, just like Mindmap
- Parent nodes: Do not have values -- their size is the sum of children
- Leaf nodes: Must have numeric values -- these determine rectangle size
- Depth: Keep to 2-3 levels for readability
Limits:
- Approximately 30 leaf nodes maximum before labels overlap
- 2-3 levels of depth is the practical limit
- Values below 2% of the total become invisible rectangles
PM Example:
treemap-beta
Support Tickets
Billing
Payment Failed 245
Refund Request 180
Invoice Question 95
Product
Feature Request 320
Bug Report 275
How-To Question 150
Account
Login Issues 190
Permission Errors 85
Profile Updates 40
Integrations
API Errors 110
Webhook Failures 70
OAuth Issues 55Common Pitfalls:
- Too many levels: More than 3 levels makes inner rectangles too small to read -- flatten your hierarchy
- Tiny values: Items below 2% of the total are invisible slivers -- aggregate them into an "Other" node
- Values on parent nodes: Parent nodes must not have values -- their area is automatically calculated from their children
See Also:
- Pie -- better for flat proportions with 3-7 categories and no hierarchy
- Mindmap -- better when you want to show hierarchy without proportional sizing
---
XY-Chart
Plots data points on X and Y axes as lines or bars for trend visualization.
Note: This is an experimental diagram type, available since Mermaid v10.0.0. Syntax may change in future releases.
Use for:
- KPI tracking over time (MRR, DAU, NPS trends)
- A/B test results comparison across metrics
- Feature adoption curves post-launch
- Performance benchmarks across releases
Don't use for:
- Parts of a whole -- use Pie instead
- Duration-based task planning -- use Gantt instead
- 2D item comparison -- use Quadrant instead
Syntax:
xychart-beta
title Monthly Active Users
x-axis ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
y-axis "Users (thousands)" 0 --> 50
line [12, 18, 22, 28, 35, 42]Key Elements:
- Header:
xychart-beta - Axes:
x-axis [labels]with quoted strings,y-axis "Label" min --> max - Data series:
line [values]for trend lines,bar [values]for bar charts - Multiple series: Add additional
lineorbarrows for comparison - Mixed charts: Combine
barandlinein the same chart
Limits:
- Keep to 4 data series (lines/bars) maximum per chart
- 6-8 data points per series is optimal for readability
- Very large value ranges compress smaller values into the baseline
PM Example:
xychart-beta
title Feature Adoption: First 8 Weeks Post-Launch
x-axis ["Wk 1", "Wk 2", "Wk 3", "Wk 4", "Wk 5", "Wk 6", "Wk 7", "Wk 8"]
y-axis "Active Users" 0 --> 5000
bar [200, 800, 1500, 2200, 2800, 3400, 3900, 4200]
line [200, 800, 1500, 2200, 2800, 3400, 3900, 4200]Common Pitfalls:
- Too many lines: More than 4 overlapping lines become impossible to distinguish -- split into multiple charts
- Inconsistent x-axis intervals: Mixing weeks and months on the same axis distorts trends -- keep intervals uniform
- No axis labels or units: Without units on the y-axis (e.g., "Users (thousands)"), readers cannot interpret the values
See Also:
- Gantt -- better when you need duration bars for project planning, not data trends
- Quadrant -- better for comparing items on two dimensions at a single point in time
---
Quick Reference: Choosing the Right Type
| If you need to show... | Use this type |
|---|---|
| Process with decisions | Flowchart |
| Messages between services | Sequence |
| Status lifecycle | State |
| Work items in stages | Kanban |
| Project schedule | Gantt |
| Past milestones | Timeline |
| 2D prioritization | Quadrant |
| Parts of a whole | Pie |
| Concept hierarchy | Mindmap |
| API contracts | Class |
| Data model | ER |
| System topology | Architecture |
| Quantity flows | Sankey |
| Hierarchical proportions | Treemap |
| Metrics over time | XY-Chart |
Worked Example: Diagrams for Pulse Analytics v2.0 Launch
This example walks through four diagrams a PM would create while preparing Pulse Analytics v2.0 for launch. Each diagram follows the planning worksheet from TEMPLATE.md before writing any mermaid code.
---
Example 1: Flowchart -- Feature Approval Workflow
Context: The PRD needs a visual showing how new feature requests move through the approval process. Stakeholders keep asking "what happens after I submit a request?" and a text description has not stuck.
Filled Worksheet
What I'm showing: The decision path a feature request follows from submission to approval, deferral, or rejection. Audience: Engineering leads and business stakeholders reading the PRD. Where this will appear: Pulse Analytics v2.0 PRD, "Process" section.
Cardinal Rule Check:
- [x] This shows branching, relationships, or flow that a list would flatten
- [x] A numbered list or table would NOT communicate this more clearly
There are two decision points (strategic fit, feasibility) and a retry loop (spike). A list would hide the branching.
Selected type: Flowchart Why this type: Multiple decision diamonds with branching outcomes -- flowcharts are built for this. Considered alternatives: State diagram (possible, but the focus is on the process, not lifecycle states).
Node Inventory:
| Node/Entity | Role/Label | Notes |
|---|---|---|
| request | New Feature Request | Entry point |
| strategic | Strategic Fit? | Decision diamond |
| feasibility | Engineering Feasibility? | Decision diamond |
| scoring | Priority Scoring | Process step |
| approved | Approved | Terminal -- goes to backlog |
| deferred | Deferred | Terminal |
| spike | Spike Scheduled | Loops back to feasibility |
| rejected | Rejected with Rationale | Terminal |
Total node count: 8 (within flowchart limit of 12)
Resulting Diagram
%% MEANING: Feature approval workflow for Pulse Analytics v2.0 PRD
flowchart TD
request["New Feature Request"]
strategic{"Strategic Fit?"}
feasibility{"Engineering Feasibility?"}
scoring["Priority Scoring"]
approved["Approved"]
deferred["Deferred"]
spike["Spike Scheduled"]
rejected["Rejected with Rationale"]
request --> strategic
strategic -- "Yes" --> feasibility
strategic -- "No" --> rejected
subgraph review ["Review Phase"]
feasibility -- "Feasible" --> scoring
feasibility -- "Needs Spike" --> spike
spike -- "Re-evaluate" --> feasibility
end
feasibility -- "Not Feasible" --> rejected
scoring -- "High Priority" --> approved
scoring -- "Low Priority" --> deferredWhat this communicates: The diagram reveals that feature approval is not a straight line -- it has two independent gates (strategic and technical) and a retry loop for spikes. Stakeholders can immediately see that "needs spike" is not a rejection, it feeds back into the process. This branching structure would collapse into ambiguity in a numbered list.
---
Example 2: Gantt -- Launch Timeline
Context: The roadmap presentation needs a timeline showing the 8-week path to GA release, with dependencies visible so leadership can see which delays would cascade.
Filled Worksheet
What I'm showing: The 8-week launch timeline for Pulse Analytics v2.0 with task dependencies and critical path. Audience: Leadership team and cross-functional partners in the roadmap review. Where this will appear: Roadmap deck, "Timeline" slide.
Cardinal Rule Check:
- [x] This shows branching, relationships, or flow that a list would flatten
- [x] A numbered list or table would NOT communicate this more clearly
Parallel tracks (dev, QA, launch) with dependencies between them -- a list cannot show which tasks block others.
Selected type: Gantt Why this type: Time-based schedule with parallel tracks and dependencies. Gantt charts are purpose-built for this. Considered alternatives: Timeline (good for milestones, but does not show task duration or dependencies).
Node Inventory:
| Node/Entity | Role/Label | Notes |
|---|---|---|
| backend | Backend API | 3 weeks |
| frontend | Frontend Dashboard | 4 weeks, starts week 2 |
| pipeline | Data Pipeline | 2 weeks |
| integration | Integration Testing | 1 week, after backend + frontend |
| uat | UAT | 1 week, after integration testing |
| perf | Performance Testing | 3 days, parallel to UAT |
| docs | Documentation | 1 week |
| marketing | Marketing Prep | 1 week |
| ga | GA Release | Milestone |
Total node count: 9 tasks (within Gantt limit of 20)
Resulting Diagram
%% MEANING: Pulse Analytics v2.0 launch timeline with dependencies
gantt
title Pulse Analytics v2.0 Launch Timeline
dateFormat YYYY-MM-DD
axisFormat %b %d
section Development
Backend API :crit, backend, 2026-05-04, 3w
Frontend Dashboard :crit, frontend, 2026-05-11, 4w
Data Pipeline :pipeline, 2026-05-04, 2w
section Quality
Integration Testing :crit, integration, after frontend, 1w
UAT :crit, uat, after integration, 1w
Performance Testing :perf, after integration, 3d
section Launch
Documentation :docs, after uat, 1w
Marketing Prep :marketing, after uat, 1w
GA Release :milestone, ga, after docs, 0dWhat this communicates: The Gantt chart exposes the critical path: Backend API must finish before Integration Testing can start, and any delay in that chain pushes GA. It also shows that Data Pipeline and Performance Testing are off the critical path -- they have slack. A bullet list of tasks with dates would hide these dependency relationships entirely.
---
Example 3: Sequence -- Webhook Integration Flow
Context: The technical spec needs to show how webhook delivery works across five services, including the async handoff and retry behavior. Engineers reviewing the spec need to see the exact message flow.
Filled Worksheet
What I'm showing: The multi-service interaction flow for webhook event delivery, including async processing and retry logic. Audience: Backend engineers and integration partners reading the technical spec. Where this will appear: Pulse Analytics v2.0 Technical Spec, "Webhook Architecture" section.
Cardinal Rule Check:
- [x] This shows branching, relationships, or flow that a list would flatten
- [x] A numbered list or table would NOT communicate this more clearly
Five participants exchanging messages with async boundaries, a retry loop, and conditional behavior (success vs. failure). This is inherently a multi-party interaction.
Selected type: Sequence Why this type: Multi-party message exchange with async boundaries and conditional flows -- sequence diagrams show this precisely. Considered alternatives: Flowchart (would work for the overall flow, but loses the participant swimlanes that make service responsibilities clear).
Node Inventory:
| Node/Entity | Role/Label | Notes |
|---|---|---|
| CustomerApp | Customer App | External caller |
| PulseAPI | Pulse API | Entry point, sync response |
| EventProcessor | Event Processor | Async processing |
| WebhookService | Webhook Service | Delivery + retry |
| CustomerEndpoint | Customer Endpoint | External receiver |
Total node count: 5 participants (within sequence limit of 6)
Resulting Diagram
%% MEANING: Webhook delivery flow showing async handoff and retry logic
sequenceDiagram
participant CustomerApp as Customer App
participant PulseAPI as Pulse API
participant EventProcessor as Event Processor
participant WebhookService as Webhook Service
participant CustomerEndpoint as Customer Endpoint
CustomerApp->>PulseAPI: Send Event
PulseAPI->>PulseAPI: Validate Payload
PulseAPI-->>CustomerApp: 202 Accepted
PulseAPI-)EventProcessor: Queue Event (async)
EventProcessor->>EventProcessor: Process + Enrich
EventProcessor-)WebhookService: Dispatch Webhook
loop Retry (max 3 attempts)
WebhookService->>CustomerEndpoint: POST webhook payload
alt Success
CustomerEndpoint-->>WebhookService: 200 OK
WebhookService->>WebhookService: Mark Delivered
else Delivery Failure
CustomerEndpoint-->>WebhookService: 5xx / Timeout
WebhookService->>WebhookService: Backoff + Retry
end
endWhat this communicates: The sequence diagram makes three things visible that prose obscures. First, the sync/async boundary: the customer gets 202 immediately while processing happens in the background. Second, the retry loop with backoff is a distinct phase, not buried in a paragraph. Third, the alt block shows that success and failure are handled differently at the same interaction point. Engineers can trace the exact message flow between services without reading paragraphs of text.
---
Example 4: Quadrant -- Feature Prioritization
Context: The planning meeting needs a visual to drive prioritization discussion. Eight candidate features need to be evaluated on two dimensions: engineering effort and user impact.
Filled Worksheet
What I'm showing: Relative positioning of 8 candidate features on effort vs. impact dimensions to guide prioritization. Audience: Product and engineering leads in the quarterly planning meeting. Where this will appear: Planning meeting deck, "Prioritization" slide.
Cardinal Rule Check:
- [x] This shows branching, relationships, or flow that a list would flatten
- [x] A numbered list or table would NOT communicate this more clearly
Two-dimensional positioning reveals clusters and outliers that a sorted list on a single dimension would miss. Features in the "quick wins" quadrant are only visible when both dimensions are plotted.
Selected type: Quadrant Why this type: Two-axis comparison with labeled quadrants -- purpose-built for 2D prioritization. Considered alternatives: None -- no other mermaid type handles 2D scatter positioning.
Node Inventory:
| Node/Entity | Role/Label | Notes |
|---|---|---|
| Dashboard Export | Quick Win | Low effort, high impact |
| Custom Alerts | Strategic Bet | High effort, high impact |
| Dark Mode | Low Priority | Low effort, low impact |
| API Rate Limits | Near boundary | Medium effort, medium impact |
| SSO Integration | Strategic Bet | High effort, high impact |
| Bulk Import | Quick Win | Low effort, high impact |
| Audit Log | Near boundary | Medium effort, medium impact |
| Mobile App | Strategic Bet | Very high effort, very high impact |
Total node count: 8 data points (within quadrant limit of 10-12)
Resulting Diagram
%% MEANING: Feature prioritization for Pulse Analytics v2.0 planning meeting
quadrantChart
title Feature Prioritization Matrix
x-axis "Low Effort" --> "High Effort"
y-axis "Low Impact" --> "High Impact"
quadrant-1 "Strategic Bets"
quadrant-2 "Quick Wins"
quadrant-3 "Low Priority"
quadrant-4 "Reconsider"
"Dashboard Export": [0.2, 0.8]
"Custom Alerts": [0.7, 0.85]
"Dark Mode": [0.3, 0.4]
"API Rate Limits": [0.5, 0.6]
"SSO Integration": [0.8, 0.7]
"Bulk Import": [0.15, 0.65]
"Audit Log": [0.6, 0.5]
"Mobile App": [0.9, 0.9]What this communicates: The quadrant chart instantly reveals that Dashboard Export and Bulk Import are quick wins -- high impact, low effort -- while Mobile App demands the most investment for the highest payoff. The spatial clustering makes trade-offs visible: API Rate Limits and Audit Log sit near the center, suggesting they need further analysis before committing. A ranked list sorted by impact alone would hide the effort dimension that makes prioritization actionable.
---
Key Takeaways
- The worksheet prevents false starts. Inventorying nodes before writing code catches missing participants, states, or data points early -- not mid-diagram when restructuring is expensive.
- The cardinal rule check saved work. If any of these examples had been a simple linear sequence, the worksheet would have redirected to a list before any mermaid code was written.
- Diagram type selection is a design decision. Each example considered alternatives and chose the type that best matched the communication need, not the one the PM was most familiar with.
- Context around the diagram matters. The mermaid code block alone is not enough -- the "What this communicates" framing helps the audience know what to look for in the diagram.
PM Use Cases: Task-to-Diagram Quick Reference
This guide helps you find the right diagram type by starting from what you're trying to communicate, rather than from a diagram type you already know.
Quick-Reference Table
| # | PM Task | Primary Type | Alternative |
|---|---|---|---|
| 1 | Showing a decision or approval process | Flowchart | State |
| 2 | Specifying multi-service interactions | Sequence | Flowchart |
| 3 | Mapping feature lifecycle or status transitions | State | Flowchart |
| 4 | Tracking work stages | Kanban | State |
| 5 | Planning a release or sprint timeline | Gantt | Timeline |
| 6 | Documenting version history or milestones | Timeline | Gantt |
| 7 | Prioritizing backlog items (2D) | Quadrant | - |
| 8 | Showing allocation or composition | Pie | Treemap |
| 9 | Decomposing a problem or brainstorming | Mindmap | - |
| 10 | Documenting domain models or data relationships | ER | Class |
| 11 | Mapping API or object contracts | Class | ER |
| 12 | Showing system topology or infrastructure | Architecture | Flowchart |
| 13 | Visualizing flow quantities or budget allocation | Sankey | Pie |
| 14 | Showing hierarchical proportional data | Treemap | Pie |
| 15 | Displaying trends or time-series metrics | XY-Chart | - |
---
Use Case 1: Showing a Decision or Approval Process
Best diagram type: Flowchart | Alternative: State
A flowchart naturally maps to how PMs think about approval gates: requests come in, conditions are evaluated, and outcomes branch. The diamond decision nodes make branching logic visible in a way that prose obscures.
Example: Feature request triage - an incoming request flows through feasibility check and priority assessment, then gets approved, deferred, or rejected.
flowchart TD
A[New Feature Request] --> B{Feasibility Check}
B -->|Feasible| C{Priority Assessment}
B -->|Not Feasible| D[Rejected . Notify Requester]
C -->|P0/P1| E[Approved . Add to Roadmap]
C -->|P2| F{Capacity Available?}
C -->|P3+| G[Deferred . Add to Backlog]
F -->|Yes| E
F -->|No| G
E --> H[Assign to Sprint]
D --> I[Archive with Rationale]
G --> IWhen to use the alternative instead: Use a State diagram when the emphasis is on the request's status over time rather than the branching logic of the triage process.
See diagram-catalog.md#flowchart for full syntax reference.---
Use Case 2: Specifying Multi-Service Interactions
Best diagram type: Sequence | Alternative: Flowchart
Sequence diagrams show the back-and-forth between systems in time order. When you need to communicate "the app calls the API, which calls the payment service, which responds with a token," sequence diagrams make the call chain and response flow unmistakable.
Example: Mobile app checkout flow between the app, API gateway, payment service, and notification service.
sequenceDiagram
actor User
participant App as Mobile App
participant API as API Gateway
participant Pay as Payment Service
participant Notify as Notification Service
User->>App: Tap "Place Order"
App->>API: POST /orders
API->>Pay: Charge $49.99
Pay-->>API: Payment confirmed (txn-7829)
API->>Notify: Send order confirmation
Notify-->>User: Email receipt
API-->>App: 201 Created (order-id: 4412)
App-->>User: Show confirmation screenWhen to use the alternative instead: Use a Flowchart when the interaction is simple (two services, no branching) and you care more about the decision logic than the call sequence.
See diagram-catalog.md#sequence for full syntax reference.---
Use Case 3: Mapping Feature Lifecycle or Status Transitions
Best diagram type: State | Alternative: Flowchart
State diagrams focus on what states a thing can be in and what triggers transitions between them. This is ideal for lifecycle questions: "Can a feature go from QA back to Development? Under what conditions?"
Example: Feature status lifecycle from idea through release.
stateDiagram-v2
[*] --> Draft
Draft --> InReview : Author submits
InReview --> Approved : PM approves
InReview --> Draft : Reviewer requests changes
Approved --> InDevelopment : Sprint planning assigns
InDevelopment --> InQA : Dev marks complete
InQA --> InDevelopment : QA finds blocker
InQA --> Staged : QA passes
Staged --> Released : Deploy to production
Released --> [*]When to use the alternative instead: Use a Flowchart when you need to show the decision logic that determines transitions, rather than just listing the valid transitions themselves.
See diagram-catalog.md#state for full syntax reference.---
Use Case 4: Tracking Work Stages
Best diagram type: Kanban | Alternative: State
Kanban diagrams show work items distributed across pipeline stages. They answer the question "Where is everything right now?" rather than "How does something move through stages?"
Example: Content creation pipeline for a product launch blog series.
---
config:
kanban:
ticketBaseUrl: ""
---
kanban-beta
Backlog
id1["SEO keyword research"]
id2["Competitive comparison post"]
id3["Customer success story"]
Writing
id4["Launch announcement draft"]
id5["Migration guide v2 to v3"]
Review
id6["Performance benchmarks post"]
Design
id7["Feature walkthrough with screenshots"]
Published
id8["Getting started tutorial"]
id9["API reference update"]When to use the alternative instead: Use a State diagram when you need to document the rules governing how items move between columns, rather than showing a snapshot of current work distribution.
See diagram-catalog.md#kanban for full syntax reference.---
Use Case 5: Planning a Release or Sprint Timeline
Best diagram type: Gantt | Alternative: Timeline
Gantt charts show tasks with durations, dependencies, and parallel tracks. They answer scheduling questions: "Can QA start before design finishes? When is the critical path?"
Example: Mobile app v3.0 release plan across 6 weeks.
gantt
title Mobile App v3.0 Release Plan
dateFormat YYYY-MM-DD
axisFormat %b %d
section Design
UX wireframes :des1, 2026-04-07, 5d
Visual design :des2, after des1, 4d
Design review :des3, after des2, 2d
section Development
Core feature build :dev1, after des2, 8d
API integration :dev2, after des1, 6d
UI polish :dev3, after des3, 4d
section QA
Test plan creation :qa1, after des3, 2d
Regression testing :qa2, after dev1, 4d
UAT :qa3, after qa2, 3d
section Launch
Staged rollout (10%) :launch1, after qa3, 2d
Full rollout :milestone, after launch1, 0dWhen to use the alternative instead: Use a Timeline when you need a simpler, milestone-focused view without task durations or dependencies - for example, a quarterly roadmap for executives.
See diagram-catalog.md#gantt for full syntax reference.---
Use Case 6: Documenting Version History or Milestones
Best diagram type: Timeline | Alternative: Gantt
Timelines show milestones in chronological order without the complexity of durations and dependencies. They are ideal for "here is what we shipped and when" communications.
Example: Product evolution over 4 quarters showing key features shipped.
timeline
title Acme Platform . 2025 Product Milestones
section Q1
Jan : Team onboarding dashboard
: SSO integration
Mar : Public API beta launch
section Q2
Apr : Mobile app v1.0
Jun : Webhook support
: Custom reporting
section Q3
Jul : Enterprise tier launch
Sep : SOC 2 certification
section Q4
Oct : AI-assisted search
Dec : Multi-region deployment
: 10K customer milestoneWhen to use the alternative instead: Use a Gantt chart when stakeholders need to see how long each effort took, not just when milestones landed.
See diagram-catalog.md#timeline for full syntax reference.---
Use Case 7: Prioritizing Backlog Items (2D)
Best diagram type: Quadrant | Alternative: .
Quadrant charts place items on two axes, making trade-offs visible at a glance. The classic PM use is effort vs. impact, but any two-dimensional prioritization (risk vs. value, urgency vs. importance) works.
Example: Q4 feature prioritization on effort vs. user impact axes.
quadrantChart
title Q4 Feature Prioritization
x-axis "Low Effort" --> "High Effort"
y-axis "Low User Impact" --> "High User Impact"
quadrant-1 "Do First"
quadrant-2 "Plan Carefully"
quadrant-3 "Reconsider"
quadrant-4 "Quick Wins"
"SSO support": [0.75, 0.85]
"Dark mode": [0.25, 0.55]
"Bulk export": [0.40, 0.80]
"Admin audit log": [0.85, 0.70]
"Emoji reactions": [0.15, 0.20]
"CSV import": [0.30, 0.65]
"Onboarding wizard": [0.60, 0.90]
"Custom themes": [0.50, 0.15]
"Keyboard shortcuts": [0.20, 0.45]See diagram-catalog.md#quadrant for full syntax reference.---
Use Case 8: Showing Allocation or Composition
Best diagram type: Pie | Alternative: Treemap
Pie charts show how a whole breaks into parts. They work well when the total adds up to 100% and you have 3-7 slices. Beyond that, smaller slices become unreadable.
Example: Engineering team time allocation across work categories.
pie title Engineering Time Allocation . Q1 2026
"Feature Development" : 42
"Tech Debt Reduction" : 20
"Bug Fixes" : 15
"Code Reviews" : 10
"On-call & Support" : 8
"Meetings & Planning" : 5When to use the alternative instead: Use a Treemap when you have hierarchical categories (e.g., Feature Development breaks into sub-projects) or more than 7 slices.
See diagram-catalog.md#pie for full syntax reference.---
Use Case 9: Decomposing a Problem or Brainstorming
Best diagram type: Mindmap | Alternative: .
Mindmaps radiate outward from a central topic, making them natural for brainstorming and problem decomposition. They show hierarchy without implying sequence or flow.
Example: User onboarding improvement - branches for key improvement areas with sub-items.
mindmap
root((Onboarding Improvement))
First Run Experience
Welcome wizard
Role-based setup flow
Sample data sandbox
Documentation
Interactive tutorials
Video walkthroughs
Context-sensitive help
Guided Tours
Feature spotlight tooltips
Progressive disclosure
Achievement badges
Email Sequences
Day 1 welcome
Day 3 key-feature nudge
Day 7 check-in survey
Day 14 advanced tipsSee diagram-catalog.md#mindmap for full syntax reference.---
Use Case 10: Documenting Domain Models or Data Relationships
Best diagram type: ER | Alternative: Class
Entity-relationship diagrams show the objects in your domain and how they relate, including cardinality (one-to-many, many-to-many). They are the standard for communicating data models to engineers.
Example: E-commerce domain model with core entities and cardinality.
erDiagram
CUSTOMER ||--o{ ORDER : places
CUSTOMER {
string email
string name
string tier
}
ORDER ||--|{ ORDER_LINE : contains
ORDER {
int order_id
date created_at
string status
}
ORDER_LINE }o--|| PRODUCT : references
PRODUCT {
int product_id
string name
decimal price
}
ORDER ||--|| PAYMENT : "paid via"
PAYMENT {
string method
decimal amount
string transaction_id
}
ORDER ||--o| SHIPMENT : "fulfilled by"
SHIPMENT {
string carrier
string tracking_number
date estimated_arrival
}When to use the alternative instead: Use a Class diagram when you need to show methods and interfaces (behavioral contracts) in addition to data attributes.
See diagram-catalog.md#er-entity-relationship for full syntax reference.---
Use Case 11: Mapping API or Object Contracts
Best diagram type: Class | Alternative: ER
Class diagrams show objects with their attributes, methods, and relationships (inheritance, composition). Use them when you need to communicate behavioral contracts - not just "what data exists" but "what operations are available."
Example: Notification service API contracts showing services, templates, channels, and delivery status.
classDiagram
class NotificationService {
+send(template, channel, recipient) DeliveryStatus
+schedule(template, channel, recipient, sendAt) string
+cancel(notificationId) bool
}
class Template {
+string id
+string name
+string body
+render(variables) string
}
class Channel {
<<interface>>
+deliver(content, recipient) DeliveryStatus
}
class EmailChannel {
+deliver(content, recipient) DeliveryStatus
}
class PushChannel {
+deliver(content, recipient) DeliveryStatus
}
class DeliveryStatus {
+string status
+datetime sentAt
+string errorMessage
}
NotificationService --> Template : uses
NotificationService --> Channel : sends via
Channel <|.. EmailChannel
Channel <|.. PushChannel
NotificationService --> DeliveryStatus : returnsWhen to use the alternative instead: Use an ER diagram when the focus is on data relationships and cardinality rather than methods and interfaces.
See diagram-catalog.md#class for full syntax reference.---
Use Case 12: Showing System Topology or Infrastructure
Best diagram type: Architecture | Alternative: Flowchart
Note: Architecture diagrams are experimental (Mermaid v11.1.0+). Verify support in your rendering environment before using.
Architecture diagrams show services, databases, and infrastructure grouped by logical boundaries. They communicate "what talks to what" at a system level with purpose-built iconography.
Example: SaaS platform topology with web, API, worker, and data tiers.
architecture-beta
group web(cloud)[Web Tier]
group api(cloud)[API Tier]
group data(cloud)[Data Tier]
service cdn(internet)[CDN] in web
service webapp(server)[Web App] in web
service gateway(server)[API Gateway] in api
service workers(server)[Worker Pool] in api
service db(database)[PostgreSQL] in data
service cache(database)[Redis Cache] in data
cdn:R --> L:webapp
webapp:R --> L:gateway
gateway:R --> L:db
gateway:B --> T:cache
gateway:B --> T:workers
workers:R --> L:dbWhen to use the alternative instead: Use a Flowchart when architecture diagram support is unavailable in your environment, or when you need to show decision logic within the system flow.
See diagram-catalog.md#architecture for full syntax reference.---
Use Case 13: Visualizing Flow Quantities or Budget Allocation
Best diagram type: Sankey | Alternative: Pie
Note: Sankey diagrams are experimental (Mermaid v10.3.0+). Verify support in your rendering environment before using.
Sankey diagrams show flows between nodes with width proportional to quantity. They excel at showing how a budget, traffic, or resource pool splits and re-splits across categories.
Example: Marketing budget flow from total allocation down through channels and sub-channels.
sankey-beta
"Marketing Budget","Digital Marketing",450000
"Marketing Budget","Events & Conferences",200000
"Marketing Budget","Content Marketing",150000
"Marketing Budget","Brand & Creative",100000
"Marketing Budget","Tools & Analytics",50000
"Digital Marketing","Paid Search",180000
"Digital Marketing","Social Ads",150000
"Digital Marketing","Display & Retargeting",80000
"Digital Marketing","SEO Program",40000
"Content Marketing","Blog Production",60000
"Content Marketing","Video Content",50000
"Content Marketing","Whitepapers & Guides",40000When to use the alternative instead: Use a Pie chart when you only need to show the top-level split without showing how categories subdivide further.
See diagram-catalog.md#sankey for full syntax reference.---
Use Case 14: Showing Hierarchical Proportional Data
Best diagram type: Treemap | Alternative: Pie
Note: Treemap diagrams are experimental (Mermaid v10.3.0+). Verify support in your rendering environment before using.
Treemaps show hierarchical data as nested rectangles sized by value. They reveal both the hierarchy and the relative magnitude of each segment simultaneously.
Example: Support ticket volume by product area and issue type.
%%{init: {"treemap": {"padding": 4}} }%%
treemap-beta
root["Support Tickets . March 2026"]
["Payments (312)"]
["Failed transactions (142)"]
["Refund requests (98)"]
["Invoice issues (72)"]
["User Management (245)"]
["Login problems (120)"]
["Permission errors (85)"]
["Account deletion (40)"]
["Integrations (189)"]
["API errors (95)"]
["Webhook failures (54)"]
["OAuth setup (40)"]
["Reporting (87)"]
["Export failures (52)"]
["Dashboard bugs (35)"]When to use the alternative instead: Use a Pie chart when data is flat (single level, no hierarchy) and has fewer than 7 categories.
See diagram-catalog.md#treemap for full syntax reference.---
Use Case 15: Displaying Trends or Time-Series Metrics
Best diagram type: XY-Chart | Alternative: .
Note: XY-Chart is experimental (Mermaid v10.0.0+). Verify support in your rendering environment before using.
XY-Charts display data points on x and y axes, supporting bar and line charts. They are the right choice for showing metrics over time - adoption curves, revenue trends, or sprint velocity.
Example: Weekly active users over 8 weeks post-launch for two product cohorts.
xychart-beta
title "Weekly Active Users . Post-Launch"
x-axis ["Wk 1", "Wk 2", "Wk 3", "Wk 4", "Wk 5", "Wk 6", "Wk 7", "Wk 8"]
y-axis "Active Users" 0 --> 5000
bar [820, 1450, 2100, 2800, 3200, 3600, 3900, 4200]
line [820, 1450, 2100, 2800, 3200, 3600, 3900, 4200]See diagram-catalog.md#xy-chart for full syntax reference.---
Choosing Between Primary and Alternative
When the quick-reference table lists an alternative, here is the deciding factor:
| Primary | Alternative | Choose the alternative when... |
|---|---|---|
| Flowchart | State | Focus is on valid states, not decision logic |
| Sequence | Flowchart | Interaction is simple with no async or parallel calls |
| State | Flowchart | You need to show the decision logic behind transitions |
| Kanban | State | You need transition rules, not a snapshot of current work |
| Gantt | Timeline | Audience needs milestones only, not task durations |
| Timeline | Gantt | Audience needs to see durations and dependencies |
| Pie | Treemap | Data has nested categories or more than 7 segments |
| ER | Class | You need to show methods and behavioral contracts |
| Class | ER | Focus is on data relationships and cardinality |
| Architecture | Flowchart | Your environment does not support architecture diagrams |
| Sankey | Pie | You only need a single-level breakdown |
| Treemap | Pie | Data is flat with fewer than 7 categories |
Mermaid Syntax Guide for Product Managers
A practical reference for writing valid, readable mermaid diagrams.
---
1. Label Quoting Rules
Mermaid uses certain characters and words as syntax. When those appear inside your node labels, wrap the label in double quotes.
Quote when your label contains:
- Spaces (
User Login Flow) - Special characters (
>,<,-,#, parentheses, brackets, braces) - Reserved words used as node IDs:
end,graph,subgraph,click,style,class,default
How to quote: Wrap the entire label in double quotes inside the shape brackets.
Before/After Examples
Failure 1 -- Parentheses in label without quotes:
%% BROKEN: parentheses are interpreted as node shape delimiters
flowchart LR
A[User Login (SSO)] --> B[Dashboard]%% FIXED: quoting prevents mermaid from parsing special characters in labels
flowchart LR
A["User Login (SSO)"] --> B["Dashboard"]Failure 2 -- Reserved word `end` as a node label:
flowchart TD
start --> process --> endMermaid interprets end as the closing keyword for a subgraph. Fix:
flowchart TD
start --> process --> endNode["End"]Failure 3 -- Parentheses in label:
flowchart LR
A[Calculate ROI (annualized)] --> B[Report]The parentheses conflict with mermaid's shape syntax. Fix:
flowchart LR
A["Calculate ROI (annualized)"] --> B["Report"]Failure 4 -- Angle bracket in label:
flowchart LR
A[Revenue > $1M] --> B[Enterprise Tier]The > is interpreted as an asymmetric shape. Fix:
flowchart LR
A["Revenue > $1M"] --> B["Enterprise Tier"]---
2. Special Character Escaping
Characters That Conflict with Mermaid Syntax
| Character | Mermaid Meaning | Problem in Labels |
|---|---|---|
> | Asymmetric shape, edge arrow | Breaks node shape parsing |
< | Edge arrow | Breaks edge parsing |
- | Edge connector | Can be misread as an edge |
# | Mermaid Unicode escape prefix (#35; = #) | Triggers entity lookup |
( ) | Round node shape | Breaks shape brackets |
[ ] | Square node shape | Breaks shape brackets |
{ } | Diamond node shape | Breaks shape brackets |
Characters That Conflict with Markdown Renderers
| Character | Markdown Meaning | Effect |
|---|---|---|
> at line start | Blockquote | Line removed from diagram |
<word> | HTML tag | Swallowed or rendered as HTML |
- at line start | List item | Breaks diagram structure |
Escaping Strategies
Strategy 1: Quote the whole label (preferred)
flowchart LR
A["Cost < $500"] --> B["Margin > 40%"]Strategy 2: HTML entities (last resort)
Use when quoting alone does not resolve the issue:
flowchart LR
A["Cost < $500"] --> B["Margin > 40%"]Common HTML entities: > for >, < for <, & for &. For #, use Mermaid's native escape #35; (not HTML #).
General rule: Try double-quoting first. Only use HTML entities if quoting fails.
---
3. Node Declaration Order
In flowcharts, declare a node (give it a shape and label) before referencing it in edges. Mermaid will not always fail on out-of-order declarations, but it can produce unexpected shapes or missing labels.
Failure -- node referenced before declaration:
flowchart TD
A --> B --> C
B{"Decision Point"}Node B may render as a plain rectangle instead of a diamond because the edge A --> B was parsed before the diamond shape was declared.
Fix -- declare first, then connect:
flowchart TD
A["Start"]
B{"Decision Point"}
C["End"]
A --> B --> CWhen this matters most: Flowcharts and subgraphs. Sequence and state diagrams handle declaration order more flexibly.
Practical tip: Group all node declarations at the top, then list all edges below.
---
4. Direction and Layout
Direction Options
Set direction on the first line after the diagram type keyword:
flowchart LR
A --> B --> C| Direction | Meaning | Best For |
|---|---|---|
TD or TB | Top to bottom (default) | Hierarchies, org charts, decision trees |
LR | Left to right | Process flows, timelines, pipelines |
BT | Bottom to top | Rarely used; escalation paths |
RL | Right to left | Rarely used; right-to-left reading contexts |
When to Use Each
- TD -- Default. Parent-child relationships, approval chains, tree structures.
- LR -- Sequences over time: user journeys, release pipelines, workflow steps.
- BT and RL -- Rarely needed. Only if the content has a strong spatial metaphor.
ELK Layout Engine for Complex Diagrams
When the default layout produces excessive edge crossings or overlapping nodes, try the ELK renderer:
%%{init: {"flowchart": {"defaultRenderer": "elk"}}}%%
flowchart LR
A --> B --> C
A --> D --> C
B --> E
D --> EELK produces cleaner layouts for diagrams with many crossing edges but renders slower.
Troubleshooting Edge Crossings
1. Change direction -- Switch between TD and LR to untangle edges. 2. Reorder node declarations -- Layout depends partly on declaration order. 3. Add intermediate nodes -- Insert a routing node to control edge paths:
flowchart LR
A --> B
B --> mid[ ] --> C
style mid width:0px,height:0pxNote: Invisible node techniques vary by renderer. Test in your target environment.
---
5. Styling and Accessibility
Semantic Color Palette
WCAG AA compliant (minimum 3:1 contrast ratio). Use consistently across all diagrams.
| Meaning | Background | Text | Use For |
|---|---|---|---|
| Success | #d4edda | #155724 | Completed, approved, live |
| Error | #f8d7da | #721c24 | Failed, blocked, rejected |
| Warning | #fff3cd | #856404 | At risk, needs attention |
| Info | #cce5ff | #004085 | Informational, in progress |
| Neutral | #e2e3e5 | #383d41 | Default, no status |
Accessibility Rules
1. Dark text on light backgrounds, always. 2. Never rely on color alone. Use labels ("BLOCKED", "DONE") and shapes (diamonds for decisions, rectangles for actions) so colorblind readers can understand the diagram without seeing any color. 3. WCAG AA minimum: 3:1 contrast ratio for graphical elements.
Applying Styles
Syntax differs by diagram type:
Flowchart -- use `:::className`:
flowchart LR
A["Feature Live"]:::success --> B["Monitor"]:::info
C["Deploy Failed"]:::error --> D["Rollback"]:::warning
classDef success fill:#d4edda,stroke:#155724,color:#155724
classDef error fill:#f8d7da,stroke:#721c24,color:#721c24
classDef warning fill:#fff3cd,stroke:#856404,color:#856404
classDef info fill:#cce5ff,stroke:#004085,color:#004085State diagram -- use `class` statement:
stateDiagram-v2
[*] --> Active
Active --> Blocked
Blocked --> Active
Active --> Done
class Active info
class Blocked error
class Done success
classDef success fill:#d4edda,stroke:#155724,color:#155724
classDef error fill:#f8d7da,stroke:#721c24,color:#721c24
classDef info fill:#cce5ff,stroke:#004085,color:#004085---
6. Comments
Use %% to add comments. Comments are not rendered -- they exist for maintainers.
Comment Categories
Use a prefix to signal the comment's purpose:
| Prefix | Purpose | Example |
|---|---|---|
MEANING | Why this diagram exists | %% MEANING: Shows the approval chain for enterprise deals |
COLOR | Why a specific color was chosen | %% COLOR: Red = blocked by legal review |
GOTCHA | Non-obvious syntax or workaround | %% GOTCHA: "end" is reserved; use endNode as ID |
Example
%% MEANING: Release pipeline from PR merge to production deploy
%% GOTCHA: Node "end" renamed to "done" because "end" is a reserved word
flowchart LR
pr["PR Merged"] --> staging["Staging Deploy"]
staging --> qa["QA Sign-off"]
qa --> prod["Production"]
prod --> done["Done"]
%% COLOR: Green = automated steps, blue = manual gates
class pr,staging success
class qa,prod info
classDef success fill:#d4edda,stroke:#155724,color:#155724
classDef info fill:#cce5ff,stroke:#004085,color:#004085---
7. Configuration Blocks
Theme Selection
Mermaid ships with five built-in themes:
| Theme | When to Use |
|---|---|
base | Recommended when applying custom colors. Starts minimal so your colors show cleanly. |
default | Fine for most diagrams with no custom styling. |
dark | When embedding in a dark-mode interface. |
forest | Green-toned; rarely needed. |
neutral | Grayscale; good for print. |
Configuration Syntax
Place the init block on the very first line of the diagram, before the diagram type:
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#cce5ff", "primaryTextColor": "#004085", "primaryBorderColor": "#004085"}}}%%
flowchart LR
A["Step 1"] --> B["Step 2"] --> C["Step 3"]When to Configure vs. When to Use Defaults
Use defaults for quick diagrams and internal docs.
Configure when embedding in a themed site, enforcing brand colors, or the default theme clashes with surrounding content. Most PM diagrams are fine with defaults plus classDef on individual nodes.
---
8. Node and Participant Limits
These are guidelines, not hard rules -- but exceeding them usually means the diagram should be split.
| Diagram Type | Recommended Max | Notes |
|---|---|---|
| Flowchart | 12 nodes | Split with subgraphs above 12 |
| Sequence | 6 participants | Use aliases for long names |
| Class | 8 classes | Split by domain boundary |
| ER | 8-10 entities | Focus on one bounded context |
| State | 10 states | Use composite states for complex machines |
| Gantt | 20 tasks | Group with sections |
| Mindmap | 4 levels deep | Balance branch width |
| Pie | 3-7 slices | Group small items into "Other" |
| Quadrant | 10-12 points | Keep labels under 12 characters |
| Kanban | 10-15 tasks | 3-5 columns |
| Architecture | 10-20 services | Group with subgraphs |
| Timeline | ~15 events | Use sections for eras |
| Sankey | 5-15 nodes | Aggregate tiny flows into "Other" |
| Treemap | ~30 leaf nodes | 2-3 levels max |
| XY-Chart | 4 lines, 6-8 points | More lines or points obscures trends |
When You Exceed the Limit
1. Split into multiple diagrams. "System Overview" + "Payment Detail" beats one mega-diagram. 2. Use subgraphs or sections. Group related nodes into clusters. 3. Aggregate small items. Combine minor categories into "Other" (pie, Sankey) or collapse low-traffic paths (flowcharts).
---
9. Pre-Commit Validation Checklist
Run through this list before finalizing any diagram:
1. Paste into [mermaid.live](https://mermaid.live) -- Does it render without errors? 2. All labels with spaces are quoted -- Search for [ and check that labels containing spaces use ["..."] syntax. 3. No unescaped special characters in labels -- Check for >, <, (, ), # inside labels. 4. Node count within type-specific limit -- Count your nodes against the table in section 8. 5. Direction makes sense -- LR for timelines and process flows, TD for hierarchies and trees. 6. Colors tested in both light and dark mode -- Paste into mermaid.live and toggle the theme. 7. No linear sequences that should be lists -- If your "diagram" is just A --> B --> C --> D with no branching, a numbered list communicates the same information more simply. 8. Labels are readable at normal zoom -- If you have to zoom in to read labels, the diagram has too many nodes or labels are too long.
---
10. Common Rendering Failures
| Symptom | Cause | Fix |
|---|---|---|
| Blank diagram | Typo in diagram type keyword or malformed init block | Verify spelling of the diagram type keyword. Prefer flowchart over legacy graph for new diagrams |
| Missing node | Node referenced in an edge but never declared with a shape | Declare the node with a label before using it in edges |
| Broken arrow | Wrong arrow syntax for the diagram type (e.g., --> in a sequence diagram) | Use ->> for sequence diagrams, --> for flowcharts |
| Label shows raw text | Unquoted label with special characters | Wrap label in double quotes: ["label text"] |
| Diagram too wide | Using TD (top-down) for a long sequential process | Switch to LR (left-right) direction |
| Nodes overlap | Too many nodes without subgraph grouping | Reduce node count or group with subgraphs |
| Colors invisible in dark mode | Light text color on what becomes a light background | Use the semantic palette from section 5; test in dark mode |
| "Parse error" message | Reserved word (end, graph, default) used as a bare node ID | Rename the node ID and use quotes for the display label |
| Subgraph won't connect to outside nodes | Wrong syntax for connecting from inside a subgraph | Connect using node IDs, not the subgraph ID, or use subgraph id --> syntax |
| Timeline entries missing | Wrong indentation or missing section headers | Each event must be indented under a section; check whitespace |
---
Quick reference: Quote labels with spaces (["label"]). TD for trees, LR for processes. Use the five semantic colors. If it feels crowded, split the diagram. Always paste into mermaid.live before committing.
Mermaid Diagram Planning Worksheet
<!-- Fill out this worksheet before writing mermaid code. It prevents wasted effort by ensuring you've chosen the right diagram type and inventoried your content. -->
1. Diagram Purpose
<!-- What relationship, flow, hierarchy, or proportion are you communicating? Who is the audience? -->
What I'm showing: Audience: Where this will appear: <!-- e.g., PRD, roadmap deck, technical spec, wiki page -->
2. Cardinal Rule Check
<!-- Does this need a diagram, or would a list/table communicate it better? -->
- [ ] This shows branching, relationships, or flow that a list would flatten
- [ ] A numbered list or table would NOT communicate this more clearly
If both boxes are not checked, use a list or table instead.
3. Diagram Type Selection
<!-- Use the selection guide in SKILL.md or browse diagram-catalog.md to pick the right type. -->
Selected type: Why this type: <!-- What does this type show that others don't? --> Considered alternatives: <!-- Which other types did you evaluate? -->
4. Node Inventory
<!-- List every entity, participant, state, or data point before writing code. This prevents mid-diagram discovery of missing nodes. -->
| Node/Entity | Role/Label | Notes |
|---|---|---|
Total node count: ___ (check against type limit in diagram-catalog.md)
5. Draft Mermaid Code
%% MEANING: [Why this diagram exists]
%% Type: [selected type]
%% Direction: [TD/LR/BT/RL if applicable]6. Validation Checklist
- [ ] Renders without error (tested in mermaid.live or target environment)
- [ ] Cardinal rule satisfied -- a list or table would not communicate this more clearly
- [ ] Not a linear sequence -- has branching, relationships, or hierarchy
- [ ] Labels with spaces/special characters are quoted
- [ ] Special characters escaped where needed
- [ ] Node count within type limit
- [ ] Colors are accessible (WCAG AA 3:1 contrast, black text on light backgrounds)
- [ ] Color is never the sole differentiator -- shapes and labels also distinguish elements
- [ ] Has descriptive title or surrounding context
- [ ]
%%comments document any non-obvious layout or grouping choices
Related skills
How it compares
Pick utility-mermaid-diagrams over freeform diagram prompts when Mermaid must render in markdown specs with type-specific limits and accessibility checks.
FAQ
How many Mermaid diagram types does utility-mermaid-diagrams cover?
utility-mermaid-diagrams documents all 15 Mermaid diagram types including flowchart, sequence, state, gantt, ER, class, architecture, sankey, treemap, and XY-chart with per-type syntax in references/diagram-catalog.md.
When should utility-mermaid-diagrams use a diagram vs a list?
utility-mermaid-diagrams applies the cardinal rule: diagram only when branching, relationships, or flow would be flattened by a list or table. A linear five-step process should stay a numbered list.
How does utility-mermaid-diagrams prevent render failures?
utility-mermaid-diagrams enforces six syntax principles—quote labels with spaces, escape special characters, declare nodes before edges, respect node limits, add %% comments, and test in mermaid.live or VS Code preview.