Introduction: Why Text-Based Diagrams Matter for Technical Documentation
Technical documentation has evolved significantly over the past decade. Gone are the days when creating system architecture diagrams meant dragging shapes around in a visual editor, only to discover later that the diagram was outdated the moment the system changed. Modern technical documentation demands a new approach--one where diagrams become as version-controllable as the code they describe.
Declarative diagramming represents this paradigm shift. Instead of manipulating graphical elements directly, you describe what you want using a domain-specific language (DSL), and the renderer produces the corresponding visual output. This approach brings numerous advantages for technical teams: diagrams live alongside source code in repositories, changes are tracked via version control, and collaboration becomes as simple as merging text files.
D2 (Declarative Diagramming) stands at the forefront of this movement. Developed by Terrastruct, D2 is an open-source language that transforms text descriptions into professional-quality diagrams. Unlike older tools that were designed primarily for specific diagram types, D2 takes a generalist approach--supporting everything from simple flowcharts to complex system architectures through a consistent, intuitive syntax.
For SEO professionals and technical content creators, D2 offers something particularly valuable: the ability to generate diagrams programmatically as part of content pipelines. When you need to illustrate technical concepts with precision and maintain consistency across dozens of pages, declarative diagramming becomes not just convenient but essential. Learn more about improving technical SEO with structured data to complement your diagram-heavy content strategy.
The practical value extends beyond aesthetics. Search engines increasingly favor content that demonstrates expertise through detailed, well-structured information architecture. Diagrams created with D2 can include semantic metadata, structured labels, and accessibility annotations that improve both user experience and search visibility.
Everything you need to leverage D2 for technical documentation and SEO content
D2 Fundamentals
Core syntax, elements, shapes, and connections that form the foundation of declarative diagramming
Installation Options
Set up D2 via Go, Homebrew, Chocolatey, or Docker depending on your development environment
Layout Engines
Choose between Dagre, ELK, and Tala layout engines for optimal diagram readability
Documentation Integration
Integrate D2 into documentation workflows with version control and CI/CD automation
Understanding Declarative Diagramming
The Problem with Visual Diagramming Tools
Traditional diagramming tools, while powerful, introduce friction into documentation workflows. Consider what happens when a developer needs to update a system architecture diagram: they must open the diagramming application, locate the correct file, make their changes, export the updated image, and commit everything to version control. If multiple contributors are working on the same documentation, merge conflicts in binary image files become a real possibility.
Beyond the workflow challenges, visual editors encourage a particular anti-pattern in technical documentation: diagram drift. A beautiful architecture diagram captures a system's structure at a moment in time. As the system evolves, the diagram becomes increasingly inaccurate--but updating it requires effort that teams often deprioritize. Within months, documentation contains diagrams that misrepresent reality, undermining the credibility of the entire documentation set.
How D2 Works
D2 follows a simple but powerful model: you write a text file using D2's declarative syntax, pass it to the D2 compiler, and receive an SVG or PNG output. The language allows you to define shapes, establish connections between them, apply styling, and organize elements hierarchically. Underlying layout engines automatically position elements to create clean, readable diagrams.
As documented in the official D2 documentation, the declarative nature means you describe the desired outcome rather than specifying exact coordinates. For example, to create a diagram showing a user connecting to a web server that queries a database, you might write a simple connection chain that D2's layout engine then automatically positions optimally.
Key Concepts in D2
Shapes represent the nodes in your diagram. D2 includes a rich library of predefined shapes including rectangles, circles, diamonds, cylinders for databases, hexagons for processes, and many specialized forms. Each shape type carries semantic meaning that helps readers understand the nature of the represented component.
Connections define relationships between shapes. Arrows indicate directionality--showing data flow, dependency, or simply association. D2 supports labeled connections, styled connections (varying line thickness, color, or pattern), and even animated connections for dynamic visualizations.
Containers allow hierarchical organization. A container can hold multiple shapes and connections, creating nested structures that mirror complex system architectures. Containers can themselves contain other containers, enabling arbitrary depth of organization.
Styles control visual appearance. You can specify colors, fonts, stroke widths, fill patterns, and other presentation attributes at the shape, connection, or global level. Styles can be inherited, allowing consistent theming across large diagrams.
D2 Syntax Reference
Elements and Shapes
Every D2 diagram consists of elements connected by relationships. Elements represent the nodes in your diagram--components, processes, data stores, or any other entities you need to illustrate.
The simplest element declaration is just a name:
server
This creates an unlabeled element named "server" using the default shape (a rounded rectangle). For more control, you can specify a label and shape explicitly:
server: Web Server {
shape: rectangle
}
Here, "server" is the internal identifier used for references, while "Web Server" appears as the visible label. This separation between identifier and label enables clean referencing even when labels contain special characters or spaces.
D2 provides shapes including rectangle, circle, diamond, cylinder, hexagon, parallelogram, person, step, and cloud. Each shape carries semantic meaning that helps readers understand the represented component.
Connections and Relationships
Connections define how elements relate using arrow notation:
client -> server
This creates a directed connection from client to server with an arrowhead indicating directionality. D2 interprets the arrow direction literally--data flows from client to server in this example.
Labels provide context for connections:
client -> server: "HTTPS requests"
The text after the colon appears as a label on the connection, clarifying the nature of the relationship. Connection labels support full text formatting and can include Unicode characters.
Hierarchical Structures
D2's container syntax allows nesting elements:
system: "E-Commerce System" {
frontend: "Web Frontend" {
user_interface
api_client
}
backend: "Backend Services" {
product_service
order_service
}
}
Styling and Theming
Styles can be applied at multiple levels:
database: Database {
shape: cylinder
style.fill: "#e8f4f8"
style.stroke: "#2c7fb8"
}
For more complex styling scenarios, D2 supports themes that provide professionally-designed color schemes. Explore how to integrate these with your technical documentation workflow for consistent visual communication across your content.
1# User Authentication Flow2 3users: Users {4 shape: person5}6 7login_form: "Login Form" {8 shape: rectangle9}10 11auth_service: "Auth Service" {12 shape: hexagon13}14 15database: Database {16 shape: cylinder17}18 19users -> login_form20login_form -> auth_service21auth_service -> databaseGetting Started with D2
Installation Options
D2 can be installed through multiple channels depending on your development environment. As documented in Code4IT's installation guide, each approach offers distinct advantages for different workflows.
Go installation:
go install oss.terrastruct.com/d2@latest
This command downloads and installs the D2 compiler, making the d2 command available in your PATH. The Go-based installation ensures you always have access to the latest stable release.
macOS with Homebrew:
brew install d2lang/tap/d2
This approach integrates D2 with the broader Homebrew ecosystem, making updates straightforward through standard brew upgrade commands.
Windows with Chocolatey:
choco install d2
The Chocolatey installation handles PATH configuration automatically, ensuring the compiler is accessible from any command prompt.
Docker:
docker run --rm -v $(pwd):/data -w /data terrastruct/d2 my-diagram.d2
Docker provides an alternative for environments where local installation is restricted. This approach is particularly useful in CI/CD pipelines or team environments where consistent tooling is essential.
Your First D2 Diagram
Create a file named authentication.d2 and compile it:
d2 authentication.d2 authentication.svg
The output SVG can be viewed in any web browser. The layout engine automatically positions elements for optimal readability. This simple workflow demonstrates the power of declarative diagramming--your focus remains on describing relationships, not positioning elements.
The D2 Playground
Before diving into complex diagrams, the D2 Playground offers an excellent sandbox for experimentation with instant visual feedback. This web-based editor is ideal for learning syntax and prototyping concepts without any local setup.
Layout Engines
Understanding Layout Options
D2 supports multiple layout engines, each with different algorithms for positioning elements. The choice of layout engine significantly affects how your diagram looks, particularly for complex architectures with many interconnected elements.
As outlined in the LogRocket D2 guide, three layout engines are available:
Dagre is a hierarchical layout engine ideal for flowcharts, process diagrams, and directed graphs. It emphasizes top-to-bottom or left-to-right flow, making it perfect for illustrating sequences and dependencies. Dagre is the default engine for most diagrams.
ELK (Eclipse Layout Kernel) provides more sophisticated algorithms for complex nested structures with many interconnected elements. For diagrams with deeply nested containers or many elements, ELK often produces more readable results.
Tala is Terrastruct's proprietary layout engine, designed specifically for software architecture diagrams. It understands common architectural patterns and produces layouts optimized for technical documentation.
vars: {
d2-config: {
layout-engine: dagre
}
}
Choosing the Right Engine
For straightforward flow diagrams--user journeys, process flows, or simple state machines--Dagre's hierarchical approach produces intuitive results. For complex system architectures with multiple layers, Tala excels with its understanding of software patterns. When in doubt, experiment with different engines to find the most readable output.
For SEO optimization of technical content, choosing the right layout improves diagram readability and time-on-page metrics, both of which contribute to search performance.
Integrating D2 into Documentation Workflows
Version Control and Collaboration
D2 diagrams integrate naturally with Git-based version control. Since diagrams are text files, standard Git workflows apply: create branches for diagram updates, submit changes through pull requests, and review modifications through the same process used for code.
Large diagrams benefit from modular construction. Rather than defining everything in a single file, decompose complex architectures into components stored in separate files:
# main.d2
import "./frontend.d2"
import "./backend.d2"
import "./database.d2"
users -> frontend
frontend -> backend
backend -> database
Automated Diagram Generation
For documentation systems, D2 diagrams can be created as part of the build process. This automation ensures documentation diagrams always reflect current system state:
# CI step
grep -r "\.d2$" diagrams/ | while read f; do
d2 "$f" "${f%.d2}.svg"
done
IDE Integration
VS Code's D2 extension provides syntax highlighting, live preview, snippets, and format-on-save. The live preview updates instantly as you modify syntax, building intuition for how different constructs affect visual output. This tight feedback loop accelerates diagram development and makes experimenting with different layouts effortless.
For teams adopting documentation-as-code practices, integrating D2 into your workflow creates diagrams that are reviewable, mergeable, and automatically regeneratable as part of builds. This approach pairs well with modern SEO strategies that emphasize structured, machine-readable content.
Advanced D2 Techniques
SQL Table Diagrams
D2 includes specialized support for database schema visualization. The SQL table shape renders database tables with columns, data types, and key indicators:
users: users {
shape: sql_table
id: int {constraint: primary_key}
email: varchar(255) {constraint: unique}
password_hash: varchar(255)
}
orders: orders {
shape: sql_table
id: int {constraint: primary_key}
user_id: int {constraint: foreign_key}
total_amount: decimal(10,2)
}
orders.user_id -> users.id
This capability makes D2 particularly valuable for technical documentation of database-driven applications. Documentation that includes accurate, up-to-date schema diagrams provides significantly more value to developers and analysts than text descriptions alone.
Accessibility in Diagrams
Technical documentation should be accessible to all readers, including those using screen readers or with visual impairments. The desc property adds descriptive text that screen readers can access:
server: Web Server {
shape: rectangle
desc: "The web server handles incoming HTTP requests and routes them to appropriate backend services"
}
High-contrast themes ensure diagrams remain readable for users with color vision deficiencies. D2's theme library includes accessibility-focused options designed to maintain sufficient contrast.
Performance Optimization
Large SVG diagrams can impact page load times. Optimize using SVGO:
svgo diagram.svg -o diagram-optimized.svg
For diagrams that don't require interactivity, consider lazy loading or appropriate image formats to maintain fast page speeds--crucial for both user experience and SEO performance.
D2 vs Other Diagramming Tools
Mermaid
Mermaid offers text-to-diagram capabilities with strong static site generator integration. D2 distinguishes itself through more sophisticated layout engines, superior shape variety, and better support for complex architectures. Mermaid remains a strong choice for simple flowcharts, particularly when integration with existing documentation tools is paramount. D2 becomes the preferred choice when diagram quality or visual impact are priorities.
PlantUML
PlantUML has been the standard for text-based diagramming in enterprise environments for years. D2's advantages include a simpler, more intuitive syntax, SVG output (PlantUML primarily generates PNG), modern styling capabilities, and better support for non-UML diagram types.
Visual Editors
Visual tools like Draw.io remain popular for ad-hoc diagram creation. However, D2's text-based approach creates diagrams that are reviewable, mergeable, automatically regeneratable, and documented alongside the systems they describe. For teams committed to documentation-as-code practices, D2's approach provides significant advantages despite the initial learning investment.
When to Choose D2
Choose D2 when diagram quality and visual impact are priorities, when diagrams are version-controlled alongside code, when complex multi-level architectures need clear visualization, or when integration with documentation-as-code practices is essential. This makes D2 an excellent complement to comprehensive SEO strategies that value technical precision.
Best Practices for D2 Diagrams
Diagram Design Principles
- Start with the audience - Consider who will read your diagram and what they need to understand
- Limit diagram scope - A single diagram should communicate one key concept
- Use consistent shapes and colors - Establish conventions and apply them consistently
- Include context through labels - Every connection should have a meaningful label
Code Organization
- Use meaningful identifiers:
web_serveris clearer thanws - Add comments for documentation:
# This diagram shows... - Modularize through imports for large diagrams
Testing and Validation
- Ensure diagrams compile without errors as part of your build process
- Consider visual regression testing to catch unintended changes
- Review accessibility with appropriate tools
Performance Considerations
- Optimize SVG output for web delivery using tools like SVGO
- Use appropriate resolution for different display contexts
- Consider lazy loading for diagram-heavy pages
These practices align with broader technical SEO best practices that emphasize performance, accessibility, and structured content. When building documentation sites with D2, partner with professional web development services to ensure optimal performance and search visibility.
Frequently Asked Questions
Is D2 free to use?
Yes, D2 is open-source and free to use under the MIT license. The core compiler and language are available at no cost, with Terrastruct providing optional commercial support for enterprise users.
What file formats does D2 output?
D2 outputs SVG by default, which scales infinitely and is ideal for web documentation. PNG export is also supported for contexts that require raster images.
Can I use D2 in CI/CD pipelines?
Absolutely. D2 compiles quickly and can be integrated into any CI/CD system. Docker and command-line interfaces make automation straightforward.
Does D2 support animation?
Yes, D2 supports animated connections that show data flow direction. These animations work in SVG output and can enhance documentation interactivity.
How does D2 compare to Mermaid for documentation?
D2 offers more sophisticated layout engines, a broader shape library, and professional themes. Mermaid has broader tool integration. Choose D2 when diagram quality is paramount.
Related Resources
Explore more technical SEO resources to enhance your content strategy:
- Improving React SEO with Structured Data - Learn how structured data enhances search visibility
- Guide to React 19's New Document Metadata Feature - Implement metadata for better SEO
- How Next.js Can Help Improve SEO - Leverage Next.js for search optimization
- How to Detect Low Hanging Fruit - Identify quick wins for SEO improvement
Sources
- D2 Documentation - Official DSL documentation and language reference
- D2 GitHub Repository - Open-source compiler and project resources
- LogRocket: A complete guide to declarative diagramming with D2 - Comprehensive tutorial with practical examples
- Code4IT: D2: like Mermaid, but better - Installation, IDE integration, and comparison guide