Volker Schwaberow
Volker Schwaberow
Advanced Mermaid: Beyond Basics
Table of Contents

Advanced Mermaid: Beyond Basics

Mermaid has become a popular tool for creating diagrams within code and documentation thanks to its versatility and efficiency across various projects. I’ve found it incredibly helpful for generating org charts and visual schemes that clarify complex explanations. The first time I used Mermaid, I rushed to create a Gantt chart for a project deadline. At first, I was completely overwhelmed—figuring out the syntax while the clock ticking wasn’t ideal. But after experimenting, I realized just how powerful and flexible Mermaid could be. What started as a stressful experience was a learning opportunity that showed me how capable this tool is. Beyond its straightforward use cases—like flowcharts or Gantt diagrams—Mermaid offers advanced features that can boost productivity and collaboration. In this article, we’ll dive into these advanced functionalities, which are surprisingly easy to use, and see how you can get the most out of Mermaid.

Going Beyond Flowcharts: Mermaid’s Complex Diagram Capabilities

Mermaid often gets introduced as a simple, no-fuss tool for creating flowcharts—perfect for those days when you just want to avoid a headache. But once you peek behind that friendly facade, you’ll find a powerhouse capable of generating advanced diagrams that do more than just depict a few boxes and arrows. We’re talking complex software architectures, intricate data flows, and multi-component systems that make you look like you truly understand what’s going on. For instance, you can use Mermaid to create sequence diagrams that capture the flow of operations in distributed systems or microservices architecture. Or, you can leverage its class diagrams to visually depict relationships, inheritance hierarchies, and data structures in object-oriented software design. Some of the advanced diagrams that Mermaid can tackle include sequence diagrams, class diagrams, state diagrams, and even entity-relationship diagrams. So yes, it’s a lot more than just simple business charts.

Sequence Diagrams: Enhancing Asynchronous Collaboration

Sequence diagrams are invaluable for capturing the flow of operations in distributed systems or microservices architecture. Mermaid allows for the creation of advanced sequence diagrams, the definition of participants and messages with detailed parameters, and the creation of message notes and activation bars. This makes it easy to model asynchronous communications, WebSocket interactions, or other request-response patterns.

Here’s an example of a Mermaid sequence diagram that shows the interaction between a client, an API, and a database:

sequenceDiagram
    participant Client
    participant API
    participant DB
 
    Client->>API: Request Data
    API->>DB: Query Data
    activate DB
    DB-->>API: Data Response
    deactivate DB
    API-->>Client: JSON Data
sequenceDiagram
    participant Client
    participant API
    participant DB

    Client->>API: Request Data
    API->>DB: Query Data
    activate DB
    DB-->>API: Data Response
    deactivate DB
    API-->>Client: JSON Data

Using activation bars (activate/deactivate), Mermaid lets you visually highlight when a specific system component is actively processing. This is particularly useful when explaining complex interactions, as it clearly shows the temporal relationships between processes. This feature makes it possible to identify which component is busy at each stage of an operation, helping you assess how workloads are distributed and where there may be potential bottlenecks. Additionally, this visual representation aids in optimizing system performance, ensuring that each part of the process is accounted for and running smoothly. You can also combine activation bars with detailed notes to highlight key processes, giving a more complete picture of system behavior in distributed or parallel environments.

Advanced Class Diagrams for Architecture Planning

For developers working on object-oriented software design, Mermaid’s class diagrams are a powerful tool for visually depicting relationships, inheritance hierarchies, and data structures. Mermaid goes beyond basic diagramming by allowing developers to model complex relationships, such as multiple inheritance, interfaces, associations, and dependencies. With Mermaid, you can represent abstract classes, implement interface dependencies, and distinguish between strong and weak relationships. This level of detail is particularly beneficial for understanding large-scale systems, identifying points of refactoring, or planning out how new features might integrate with existing classes. It also provides a way to document intricate systems in a way that’s less error-prone compared to manual diagramming, which can easily become outdated or misleading as the code evolves. Additionally, Mermaid’s ability to generate and update these diagrams programmatically means less manual work, enabling diagrams that stay in sync with your underlying architecture.

classDiagram
    class User {
        +String name
        +String email
        +login()
        +logout()
    }
    class Admin {
        +manageUsers()
    }
    class Guest
 
    User <|-- Admin : extends
    User <|.. Guest : inheritance
    Admin ..> User : dependency
classDiagram
    class User {
        +String name
        +String email
        +login()
        +logout()
    }
    class Admin {
        +manageUsers()
    }
    class Guest

    User <|-- Admin : extends
    User <|.. Guest : inheritance
    Admin ..> User : dependency

In this class diagram, the relationship indicators (<|--, ..>) make it possible to describe inheritance and dependencies clearly, which assists in analyzing object-oriented code and understanding potential code refactoring opportunities.

Advanced Features: Configurations and Custom Styling

One often underused yet extremely powerful aspect of Mermaid is its configurability. Mermaid provides a rich set of configuration options and custom styling parameters, allowing you to tailor diagrams to various scenarios. Whether it’s about matching your company’s visual branding, differentiating complex elements with distinct styles, or optimizing diagrams for particular audiences, Mermaid’s flexibility can be a game-changer. Users can programmatically modify themes, customize colors, set fonts, or control diagram layouts.

Custom Themes and Configurations

Mermaid’s default appearance can be modified extensively to fit your aesthetic or comply with organizational style guides. Using Mermaid’s configuration objects, custom themes can be created, colors and fonts can be changed, and global rendering options that affect all diagrams can be set. This helps maintain a consistent look for diagrams across various documents.

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#ff6347', 'edgeLabelBackground':'#f9f9f9'}}}%%
flowchart TD
    A[Custom Themed Box] --> B{Decision}
    B -->|Yes| C[Positive Outcome]
    B -->|No| D[Negative Outcome]
%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#ff6347', 'edgeLabelBackground':'#f9f9f9'}}}%%
flowchart TD
    A[Custom Themed Box] --> B{Decision}
    B -->|Yes| C[Positive Outcome]
    B -->|No| D[Negative Outcome]

With %%{init}%%, the configuration options are injected into the diagram, allowing customization beyond the standard predefined themes. The colors, labels, and layout can be set to match the branding of the documentation without tedious manual editing.

Embedding HTML Elements for Enhanced Functionality

Mermaid allows embedding HTML elements directly within diagrams, enhancing interactivity and creating a more dynamic user experience. Adding links, images, and formatted text can transform a basic diagram into a fully interactive user-guidance system. This is particularly valuable for onboarding flows, complex user journeys, or knowledge-based diagrams where access to additional resources is crucial. For example, adding buttons that link to documentation or interactive tutorials turns diagrams into functional tools rather than just illustrative aids, providing context precisely when needed.

flowchart LR
    A[Start] --> B{Is it Advanced?}
    B -->|Yes| C[Advanced Concepts]
    C --> D[[Click here for more info]]
    D -->|Link| E[External Resource]
flowchart LR
    A[Start] --> B{Is it Advanced?}
    B -->|Yes| C[Advanced Concepts]
    C --> D[[Click here for more info]]
    D -->|Link| E[External Resource]

These embedded elements help create deeply integrated diagrams, including links to external content or interactive tutorials. This functionality makes Mermaid a powerful tool for generating context-aware diagrams. For example, during technical onboarding, embedded links can guide new users to detailed explanations or even interactive sandboxes for direct experimentation. This bridges the gap between theory and practice, creating a more engaging, user-driven experience. Additionally, embedding multimedia elements allows for dynamic presentations that respond to user interactions, giving learners the tools to explore complex concepts thoroughly.

Auto-Generation and Integration with CI/CD Pipelines

Mermaid becomes even more powerful when combined with automation tools. For example, integrating Mermaid with a CI/CD pipeline enables the automatic generation of diagrams as part of the documentation. When you integrate Mermaid diagrams directly into markdown (.md) files within repositories like GitHub, changes to source code or system configurations can automatically trigger updates to the diagrams. This keeps diagrams up to date and reduces human error in documenting systems.

For such automation, tools like Mermaid CLI come in handy. The CLI can convert .mmd files to images as an automated build process. For example:

mmdc -i diagram.mmd -o diagram.png -b transparent

This helps generate up-to-date documentation diagrams in PNG files that can be embedded into generated HTML or PDFs, ensuring that your documentation is always in sync with your code.

Getting Mermaid and Installation

To start using Mermaid, you can integrate it directly into many platforms, such as GitHub, GitLab, or any Markdown-compatible documentation platform. If you want to install Mermaid locally or use it in your own projects, you can use the following methods:

  1. Using Node.js: You can install Mermaid CLI via npm for command-line usage to generate diagrams as images.

    npm install -g @mermaid-js/mermaid-cli

    This command installs the Mermaid CLI globally, allowing you to convert .mmd files to image formats like PNG or SVG.

  2. Using a CDN: If you just want to embed Mermaid diagrams in an HTML page, you can include Mermaid via a CDN link:

    <script type="module">
        import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
        mermaid.initialize({ startOnLoad: true });
    </script>

    This approach lets you quickly use Mermaid in your web projects without additional installations.

  3. Editors and Plugins: Many code editors and documentation tools support Mermaid via plugins. For example:

    • VS Code: Extensions allow you to preview Mermaid diagrams directly within the editor.
    • Obsidian and Typora: Both support Mermaid syntax out of the box, making it easy to create and view diagrams.

Advanced Use Cases for Mermaid

Network Diagrams

Mermaid can visualize detailed network topologies, depict data flow across multiple nodes, and illustrate routing paths. With Mermaid’s advanced graph representation, you can effectively convey the intricate details of network infrastructure, such as node interconnections, data routes, and communication protocols. This allows for a clearer understanding of how data traverses the network, how nodes are linked, and where potential bottlenecks or vulnerabilities might arise. Such visual clarity is essential for designing new network systems and troubleshooting existing ones, as it provides a comprehensive map that facilitates discussions among network engineers and stakeholders.

Here is an example of using Mermaid to illustrate the TLS 1.3 handshake workflow, which is a critical part of secure communication between a client and a server:

sequenceDiagram
    participant Client
    participant Server
 
    Client->>Server: ClientHello
    Note right of Client: Contains supported ciphers and key shares
    Server-->>Client: ServerHello
    Note left of Server: Chooses cipher and sends key share
    Server->>Client: EncryptedExtensions
    Server->>Client: Certificate (optional)
    Server->>Client: CertificateVerify (optional)
    Server->>Client: Finished
    Note left of Server: Server is ready for secure communication
    Client-->>Server: Finished
    Note right of Client: Client confirms and starts secure data exchange
sequenceDiagram
    participant Client
    participant Server

    Client->>Server: ClientHello
    Note right of Client: Contains supported ciphers and key shares
    Server-->>Client: ServerHello
    Note left of Server: Chooses cipher and sends key share
    Server->>Client: EncryptedExtensions
    Server->>Client: Certificate (optional)
    Server->>Client: CertificateVerify (optional)
    Server->>Client: Finished
    Note left of Server: Server is ready for secure communication
    Client-->>Server: Finished
    Note right of Client: Client confirms and starts secure data exchange

This sequence diagram provides a detailed overview of the TLS 1.3 handshake, showcasing each step in the communication process between the client and server. Such visualizations can enhance understanding of security protocols, helping teams identify potential vulnerabilities or inefficiencies in the handshake process.

State Machines

State diagrams are crucial for visualizing states and transitions within complex systems, clearly representing the various conditions and their possible transitions. Mermaid’s state diagrams are well-suited for modeling reactive user interfaces, signaling protocols, embedded systems, or game state management. They provide detailed insights into the system’s behavior by explicitly defining each state, its transitions, and the associated triggers. This clarity not only aids in understanding the normal operation of a system but also helps identify edge cases, concurrency issues, and failure points that may not be evident through code alone. Furthermore, Mermaid’s capabilities make it possible to maintain these diagrams in a programmatically updated format, ensuring they remain accurate as systems evolve. This is vital for debugging and system validation processes.

Here’s an example of a state diagram using Mermaid, which models the states in a simple traffic light system:

stateDiagram-v2
    [*] --> Red
    Red --> Green: Timer expires
    Green --> Yellow: Timer expires
    Yellow --> Red: Timer expires
stateDiagram-v2
    [*] --> Red
    Red --> Green: Timer expires
    Green --> Yellow: Timer expires
    Yellow --> Red: Timer expires

This state diagram illustrates the transition between different traffic light states. Each state (Red, Green, Yellow) transitions to the next based on a timer event. Such a diagram can be expanded to include more states or conditions, making it a powerful tool for visualizing and validating state-dependent logic in both hardware and software systems.

Here is a more complex example showing a vending machine state diagram:

stateDiagram-v2
    [*] --> Idle
    Idle --> CoinInserted: Coin Inserted
    CoinInserted --> SelectProduct: Product Selected
    SelectProduct --> Dispense: Dispense Product
    Dispense --> Idle: Product Collected
    CoinInserted --> Refund: Cancel Request
    Refund --> Idle: Coin Returned
stateDiagram-v2
    [*] --> Idle
    Idle --> CoinInserted: Coin Inserted
    CoinInserted --> SelectProduct: Product Selected
    SelectProduct --> Dispense: Dispense Product
    Dispense --> Idle: Product Collected
    CoinInserted --> Refund: Cancel Request
    Refund --> Idle: Coin Returned

This vending machine diagram represents the different states and the interactions required for each transition, such as inserting a coin, selecting a product, dispensing the product, and handling refund requests. This level of modeling helps identify all possible user interactions and ensures the machine behaves correctly under each condition.

Another example is a state diagram representing a user authentication flow:

stateDiagram-v2
    [*] --> LoggedOut
    LoggedOut --> LoggingIn: Enter Credentials
    LoggingIn --> LoggedIn: Authentication Success
    LoggingIn --> LoginFailed: Authentication Failed
    LoginFailed --> LoggedOut: Retry Login
    LoggedIn --> LoggedOut: User Logs Out
stateDiagram-v2
    [*] --> LoggedOut
    LoggedOut --> LoggingIn: Enter Credentials
    LoggingIn --> LoggedIn: Authentication Success
    LoggingIn --> LoginFailed: Authentication Failed
    LoginFailed --> LoggedOut: Retry Login
    LoggedIn --> LoggedOut: User Logs Out

This diagram models the user authentication process, including states for logging out, attempting to log in, succeeding, or failing. It also represents retry and logout actions. A detailed view of the authentication process is useful for designing secure systems and properly handling all transitions.

Dynamic Dependencies

Mermaid’s graph representation capabilities allow you to map out complete dependency graphs for services in a microservices architecture. This is crucial for understanding how services interact, identifying bottlenecks, and spotting single points of failure. For example, a graph depicting the interactions between a payment service, user management, and inventory service can immediately reveal which components are critical for transaction processing. By visualizing these dependencies dynamically, Mermaid makes it easier to grasp complex system interactions, ensuring that relationships between services are well understood and potential issues are proactively addressed. Another example would be depicting the dependencies between different backend services in an e-commerce platform, allowing you to quickly assess the impact of a failure in any particular microservice. Furthermore, this visualization helps plan improvements, optimize communication paths, and ensure robustness across the service ecosystem.

Here’s an example of using Mermaid to depict a dependency graph for microservices in an e-commerce platform:

graph TD
    UserService --> PaymentService
    UserService --> InventoryService
    PaymentService --> NotificationService
    InventoryService --> WarehouseService
    PaymentService --> FraudDetectionService
graph TD
    UserService --> PaymentService
    UserService --> InventoryService
    PaymentService --> NotificationService
    InventoryService --> WarehouseService
    PaymentService --> FraudDetectionService

This diagram represents each service as a node, and the arrows show their dependencies. For instance, the UserService depends on both the PaymentService and InventoryService, while the PaymentService is linked to the NotificationService and FraudDetectionService. Visualizing this helps us understand which services are interconnected and highlights potential points of failure or opportunities for optimization.

Here’s another example showing a simple content delivery system:

graph TD
    Client --> CDN
    CDN --> WebServer
    WebServer --> Database
    WebServer --> Cache
    Database --> BackupService
graph TD
    Client --> CDN
    CDN --> WebServer
    WebServer --> Database
    WebServer --> Cache
    Database --> BackupService

In this diagram, the content delivery system is visualized. The client requests content from the CDN, which is then handled by the web server. The web server interacts with a database and a caching layer while the database is connected to a backup service. This kind of visualization helps to understand the interactions and potential data flow clearly, ensuring that each component’s dependencies are well-defined and can be easily managed for fault tolerance.

Wrapping It Up

Mermaid provides extensive capabilities for visualizing complex systems and processes. With this functionality Mermaid enhances documentation with visual representations, from clear class diagrams that define relationships and inheritance to automated sequence diagrams for complex workflows in distributed systems. By utilizing advanced features like custom configurations, HTML integration, and automation, Mermaid helps streamline the creation and maintenance of high-quality diagrams.

Whether your focus is on system architecture design, detailed software documentation, or creating onboarding guides, Mermaid’s advanced functionality ensures that your diagrams remain clear, informative, and easy to update. The integration possibilities allow you to build truly dynamic diagrams that grow with your systems, helping to bridge the gap between static documentation and adaptive, real-time visual insights.

Here’s a fun way to conclude your journey with Mermaid:

graph TD
    A[You, the Brave User] -->|Learns about Mermaid| B[Advanced Diagramming Skills]
    B -->|Implements Diagrams| C[Awesome Documentation]
    C -->|Shares Knowledge| D[Happy Team]
    D -->|Continues Exploring| E[Master of Mermaid]
    E -->|Takes a Break| F((Coffee Time))
    F -->|Refreshed| A

This diagram is your journey with Mermaid. You start as a brave user, learn advanced diagramming skills, create awesome documentation, share knowledge with your team, become a master of Mermaid, and then take a well-deserved coffee break before starting the cycle anew. Have fun!