D2

Master this essential documentation concept

Quick Definition

A modern text-based diagramming language designed to produce clean, polished architecture and infrastructure diagrams from plain text definitions stored in code repositories.

How D2 Works

graph TD A[.d2 Source File in Git Repo] --> B[D2 CLI Compiler] B --> C{Output Format} C --> D[SVG Diagram] C --> E[PNG Export] C --> F[PDF Document] D --> G[Embedded in Markdown Docs] E --> H[Confluence / Notion Pages] F --> I[Architecture Review Packets] J[TALA Layout Engine] --> B K[Sketch Theme / Custom Styles] --> B style A fill:#4A90D9,color:#fff style B fill:#2C3E50,color:#fff style D fill:#27AE60,color:#fff style E fill:#27AE60,color:#fff style F fill:#27AE60,color:#fff

Understanding D2

A modern text-based diagramming language designed to produce clean, polished architecture and infrastructure diagrams from plain text definitions stored in code repositories.

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

Keeping Your D2 Diagram Knowledge Out of Video Silos

When your team adopts D2 as your diagramming standard, the learning curve often plays out in recorded sessions — architecture walkthroughs, onboarding calls, or live coding demonstrations where someone shares their screen and explains how to structure a D2 file to represent a microservices topology or a CI/CD pipeline.

The problem is that D2 syntax, conventions, and your team's specific diagramming patterns get buried inside those recordings. A new engineer trying to understand why your team uses a particular D2 layout for network diagrams has to scrub through a 45-minute meeting to find a two-minute explanation. There's no way to search for "D2 connection syntax" or "how we label external services" across your video library.

Converting those recordings into structured documentation changes this entirely. Imagine a walkthrough where a senior architect explains your D2 conventions getting transformed into a searchable reference — complete with the actual D2 code snippets discussed, the reasoning behind naming decisions, and step-by-step guidance your whole team can find in seconds. Your D2 standards stop living in someone's recorded screen share and start becoming a living part of your documentation system.

If your team regularly explains technical tooling like D2 through meetings and demos, there's a more efficient way to preserve that knowledge.

Real-World Documentation Use Cases

Keeping Microservices Architecture Diagrams in Sync with Code Changes

Problem

Engineering teams maintain architecture diagrams in Lucidchart or draw.io, but these binary files cannot be meaningfully reviewed in pull requests. When a new service is added or a dependency changes, the diagram is either forgotten or updated manually weeks later, causing documentation drift that misleads new engineers during onboarding.

Solution

D2 stores architecture definitions as plain .d2 text files committed alongside service code. Reviewers can diff diagram changes in GitHub pull requests exactly like code, and CI pipelines automatically re-render SVGs on merge, ensuring the published diagram always reflects the current state of the repository.

Implementation

['Create an `architecture/services.d2` file in the monorepo root defining each microservice as a node and inter-service API calls as directed edges with labels like `REST /orders` or `gRPC stream`.', 'Add a GitHub Actions step that runs `d2 architecture/services.d2 docs/architecture.svg` on every push to main, committing the rendered SVG back to the docs folder.', "Enforce a PR checklist item: 'If a new service or dependency was added, update services.d2.' Reviewers can see the textual diff and catch missing connections before merge.", "Embed the rendered SVG in the team's README.md using a relative image link so it is always current when developers clone the repository."]

Expected Outcome

Architecture diagrams stay accurate within one pull request cycle of any infrastructure change, and new engineers can trace service dependencies by reading a single versioned file rather than hunting through stale wiki pages.

Generating Per-Environment Infrastructure Diagrams from Shared D2 Templates

Problem

Platform teams document AWS infrastructure separately for dev, staging, and production environments. Maintaining three nearly identical Visio files leads to copy-paste errors where production diagrams show outdated VPC CIDR ranges or missing NAT gateways, creating confusion during incident response.

Solution

D2 supports variables and imports, allowing teams to define a base infrastructure topology once and override environment-specific values such as instance types, replica counts, and CIDR blocks using D2's `vars` block. A single `make diagrams` command renders all three environment diagrams from one canonical source.

Implementation

['Write a `base-infra.d2` file defining the logical topology: VPC, public and private subnets, ALB, ECS cluster, RDS primary, and read replica nodes with connection labels.', 'Create `prod.d2`, `staging.d2`, and `dev.d2` files that import `base-infra.d2` and override vars like `db_instance: db.r6g.2xlarge` for prod versus `db.t3.medium` for dev.', 'Add a Makefile target that loops over the three environment files and runs `d2 --theme 200 {env}.d2 docs/infra/{env}.svg` to produce themed, labeled SVGs.', "Link each environment's SVG in the runbook for that environment so on-call engineers see an accurate diagram without navigating to a separate tool."]

Expected Outcome

Three accurate, visually consistent environment diagrams are produced from a single source of truth, eliminating the class of incidents where engineers apply a fix to the wrong tier because they misread an outdated diagram.

Documenting API Gateway Request Flows for Developer Portal Onboarding

Problem

API platform teams struggle to explain multi-step authentication and routing flows to external developers. Prose descriptions of OAuth token exchange, rate limiting middleware, and backend fan-out are long and error-prone, yet sequence diagrams in tools like Miro require design tool access and cannot be updated by backend engineers who only work in code editors.

Solution

D2's sequence diagram syntax lets backend engineers write request flow diagrams as text directly in the API documentation repository. The clean rendered output with D2's built-in sketch or terminal themes is embedded in the developer portal, and any engineer can submit a PR to correct a step without learning a GUI tool.

Implementation

['Create `docs/flows/oauth-token-exchange.d2` using D2 sequence diagram blocks to model the client, API gateway, identity provider, and backend service as actors with labeled arrows for each HTTP call and response.', 'Use D2 `note` blocks to annotate critical steps such as token TTL validation and the 401 retry loop, making the diagram self-documenting without requiring a separate explanation paragraph.', 'Run `d2 --layout elk docs/flows/oauth-token-exchange.d2 portal/static/oauth-flow.svg` in the documentation build pipeline triggered on every docs branch merge.', "Reference the SVG in the OpenAPI specification's `x-readme` extension or embed it in the developer portal's Getting Started page with a link to the source .d2 file in GitHub."]

Expected Outcome

External developer support tickets related to authentication flow misunderstandings drop measurably, and the average time for a new API consumer to successfully complete OAuth integration decreases because the sequence diagram precisely mirrors the actual gateway behavior.

Producing Architecture Decision Record Diagrams That Survive Long-Term Maintenance

Problem

Architecture Decision Records (ADRs) written in Markdown often reference diagrams that are stored as binary image attachments or external Lucidchart links. Over months, the external links rot, the images become orphaned, and the context needed to understand why a technology was chosen is lost, making ADRs unreliable as historical references.

Solution

D2 diagram source is embedded or co-located with each ADR as a plain text .d2 file. Because the diagram definition is human-readable text, it can be read and understood even if the rendering toolchain changes, and it is indexed by code search tools like GitHub's search or Sourcegraph, making ADRs discoverable by component name.

Implementation

["Establish a convention where each ADR directory contains both `decision.md` and `context-diagram.d2`, with the .d2 file showing the architectural options considered and the chosen path highlighted using D2's `style` block with a distinct fill color.", 'Add a `d2` render step to the documentation CI job that processes all `*.d2` files under the `docs/adr/` directory and writes SVGs adjacent to each decision file.', 'Update the ADR template to include a `## Context Diagram` section with a relative Markdown image link to the rendered SVG, so the diagram appears inline when browsing the repository on GitHub.', 'Configure Sourcegraph or GitHub code search to index .d2 files, enabling engineers to search for a service name like `PaymentService` and find every ADR that references it in a diagram.']

Expected Outcome

ADRs remain self-contained and fully renderable years after creation. Engineers performing system audits or planning migrations can find all architectural decisions involving a specific component through a single code search query, reducing research time from hours to minutes.

Best Practices

Store .d2 Source Files Adjacent to the Code They Describe

Placing `architecture.d2` or `data-flow.d2` files in the same directory as the service or module they document creates an implicit ownership contract. When a developer changes a service's API surface, the adjacent diagram file is a natural reminder to update the documentation. This co-location strategy also ensures diagrams are included in code reviews without requiring a separate documentation PR.

✓ Do: Place `docs/architecture.d2` inside the service repository and commit rendered SVGs to the same `docs/` folder so both source and output travel together through version history.
✗ Don't: Do not store all D2 files in a centralized `company-diagrams` repository disconnected from the services they represent, as this breaks the feedback loop between code changes and diagram updates.

Use D2 Labels on Connections to Encode Protocol and Data Contract Details

D2 edges support rich label syntax, allowing you to annotate connections with the protocol, HTTP method, event topic name, or data format rather than leaving relationships unlabeled. Labeled edges turn a topology diagram into a communication contract reference that engineers can consult during debugging or integration work. This information is especially valuable in microservices diagrams where implicit coupling is a common source of production incidents.

✓ Do: Write edges as `OrderService -> InventoryService: gRPC CheckStock(SKU) -> StockResponse` to capture the contract directly on the diagram line.
✗ Don't: Do not draw unlabeled arrows between services and rely on prose documentation to explain what data flows across each connection, as the prose and diagram will inevitably diverge.

Pin the D2 CLI Version in CI to Prevent Rendering Regressions

D2 is actively developed and new releases occasionally change default layout behavior, font rendering, or theme output. If your CI pipeline installs the latest D2 version on every run, a new release can silently change the visual output of your diagrams, causing SVGs embedded in documentation to look different without any corresponding change in the .d2 source file. Pinning the version ensures reproducible renders across all environments.

✓ Do: Specify an exact version in your CI install step, such as `curl -fsSL https://d2lang.com/install.sh | sh -s -- --version v0.6.5`, and update it deliberately as part of a planned dependency upgrade.
✗ Don't: Do not use `--version latest` or omit the version flag in automated pipelines, as this trades reproducibility for convenience and can introduce invisible documentation regressions.

Apply D2 Themes Consistently Across All Diagrams in a Documentation Set

D2 ships with numbered themes (0 through 300+) and supports custom theme overrides via the `--theme` CLI flag or inline `vars` blocks. Using different themes across diagrams in the same documentation site creates a fragmented visual experience that signals low documentation quality to readers. Selecting one theme for light mode and one for dark mode and applying them uniformly through a Makefile or CI variable ensures visual cohesion.

✓ Do: Define `D2_THEME=200` and `D2_DARK_THEME=200` as environment variables in your CI pipeline and reference them in every `d2` render command so all diagrams share a consistent palette.
✗ Don't: Do not mix the default theme on some diagrams with sketch mode or terminal themes on others within the same documentation site, as the inconsistency undermines trust in the documentation as a whole.

Use D2 Containers to Group Related Components and Reduce Visual Noise

D2 supports nested containers using curly brace syntax, allowing you to group nodes that belong to the same AWS VPC, Kubernetes namespace, or bounded domain context. Grouping reduces the number of visual elements readers must parse simultaneously and makes the diagram's logical boundaries explicit without requiring additional prose explanation. Containers also enable D2's layout engine to optimize spacing within and between groups independently.

✓ Do: Define `aws.vpc.private_subnet { OrderService; InventoryService }` to visually enclose services that share a network boundary, making security and routing rules immediately apparent from the diagram shape.
✗ Don't: Do not place all nodes at the top level of a D2 file when logical groupings exist, as a flat list of 15 or more nodes with crossing edges becomes unreadable and fails to communicate architectural boundaries.

How Docsie Helps with D2

Build Better Documentation with Docsie

Join thousands of teams creating outstanding documentation

Start Free Trial