Diagrams as Code

Master this essential documentation concept

Quick Definition

A documentation approach where visual diagrams are written and stored as plain text syntax rather than binary image files, making them version-controllable and easy to update.

How Diagrams as Code Works

graph TD A[Developer writes Plaintext Syntax] --> B{Diagram Tool} B --> C[Mermaid.js] B --> D[PlantUML] B --> E[Graphviz DOT] C --> F[Rendered SVG/PNG] D --> F E --> F A --> G[Git Repository] G --> H[Pull Request Review] H --> I[Diff Shows Text Changes] I --> J[Merged & Auto-Published Docs] F --> J

Understanding Diagrams as Code

A documentation approach where visual diagrams are written and stored as plain text syntax rather than binary image files, making them version-controllable and easy to update.

Key Features

  • Centralized information management
  • Improved documentation workflows
  • Better team collaboration
  • Enhanced user experience

Benefits for Documentation Teams

  • Reduces repetitive documentation tasks
  • Improves content consistency
  • Enables better content reuse
  • Streamlines review processes

Turning Diagram-as-Code Walkthroughs Into Searchable References

Many teams introduce diagrams as code through recorded onboarding sessions, architecture reviews, or live coding walkthroughs — a developer shares their screen, explains the syntax, and demonstrates how a few lines of plain text become a sequence or flowchart. It feels efficient in the moment, but that knowledge stays locked inside the recording.

The problem surfaces when a teammate needs to remember the exact syntax for a specific diagram type, or when someone new joins and wants to understand why your team adopted this approach in the first place. Scrubbing through a 45-minute architecture call to find a two-minute explanation of Mermaid block syntax is a real productivity drain — especially when the answer should be a quick reference lookup.

Converting those recordings into structured documentation changes how your team actually uses that knowledge. Diagrams as code explanations become searchable by keyword, syntax examples can be pulled out as standalone snippets, and the reasoning behind your tooling choices is preserved in context rather than buried in a timestamp. When someone asks "how do we write entity-relationship diagrams in our stack?", the answer is findable in seconds rather than tracked down through meeting notes or Slack history.

If your team regularly explains technical workflows like this on video, see how converting those recordings into living documentation works →

Real-World Documentation Use Cases

Keeping Microservice Architecture Diagrams in Sync with Code Changes

Problem

Engineering teams at companies like Spotify or Netflix add or remove microservices frequently, but architecture diagrams live in Confluence as PNG exports from Lucidchart. When a service is deprecated, no one updates the diagram, leading to onboarding engineers following outdated service maps.

Solution

Store a Mermaid or PlantUML diagram file alongside the service's codebase in the same Git repository. When a developer removes or adds a service dependency, they update the diagram text file in the same pull request as the code change, making diagram drift structurally impossible to merge unreviewed.

Implementation

['Create a file named architecture.mmd in the root of the repository using Mermaid graph TD syntax representing current service dependencies.', 'Add a GitHub Actions workflow that renders the .mmd file to SVG on every push to main and commits the output to a /docs/assets folder.', 'Enforce a PR checklist item requiring diagram updates when service dependencies change, using a CODEOWNERS file to require a tech lead review of any .mmd changes.', 'Embed the rendered SVG in the README.md using a relative image link so it auto-updates whenever the diagram source changes.']

Expected Outcome

Architecture diagrams are guaranteed to reflect the merged codebase state, and reviewers can see exact line-level changes to topology in the PR diff without opening any external tool.

Documenting API Authentication Flows Across Multiple SDK Versions

Problem

SDK teams at companies like Stripe or Twilio maintain separate authentication flows for v1, v2, and v3 of their API. Each version has a slightly different OAuth sequence, but the diagrams are stored as binary Visio files on a shared drive with filenames like auth-flow-FINAL-v2-revised.vsdx, making it impossible to track what changed between versions.

Solution

Use PlantUML sequenceDiagram files stored in a versioned docs folder within the SDK monorepo. Each API version has its own .puml file, and Git history provides a complete audit trail of every change to the authentication sequence, including who changed it and why via commit messages.

Implementation

['Create a /docs/diagrams/auth/ directory with files named oauth-flow-v1.puml, oauth-flow-v2.puml, and oauth-flow-v3.puml using PlantUML sequence diagram syntax.', "When updating an auth flow for a new SDK release, copy the previous version's .puml file as the starting point and modify only the changed steps, preserving Git blame history.", 'Configure a MkDocs or Docusaurus site to render PlantUML files server-side during the documentation build pipeline using the plantuml-markdown plugin.', 'Tag each diagram commit with the corresponding SDK release version so developers can run git log --follow to trace the full evolution of any auth flow.']

Expected Outcome

Support engineers can instantly show customers the exact sequence diagram for their SDK version, and security auditors can review the full history of authentication flow changes with timestamps and author attribution.

Onboarding New Engineers with Always-Current Database Schema Diagrams

Problem

Data engineering teams run hundreds of database migrations over months, but the ERD diagrams shared during onboarding were last updated six months ago. New engineers spend their first week discovering that foreign key relationships shown in the diagram no longer exist, or that critical junction tables are entirely missing from the visual.

Solution

Use a tool like SchemaSpy or tbls to auto-generate ERD diagrams in Graphviz DOT or Mermaid ERD syntax directly from the live database schema as part of the CI/CD pipeline, eliminating manual diagram maintenance entirely.

Implementation

['Integrate tbls into the CI pipeline to introspect the staging database and output a schema.mmd file in Mermaid ERD syntax after every successful migration run.', 'Commit the auto-generated schema.mmd file back to the repository using a bot commit, so the diagram file always reflects the post-migration schema state.', 'Embed the rendered ERD in the engineering onboarding wiki by referencing the raw GitHub URL of the rendered SVG output, which updates automatically with each pipeline run.', 'Add a CI check that fails the pipeline if the committed schema.mmd file does not match the freshly generated output, preventing schema drift from going undetected.']

Expected Outcome

New engineers have a database schema diagram that is guaranteed to be accurate as of the last merged migration, reducing onboarding ramp-up time and eliminating a common source of incorrect assumptions about data relationships.

Reviewing Infrastructure Changes in Terraform Pull Requests with Visual Diffs

Problem

Platform teams reviewing Terraform PRs that add new VPCs, subnets, or security groups have no visual context for how the proposed infrastructure fits into the existing network topology. Reviewers must mentally construct the network layout from raw HCL code, leading to missed security group misconfigurations or unintended public subnet exposures.

Solution

Use nwdiag or Graphviz DOT files to represent the network topology as code, stored in the same repository as Terraform configurations. When a PR modifies infrastructure, the diagram file is updated in the same commit, giving reviewers a text diff that maps directly to visual topology changes.

Implementation

['Create a network-topology.nwdiag file in the /docs directory that mirrors the current Terraform-defined VPC structure, subnets, and key EC2 or ECS resources using nwdiag syntax.', 'Add a PR template instruction requiring authors to update network-topology.nwdiag whenever they add or modify VPCs, subnets, security groups, or load balancers in Terraform files.', 'Configure a GitHub Actions step to render the nwdiag file to PNG and post it as a comment on the PR using the GitHub API, giving reviewers an instant visual preview without leaving the PR interface.', 'Store previous rendered images as PR artifacts so reviewers can toggle between the before and after network diagrams to visually confirm the intended topology change.']

Expected Outcome

Infrastructure reviewers catch topology mistakes such as accidentally routing internal services through public subnets at PR review time rather than post-deployment, and the repository maintains a complete visual history of how the network architecture evolved over time.

Best Practices

Co-locate Diagram Source Files with the Code They Describe

Placing a .mmd, .puml, or .dot file in the same directory as the code it visualizes creates a natural coupling that reminds developers to update the diagram when the code changes. This proximity principle is the same reason inline code comments stay more accurate than separate documentation wikis. When the diagram lives next to the service, microservice, or module, ownership is implicit and drift is visible during code review.

✓ Do: Store auth-flow.puml in the same directory as your authentication module and reference it from the module's README.md using a relative path.
✗ Don't: Do not store all diagrams in a single centralized /docs/diagrams folder disconnected from the code they represent, as this breaks the feedback loop that keeps diagrams accurate.

Render Diagrams Automatically in CI Rather Than Committing Binary Outputs

Committing rendered PNG or SVG files alongside source diagram files creates merge conflicts on binary assets and doubles the maintenance burden. Instead, configure your CI pipeline to render diagrams at build time using tools like mermaid-cli, PlantUML server, or Kroki, publishing the outputs to your documentation hosting platform. This ensures the rendered image always reflects the current source text without requiring manual re-export steps.

✓ Do: Use a GitHub Actions step with mmdc -i architecture.mmd -o docs/assets/architecture.svg to render diagrams during the documentation build pipeline.
✗ Don't: Do not manually export diagrams to PNG in Mermaid Live Editor and commit the binary file to Git, as this creates stale images that silently diverge from the source .mmd file.

Choose Diagram Syntax That Matches Your Team's Existing Toolchain

Selecting a diagram-as-code tool that integrates with your existing documentation platform reduces adoption friction significantly. Mermaid is natively supported in GitHub Markdown, GitLab, Notion, and Docusaurus without any plugins. PlantUML is preferred in enterprise Java environments where Confluence plugins are already licensed. Forcing a team to install a separate server or learn an unfamiliar syntax when a native option exists creates resistance that leads to teams reverting to screenshot-based diagrams.

✓ Do: Use Mermaid syntax for diagrams in GitHub-hosted repositories since GitHub renders Mermaid natively in Markdown files without any build step or plugin configuration.
✗ Don't: Do not standardize on a diagram tool that requires a self-hosted rendering server if your team uses GitHub Pages or Netlify, as the additional infrastructure creates a maintenance burden that outweighs the benefits.

Write Diagram Updates as Part of the Same Commit as the Code Change

The most powerful guarantee that diagrams stay accurate is making diagram updates an atomic part of the same Git commit as the code change they reflect. When a developer adds a new Kafka topic to a data pipeline, the architecture diagram update should appear in the same commit, not as a follow-up ticket. Code reviewers should be explicitly asked to verify that the diagram change accurately reflects the code change, treating diagram drift as a review failure.

✓ Do: Include diagram file changes in the same PR as the feature or infrastructure change, and add a PR template checklist item that reads: Diagram files updated to reflect this change.
✗ Don't: Do not create separate documentation tickets like JIRA-4521: Update architecture diagram after merging a code change, as these tickets are consistently deprioritized and result in permanently outdated diagrams.

Use Meaningful Node Labels and Consistent Naming Conventions Across All Diagrams

Diagram-as-code files are read by both humans and rendering engines, so node identifiers and labels must be descriptive enough to be understood in raw text form without rendering. Using identifiers like A, B, C or node1, node2 makes the source file unreadable during code review and impossible to search across a repository. Establishing a naming convention such as using service names in snake_case for node IDs and human-readable labels in quotes ensures diagrams are self-documenting even in their unrendered text form.

✓ Do: Write Mermaid nodes as payment_service[Payment Service] and auth_gateway[Auth Gateway] so the diagram source is readable as plain text in a Git diff during code review.
✗ Don't: Do not use single-letter node identifiers like A --> B --> C in diagram source files, as these are meaningless in a text diff and force reviewers to render the diagram before they can understand what changed.

How Docsie Helps with Diagrams as Code

Build Better Documentation with Docsie

Join thousands of teams creating outstanding documentation

Start Free Trial