Mermaid Subgraphs — Grouping and Nested Diagrams

Use Mermaid subgraphs to group nodes, create nested layouts, and build complex multi-layer diagrams. Learn subgraph syntax, direction overrides, and styling.

Advanced

Detailed Explanation

Subgraphs in Mermaid

Subgraphs let you group related nodes into labeled boxes, creating visual clusters within a flowchart. They are essential for modeling complex architectures like microservice systems, network topologies, and layered applications.

Basic Subgraph Syntax

flowchart TB
    subgraph Frontend
        A[React App] --> B[API Client]
    end
    subgraph Backend
        C[Express Server] --> D[PostgreSQL]
    end
    B --> C

Each subgraph ... end block creates a labeled container. Nodes inside the block are visually grouped, and edges can cross subgraph boundaries.

Subgraph Labels and IDs

You can give a subgraph a display label different from its ID:

flowchart LR
    subgraph fe["Frontend Layer"]
        A[React] --> B[Redux]
    end
    subgraph be["Backend Layer"]
        C[Node.js] --> D[MongoDB]
    end
    fe --> be

Use the ID (fe, be) to reference subgraphs in edges and the label in brackets for display.

Nested Subgraphs

Subgraphs can be nested to any depth:

flowchart TB
    subgraph Cloud["AWS Cloud"]
        subgraph VPC["VPC 10.0.0.0/16"]
            subgraph PublicSubnet["Public Subnet"]
                ALB[Application Load Balancer]
            end
            subgraph PrivateSubnet["Private Subnet"]
                EC2[EC2 Instance]
                RDS[(RDS Database)]
            end
        end
    end
    User[User] --> ALB
    ALB --> EC2
    EC2 --> RDS

Direction Overrides

Each subgraph can have its own direction, independent of the parent:

flowchart LR
    subgraph Pipeline["CI/CD Pipeline"]
        direction LR
        Build --> Test --> Deploy
    end
    subgraph Environments
        direction TB
        Dev --> Staging --> Prod
    end
    Deploy --> Dev

Styling Subgraphs

Apply styles to subgraphs using their ID:

flowchart LR
    subgraph secure["Secure Zone"]
        A[Auth Service] --> B[User DB]
    end
    subgraph public["Public Zone"]
        C[API Gateway] --> D[CDN]
    end
    C --> A
    style secure fill:#dcfce7,stroke:#16a34a
    style public fill:#fef3c7,stroke:#f59e0b

Best Practices

  1. Use subgraphs for logical grouping — network zones, services, deployment environments.
  2. Limit nesting to 2-3 levels — deeper nesting becomes hard to read.
  3. Name subgraphs descriptively — "Payment Services" is better than "Group 1."
  4. Use direction overrides sparingly — mixing directions can confuse the layout engine.

Use Case

A cloud architect diagramming a multi-tier application on AWS. Subgraphs represent VPCs, subnets, and availability zones, making it clear which services live in public vs. private subnets and how traffic flows through the load balancer.

Try It — Mermaid Diagram Editor

Open full tool