Mermaid Cheat Sheet

17 diagram types · 39 examples, aligned with Mermaid Live Editor (type + secondary sample). Copy one or open it in the Editor.

Common diagrams

Flowchart 4 examples

Basic Flowchart

flowchart TD
  A[Christmas] -->|Get money| B(Go shopping)
  B --> C{Let me think}
  C -->|One| D[Laptop]
  C -->|Two| E[iPhone]
  C -->|Three| F[fa:fa-car Car]

Online Checkout Flow

flowchart TD
  Start([Visit online store]) --> Browse[Browse products]
  Browse --> Cart[Add items to cart]
  Cart --> Decide{Ready to check out?}
  Decide -->|Keep shopping| Browse
  Decide -->|Yes| Pay[Enter payment details]
  Pay --> Valid{Payment accepted?}
  Valid -->|No| Retry[Show error message]
  Retry --> Pay
  Valid -->|Yes| Confirm[Order confirmed]
  Confirm --> Done([Email receipt])

  style Start fill:#e8f5e9,stroke:#43a047
  style Done fill:#e8f5e9,stroke:#43a047
  style Valid fill:#fff3e0,stroke:#fb8c00

CI/CD Pipeline with Subgraphs

flowchart LR
  subgraph dev[Development]
    Code[Write code] --> PR[Open pull request]
  end

  subgraph ci[Continuous Integration]
    Build[Build] --> Test[Run tests]
    Test --> Gate{Tests pass?}
  end

  subgraph cd[Deployment]
    Stage[Deploy to staging] --> Approve[Manual approval]
    Approve --> Prod[Deploy to production]
  end

  PR --> Build
  Gate -->|Yes| Stage
  Gate -->|No| Code

Expanded Node Shapes

flowchart TD
  Form@{ shape: manual-input, label: "User fills in form" }
  Docs@{ shape: docs, label: "Uploaded documents" }
  Check@{ shape: procs, label: "Automated checks" }
  Decision@{ shape: diam, label: "Application approved?" }
  DB@{ shape: cyl, label: "Customer database" }
  Letter@{ shape: stadium, label: "Send welcome email" }

  Form --> Docs
  Docs --> Check
  Check --> Decision
  Decision -->|Yes| DB
  Decision -->|No| Form
  DB --> Letter

Class 2 examples

Basic Class Inheritance

classDiagram
  Animal <|-- Duck
  Animal <|-- Fish
  Animal <|-- Zebra
  Animal : +int age
  Animal : +String gender
  Animal: +isMammal()
  Animal: +mate()
  class Duck{
    +String beakColor
    +swim()
    +quack()
  }
  class Fish{
    -int sizeInFeet
    -canEat()
  }
  class Zebra{
    +bool is_wild
    +run()
  }

E-commerce Domain Model

classDiagram
  direction LR
  class Customer {
    +String name
    +String email
    +register()
    +placeOrder() Order
  }
  class Order {
    +Date createdAt
    +List~OrderItem~ items
    +addItem(Product product, int quantity)
    +total() float
  }
  class OrderItem {
    +int quantity
    +float unitPrice
  }
  class Product {
    +String name
    +float price
  }
  class PaymentMethod {
    <<interface>>
    +authorize(float amount) bool
  }
  class CreditCard {
    +String maskedNumber
    +authorize(float amount) bool
  }
  class GiftCard {
    +float balance
    +authorize(float amount) bool
  }

  Customer "1" --> "0..*" Order : places
  Order "1" *-- "1..*" OrderItem : contains
  OrderItem "0..*" --> "1" Product : refers to
  PaymentMethod <|.. CreditCard
  PaymentMethod <|.. GiftCard
  Order --> PaymentMethod : paid via

Sequence 3 examples

Basic Sequence

sequenceDiagram
  Alice->>+John: Hello John, how are you?
  Alice->>+John: John, can you hear me?
  John-->>-Alice: Hi Alice, I can hear you!
  John-->>-Alice: I feel great!

Online Payment Flow

sequenceDiagram
  autonumber
  actor Customer
  participant Shop as Web Shop
  participant Pay as Payment Service
  participant Bank

  Customer->>Shop: Place order
  activate Shop
  Shop->>Pay: Create payment request
  activate Pay
  Pay->>Bank: Authorize card
  Bank-->>Pay: Authorization result
  alt Payment approved
    Pay-->>Shop: Payment confirmed
    Shop-->>Customer: Show receipt
  else Payment declined
    Pay-->>Shop: Payment failed
    Shop-->>Customer: Ask for another card
  end
  deactivate Pay
  deactivate Shop

Food Delivery with Parallel Actions

sequenceDiagram
  participant App as Mobile App
  participant API as Order Service
  participant Kitchen
  actor Courier

  App->>API: Submit order
  Note right of API: Validate items, charge payment
  par Notify kitchen
    API->>Kitchen: New order ticket
  and Confirm to customer
    API-->>App: Order accepted, ETA 30 min
  end
  Kitchen-->>API: Order ready
  API->>Courier: Request pickup
  loop Until delivered
    Courier->>App: Share live location
  end
  Courier-->>App: Order delivered

Entity Relationship 2 examples

Basic ER Schema

erDiagram
  CUSTOMER ||--o{ ORDER : places
  ORDER ||--|{ ORDER_ITEM : contains
  PRODUCT ||--o{ ORDER_ITEM : includes
  CUSTOMER {
    string id
    string name
    string email
  }
  ORDER {
    string id
    date orderDate
    string status
  }
  PRODUCT {
    string id
    string name
    float price
  }
  ORDER_ITEM {
    int quantity
    float price
  }

Streaming Service with Keys

erDiagram
  USER ||--o{ SUBSCRIPTION : has
  PLAN ||--o{ SUBSCRIPTION : "subscribed via"
  USER ||--o{ WATCH_HISTORY : logs
  EPISODE ||--o{ WATCH_HISTORY : "appears in"
  SHOW ||--|{ EPISODE : contains
  USER {
    string id PK
    string email UK "Used for login"
    string country
  }
  SUBSCRIPTION {
    string id PK
    string userId FK
    string planId FK
    date startedAt
    bool autoRenew
  }
  PLAN {
    string id PK
    string name "Basic, Standard or Premium"
    float monthlyPrice
  }
  SHOW {
    string id PK
    string title
    string genre
  }
  EPISODE {
    string id PK
    string showId FK
    int seasonNumber
    int episodeNumber
  }
  WATCH_HISTORY {
    string userId FK
    string episodeId FK
    date watchedAt
    int secondsWatched
  }

State 3 examples

Basic State Diagram

stateDiagram-v2
  [*] --> Still
  Still --> [*]
  Still --> Moving
  Moving --> Still
  Moving --> Crash
  Crash --> [*]

Order Lifecycle with Composite States

stateDiagram-v2
  direction LR
  [*] --> Placed
  Placed --> Paid : payment received
  Placed --> Cancelled : customer cancels
  Paid --> Fulfilment

  state Fulfilment {
    [*] --> Packing
    Packing --> Shipped : handed to courier
    Shipped --> [*]
  }

  Fulfilment --> Delivered : courier confirms
  Delivered --> [*]
  Cancelled --> [*]

Choice and Concurrency

stateDiagram-v2
  state battery_check <<choice>>
  [*] --> PowerOn
  PowerOn --> battery_check
  battery_check --> LowPowerMode : battery < 20%
  battery_check --> Active : battery >= 20%

  state Active {
    [*] --> Playing
    Playing --> Paused : pause
    Paused --> Playing : play
    --
    [*] --> ScreenOn
    ScreenOn --> ScreenDimmed : idle 30s
    ScreenDimmed --> ScreenOn : touch
  }

  LowPowerMode --> [*] : power off
  Active --> [*] : power off

Mindmap 2 examples

Basic Mindmap

mindmap
  root((mindmap))
    Origins
      Long history
      ::icon(fa fa-book)
      Popularisation
        British popular psychology author Tony Buzan
    Research
      On effectiveness and features
      On Automatic creation
    Uses
      Creative techniques
      Strategic planning
      Argument mapping
    Tools
      Pen and paper
      Mermaid

Trip Planning with Shapes and Icons

mindmap
  root((Summer Trip))
    Destination
      Beach town
      Mountain village
    Budget
      ::icon(fa fa-wallet)
      Flights
      Hotel
      Food and activities
    Packing
      Documents
        Passport
        Travel insurance
      reminder{{Sunscreen!}}
    Activities
      ::icon(fa fa-person-hiking)
      Hiking
      Snorkeling
      Local food tour

More diagram types

Block 2 examples

Three-Tier Web Architecture

block-beta
  columns 3
  user(("User")):3
  space:3
  ui["Web UI"] api["API Server"] db[("Database")]

  user --> ui
  ui --> api
  api --> db

  style user fill:#ffe0b2,stroke:#fb8c00
  style db fill:#bbdefb,stroke:#1e88e5

Block Arrows and Nested Blocks

block-beta
  columns 1
  db(("DB"))
  blockArrowId6<["&nbsp;&nbsp;&nbsp;"]>(down)
  block:ID
    A
    B["A wide one in the middle"]
    C
  end
  space
  D
  ID --> D
  C --> D
  style B fill:#969,stroke:#333,stroke-width:4px

C4 2 examples

Internet Banking System Context

C4Context
  title System Context diagram for Internet Banking System
  Enterprise_Boundary(b0, "BankBoundary0") {
    Person(customerA, "Banking Customer A", "A customer of the bank, with personal bank accounts.")
    Person(customerB, "Banking Customer B")
    Person_Ext(customerC, "Banking Customer C", "desc")

    Person(customerD, "Banking Customer D", "A customer of the bank, with personal bank accounts.")

    System(SystemAA, "Internet Banking System", "Allows customers to view information about their bank accounts, and make payments.")

    Enterprise_Boundary(b1, "BankBoundary") {
      SystemDb_Ext(SystemE, "Mainframe Banking System", "Stores all of the core banking information about customers, accounts, transactions, etc.")

      System_Boundary(b2, "BankBoundary2") {
        System(SystemA, "Banking System A")
        System(SystemB, "Banking System B", "A system of the bank, with personal bank accounts. next line.")
      }

      System_Ext(SystemC, "E-mail system", "The internal Microsoft Exchange e-mail system.")
      SystemDb(SystemD, "Banking System D Database", "A system of the bank, with personal bank accounts.")

      Boundary(b3, "BankBoundary3", "boundary") {
        SystemQueue(SystemF, "Banking System F Queue", "A system of the bank.")
        SystemQueue_Ext(SystemG, "Banking System G Queue", "A system of the bank, with personal bank accounts.")
      }
    }
  }

  BiRel(customerA, SystemAA, "Uses")
  BiRel(SystemAA, SystemE, "Uses")
  Rel(SystemAA, SystemC, "Sends e-mails", "SMTP")
  Rel(SystemC, customerA, "Sends e-mails to")

Internet Banking Container Diagram

C4Container
  title Container diagram for Internet Banking System

  Person(customer, "Banking Customer", "A customer of the bank, with personal bank accounts")
  System_Ext(email_system, "E-Mail System", "The internal Microsoft Exchange system")

  Container_Boundary(c1, "Internet Banking") {
    Container(web_app, "Web Application", "JavaScript, React", "Delivers the static content and the SPA")
    Container(spa, "Single-Page App", "JavaScript, React", "Provides all banking functionality via the browser")
    Container(mobile_app, "Mobile App", "C#, Xamarin", "Provides a subset of banking functionality")
    ContainerDb(database, "Database", "SQL Database", "Stores user registration, hashed auth credentials, access logs")
    Container(backend_api, "API Application", "Java, Docker", "Provides banking functionality via JSON/HTTPS API")
  }

  Rel(customer, web_app, "Uses", "HTTPS")
  Rel(customer, spa, "Uses", "HTTPS")
  Rel(customer, mobile_app, "Uses")
  Rel(web_app, spa, "Delivers")
  Rel(spa, backend_api, "Makes API calls to", "JSON/HTTPS")
  Rel(mobile_app, backend_api, "Makes API calls to", "JSON/HTTPS")
  Rel(backend_api, database, "Reads from and writes to", "JDBC")
  Rel(email_system, customer, "Sends e-mails to")
  Rel(backend_api, email_system, "Sends e-mails using", "SMTP")

Gantt 2 examples

Product Launch Plan

gantt
  title Product Launch Plan
  dateFormat YYYY-MM-DD
  section Planning
  Market research :done, research, 2024-03-01, 10d
  Define requirements :done, reqs, after research, 7d
  section Build
  Design prototype :active, proto, after reqs, 14d
  User testing :testing, after proto, 7d
  section Launch
  Marketing campaign :marketing, after proto, 14d
  Release day :milestone, after testing, 0d

Website Redesign with Dependencies

gantt
  title Website Redesign Project
  dateFormat YYYY-MM-DD
  excludes weekends

  section Discovery
  Stakeholder interviews :done, interviews, 2024-01-08, 5d
  Competitive analysis :done, analysis, 2024-01-10, 4d

  section Design
  Wireframes :active, wireframes, after interviews, 7d
  Visual design :design, after wireframes, 10d
  Design sign-off :milestone, after design, 0d

  section Development
  Frontend build :crit, frontend, after design, 15d
  CMS integration :cms, after wireframes, 12d
  Content migration :content, after cms, 5d

  section Launch
  QA testing :qa, after frontend content, 5d
  Go live :milestone, after qa, 0d

Git Graph 3 examples

Basic Git Flow

gitGraph
  commit id: "a3f82c1"
  branch develop
  checkout develop
  commit id: "b7e41d9"
  commit id: "c9d52e4"
  checkout main
  merge develop id: "d4e8f3a"
  commit id: "e1b6c90"
  branch feature
  checkout feature
  commit id: "f2a8d17"
  commit id: "a8c3f54"
  checkout main
  merge feature id: "b9d7e21"

Release and Hotfix Workflow

gitGraph
  commit id: "initial setup"
  branch develop
  commit id: "feat: login page"
  commit id: "feat: search"
  checkout main
  merge develop tag: "v1.0.0"
  checkout develop
  commit id: "feat: user profile"
  checkout main
  branch hotfix
  commit id: "fix: crash on load"
  checkout main
  merge hotfix tag: "v1.0.1"
  checkout develop
  cherry-pick id: "fix: crash on load"
  commit id: "feat: dark mode"
  checkout main
  merge develop tag: "v1.1.0"

Highlighted Commits

gitGraph TB:
  commit id: "v2 groundwork"
  commit id: "schema migration" type: HIGHLIGHT
  commit id: "revert experiment" type: REVERSE
  commit id: "stabilize" tag: "v2.0.0-rc1"

User Journey 2 examples

My Working Day

journey
  title My working day
  section Go to work
    Make tea: 5: Me
    Go upstairs: 3: Me
    Do work: 1: Me, Cat
  section Go home
    Go downstairs: 5: Me
    Sit down: 5: Me

Online Grocery Shopping

journey
  title Ordering groceries online
  section Browse and select
    Search for items: 6: Customer
    Compare prices: 4: Customer
    Add to basket: 7: Customer
  section Checkout
    Choose delivery slot: 5: Customer
    Pay for order: 3: Customer
  section Fulfilment
    Pick items in store: 4: Store staff
    Deliver groceries: 5: Driver
    Unpack at home: 7: Customer

Pie 2 examples

Basic Pie Chart

pie title Pets adopted by volunteers
  "Dogs" : 386
  "Cats" : 85
  "Rats" : 15

Workday Breakdown with Values

pie showData title Where the workday goes (minutes)
  "Focused work" : 210
  "Meetings" : 120
  "Email and chat" : 90
  "Breaks" : 45
  "Context switching" : 15

Quadrant 2 examples

Product Positioning

quadrantChart
  title Reach and engagement of campaigns
  x-axis Low Reach --> High Reach
  y-axis Low Engagement --> High Engagement
  quadrant-1 We should expand
  quadrant-2 Need to promote
  quadrant-3 Re-evaluate
  quadrant-4 May be improved
  Campaign A: [0.3, 0.6]
  Campaign B: [0.45, 0.23]
  Campaign C: [0.57, 0.69]
  Campaign D: [0.78, 0.34]
  Campaign E: [0.40, 0.34]
  Campaign F: [0.35, 0.78]

Eisenhower Matrix with Styled Points

quadrantChart
  title Task Prioritization
  x-axis Not Urgent --> Urgent
  y-axis Not Important --> Important
  quadrant-1 Do first
  quadrant-2 Schedule
  quadrant-3 Eliminate
  quadrant-4 Delegate
  Fix production outage: [0.88, 0.92]
  Plan next quarter: [0.28, 0.85]
  Renew passport: [0.65, 0.75]
  Answer routine emails: [0.78, 0.28]
  Tidy desktop folders: [0.18, 0.12]
  Book dentist appointment: [0.72, 0.62]

Requirement 1 examples

E-Bike Braking System

requirementDiagram

  requirement rider_safety {
    id: 1
    text: Riders must be able to stop safely in all conditions.
    risk: high
    verifymethod: test
  }

  functionalRequirement brake_response {
    id: 1.1
    text: Brakes engage within 100 ms of lever pull.
    risk: medium
    verifymethod: test
  }

  performanceRequirement stopping_distance {
    id: 1.2
    text: Stop from 25 km/h within 4 m on dry pavement.
    risk: medium
    verifymethod: demonstration
  }

  designConstraint water_resistance {
    id: 1.3
    text: Brake electronics must be IP67 rated.
    risk: low
    verifymethod: inspection
  }

  element brake_controller {
    type: hardware
    docRef: "specs/brake-controller"
  }

  element road_test_suite {
    type: "test suite"
    docRef: "qa/road-tests"
  }

  rider_safety - contains -> brake_response
  rider_safety - contains -> stopping_distance
  brake_response - derives -> water_resistance
  brake_controller - satisfies -> brake_response
  road_test_suite - verifies -> stopping_distance

Sankey 2 examples

Monthly Budget Flow

sankey-beta

Salary,Budget,3000
Freelance work,Budget,1200
Budget,Rent,1300
Budget,Groceries,600
Budget,Transport,250
Budget,Fun,350
Budget,Savings,1700

Job Application Funnel

sankey-beta

Applications,Screening,120
Screening,Rejected early,70
Screening,Phone interview,50
Phone interview,Rejected,20
Phone interview,Technical interview,30
Technical interview,Rejected late,12
Technical interview,Offer,18
Offer,Declined,4
Offer,Hired,14

Timeline 2 examples

Project Timeline

timeline
  title History of Social Media Platform
  2002 : LinkedIn
  2004 : Facebook
       : Google
  2005 : YouTube
  2006 : Twitter

Product Roadmap with Sections

timeline
  title Product Roadmap 2024
  section Q1 Foundations
    January : Team hired : Tech stack chosen
    February : MVP scoped
    March : Alpha release
  section Q2 Growth
    April : Beta program opens
    May : Mobile app : Public API
    June : v1.0 launch

XY Chart 3 examples

Sales Revenue

xychart-beta
  title "Sales Revenue"
  x-axis [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
  y-axis "Revenue (in $)" 4000 --> 11000
  bar [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]
  line [5000, 6000, 7500, 8200, 9500, 10500, 11000, 10200, 9200, 8500, 7000, 6000]

Coffee Sales with Data Labels

---
config:
  xyChart:
    showDataLabel: true
---
xychart-beta
  title "Cups sold per day"
  x-axis [Espresso, Latte, "Cold Brew", Mocha, Tea]
  y-axis "Cups" 0 --> 120
  bar [95, 110, 68, 45, 30]

Sign-ups vs Churn

xychart-beta
  title "Sign-ups vs churned users"
  x-axis [Q1, Q2, Q3, Q4]
  y-axis "Users" 0 --> 500
  line [120, 260, 380, 470]
  line [40, 60, 90, 110]

Common pitfalls

Wrong diagram header
Start with flowchart TD / sequenceDiagram / classDiagram etc. Mixing a sequence snippet into a flowchart will fail to parse.
AI paste fences
Chat replies often wrap code in ```mermaid fences or smart quotes. Use Clean Mermaid or Editor Auto-fix before rendering.
Duplicate node IDs
Reusing the same ID with different shapes or inserting snippets at the top of the file can break the graph. Prefer unique IDs (snippets use $n placeholders).
Arrows and spaces
"a/b"

FAQ

Where do these samples come from?

Defaults match the Mermaid Live Editor sample set, including secondary examples under each diagram type.

Is this the full Mermaid grammar?

No — these are starter diagrams. See the official Mermaid docs for complete syntax.

Open in Editor