
Diagram as Code with Mermaid
Learn Diagram as Code with Mermaid—benefits, examples, challenges, and how MermaidKit improves the workflow.
Introduction: The Pain of Traditional Diagramming Tools
As a developer, have you ever found yourself in these frustrating situations?
-
📊 Mouse Dragging Fatigue: Spending hours in Visio or Draw.io, meticulously adjusting component positions, aligning connectors, all just to make your diagram look "professional"
-
💾 File Format Nightmares: Your colleague's OmniGraffle file from their Mac won't open on your Windows machine, forcing awkward screenshot-based workarounds
-
🤝 Collaboration Hell: Multiple people editing the same architecture diagram leads to either file conflicts or overwritten changes, eventually resorting to "final_v2_really_final.xml"
-
🔄 Version Control Impossibility: Want to see last month's system design? Good luck searching through a pile of cryptically named files with no meaningful diff history
Even worse, when business requirements change and your architecture evolves, you need to reopen that heavyweight .vsdx file and go through the mouse-dragging ordeal all over again. With diagrams living separately from code, documentation quickly becomes stale. Team members stare at three-month-old architecture diagrams wondering: "Is this still how the system works?"
It's time for a change.
What is Diagram as Code?
Diagram as Code is a modern approach to creating visual documentation: describe diagrams with code instead of drawing them with a mouse. Just as we use Infrastructure as Code to define our infrastructure, we can use code to express system architectures, business processes, and data relationships.
A simple example illustrates the difference. With traditional tools, you would:
-
Create three rectangular boxes
-
Label them "User", "Server", and "Database"
-
Drag arrows to connect them
-
Manually adjust positions for visual alignment
With Diagram as Code, you simply write:
graph LR User --> Server Server --> DatabaseThe code automatically renders into a beautiful flowchart, with layout optimized by algorithms. You focus on content, not pixel-perfect positioning.
The core principle: diagrams are no longer static images, but version-controllable, collaborative, and programmable code.
Five Key Advantages of Diagram as Code
1. Version Control Friendly 📝
Diagram code lives in your Git repository with clear, readable diffs:
graph LR
User --> Server
Server --> Database
+ Server --> Cache
+ Cache --> DatabaseNo more v1, v2, v3_final_really_final file naming chaos. Git history becomes your version record.
2. Seamless Team Collaboration 🤝
Team members only need a text editor to modify diagrams. Merge conflicts? Resolve them with Git's three-way merge tools. No more worrying about "who locked the file" or "whose changes got overwritten".
3. Programmable and Automatable 🤖
Diagram code can be generated programmatically and integrated into CI/CD pipelines:
# Auto-generate ER diagram from database schema
./generate-erd.sh | tee docs/database.mmd
# Validate diagram syntax in CI
mermaid-cli --validate docs/**/*.mmdImagine sequence diagrams in your API documentation auto-generated from OpenAPI specs, always staying in sync with your implementation.
4. Documentation as Code 📚
Diagram code embeds directly in Markdown documents alongside text content:
## System Architecture
We adopt a microservices architecture:
```mermaid
graph TB
Gateway --> ServiceA
Gateway --> ServiceB
```
Each service's responsibilities are...This approach tightly couples documentation with diagrams, eliminating the need to manage separate image files and broken links.
5. Fast Iteration ⚡
Modifying diagrams is just editing a few lines of code, not re-dragging and re-aligning. Need to add a new service? One line of code. Need to rename a component? Global find-and-replace.
Comparing Popular Diagram as Code Tools
Several Diagram as Code tools are available, each with unique strengths:
| Tool | Strengths | Weaknesses | Best For |
|---|---|---|---|
| Mermaid | Concise syntax, rich ecosystem, multiple diagram types | Limited style customization | Most technical docs, READMEs, Wikis |
| PlantUML | Powerful features, comprehensive UML support | Complex syntax, requires Java runtime | Detailed software design documentation |
| Graphviz | Powerful foundation, excellent layout algorithms | Steep learning curve, unintuitive syntax | Academic papers, complex graph visualizations |
| D2 | Modern design, clean syntax | Newer ecosystem, fewer tool integrations | Teams seeking modern experiences |
For most technical teams, Mermaid is the optimal choice.
Why Mermaid Stands Out
Zero-Config Rendering, Works Everywhere 🎁
Mermaid's biggest advantage is ecosystem support:
-
GitHub/GitLab: Native support, Mermaid code in Markdown auto-renders
-
Notion/Obsidian: Direct Mermaid syntax support
-
VSCode: Rich plugin ecosystem with live preview
-
Documentation Tools: VuePress, Docusaurus, MkDocs all have built-in support
This means your diagrams display seamlessly almost everywhere, with no extra build steps required.
Intuitive Syntax, Easy to Learn 📖
Mermaid's syntax reads like natural language, approachable even for non-technical team members:
sequenceDiagram Alice->>Bob: Hello Bob! Bob-->>Alice: Hello Alice!Compare with PlantUML's equivalent:
@startuml
Alice -> Bob: Hello Bob!
Bob --> Alice: Hello Alice!
@endumlMermaid is more concise, without extra start/end markers.
Rich Diagram Types 🎨
Mermaid supports 10+ diagram types, covering most use cases:
-
Flowchart
-
Sequence Diagram
-
Class Diagram
-
State Diagram
-
Entity Relationship Diagram
-
Gantt Chart
-
User Journey
-
Git Graph
-
Pie Chart
-
Mind Map
Active Community, Continuous Evolution 🚀
Mermaid has 70k+ GitHub stars with an active community and continuous feature updates. Stuck on something? Stack Overflow and GitHub Issues have abundant discussions and solutions.
Real-World Examples: Mermaid's Power in Action
Let's explore Mermaid's capabilities through practical examples.
Example 1: Business Flowchart 💼
Code:
flowchart TD Start([User Visit]) --> Login{Logged In?} Login -->|No| ShowLoginPage[Show Login Page] Login -->|Yes| CheckPermission{Check Permission} ShowLoginPage --> InputCredentials[Enter Credentials] InputCredentials --> Validate{Valid?} Validate -->|No| ShowLoginPage Validate -->|Yes| CheckPermission CheckPermission -->|No Permission| ShowError[Show Error] CheckPermission -->|Has Permission| ShowDashboard[Show Dashboard] ShowError --> End([End]) ShowDashboard --> End style Start fill:#e1f5ff style End fill:#ffe1e1 style ShowDashboard fill:#e1ffe1Rendered Output: This flowchart clearly visualizes the complete user access flow, including login validation and permission checks. Different colors (blue for start, red for end, green for success) make the logic immediately comprehensible.
Example 2: API Sequence Diagram 🔄
Code:
sequenceDiagram participant Client participant Gateway as API Gateway participant Auth as Auth Service participant Service as Business Service participant DB as Database Client->>Gateway: POST /api/orders activate Gateway Gateway->>Auth: Verify Token activate Auth Auth-->>Gateway: Token Valid deactivate Auth Gateway->>Service: Create Order activate Service Service->>DB: Insert Order Record activate DB DB-->>Service: Order ID deactivate DB Service->>Service: Send Notification Service-->>Gateway: Order Created deactivate Service Gateway-->>Client: 200 OK + Order Details deactivate GatewayRendered Output: The sequence diagram shows temporal interactions between multiple services. activate/deactivate keywords visualize call stack depth, while arrow styles (->> solid, -->> dashed) distinguish requests from responses, helping readers understand asynchronous flows.
Example 3: System Architecture 🏗️
Code:
graph TB subgraph "Frontend Layer" Web[Web App] Mobile[Mobile App] end subgraph "Gateway Layer" Gateway[API Gateway<br>Load Balancer] end subgraph "Service Layer" AuthService[Auth Service] OrderService[Order Service] PaymentService[Payment Service] NotifyService[Notification Service] end subgraph "Data Layer" MySQL[(MySQL<br>Primary DB)] Redis[(Redis<br>Cache)] MongoDB[(MongoDB<br>Logs)] end Web --> Gateway Mobile --> Gateway Gateway --> AuthService Gateway --> OrderService Gateway --> PaymentService OrderService --> MySQL OrderService --> Redis PaymentService --> MySQL AuthService --> Redis OrderService -.Message Queue.-> NotifyService NotifyService --> MongoDB style Gateway fill:#fff4e6 style MySQL fill:#e6f3ff style Redis fill:#ffe6e6Rendered Output: Using subgraph to layer the system, different line styles (solid for synchronous calls, dashed for async messages) clearly express architectural hierarchy. Color coding makes each layer's responsibilities immediately apparent.
Challenges of Diagram as Code
Despite its many advantages, Diagram as Code faces some challenges:
1. Learning Curve for Non-Technical Users 📚
For team members unfamiliar with code (product managers, UI designers), learning the syntax requires time investment. While Mermaid's syntax is simple, keywords and structures still need memorization.
2. Code Readability for Complex Diagrams 🤔
When diagrams grow complex (e.g., 50+ node architecture diagrams), code becomes lengthy and the overall structure may not be immediately apparent. This demands good code organization and commenting.
3. Real-Time Preview Needs 👀
When writing diagram code, developers want to see rendered output immediately, not go through "edit code → save → refresh browser" loops. While VSCode plugins exist, the experience isn't always smooth.
4. Style Customization Complexity 🎨
Mermaid's default styling is beautiful, but deep customization (matching company brand guidelines) through code configuration is relatively complex compared to visual tool controls.
MermaidKit: Making Diagram as Code Simpler
To address these challenges, we built MermaidKit.
MermaidKit is an online platform specifically designed for Mermaid, making Diagram as Code more fluid:
🚀 Real-Time Preview, WYSIWYG
Say goodbye to "edit-save-refresh" cycles. In MermaidKit, every code change renders immediately. Write code on the left, see results on the right—as intuitive as using visual tools.
💡 Smart Completion, Lower Learning Curve
Can't remember Mermaid syntax? No problem. MermaidKit provides intelligent code completion and syntax hints. Type seq to auto-expand a complete sequence diagram template. Built-in snippet library lets you insert common diagrams with one click.
🎨 Style Customization, Easy Adjustments
Through a visual theme editor, easily adjust colors, fonts, and line styles without writing complex CSS. Save customized themes as templates and share them across your team.
🤝 Team Collaboration, Knowledge Sharing
Publish your diagrams as public links—team members can view without registration. Comments and version history make diagram evolution traceable. Create diagram collections to organize related architecture and flow diagrams.
📤 Multi-Format Export, Flexible Usage
Beyond copying Mermaid code, MermaidKit exports to PNG, SVG, and PDF for use in various contexts. Generated images are automatically optimized for size and resolution, ensuring clarity and beauty.
Visit https://mermaidkit.com to experience it now, and make Diagram as Code truly work for you.
Conclusion: Embrace the Code-Based Future of Diagrams
Diagram as Code isn't just a tool choice—it's a paradigm shift: bringing diagrams into the code world to enjoy version control, collaboration, and automation benefits.
Just as infrastructure evolved from manual configuration to Infrastructure as Code, and documentation evolved from Word to Docs as Code, diagrams are undergoing the same transformation. In this transformation, Mermaid has become the most popular choice through its concise syntax and broad ecosystem support.
If you're still struggling with maintaining massive Visio files, if your team still suffers from diagram collaboration pain, give Diagram as Code a try. Starting today, embed your first Mermaid flowchart in your README.md and experience the magic of text-based diagramming.
When you fall in love with this approach, don't forget to visit MermaidKit to further boost your productivity.
Let's draw a better world with code together. 🚀