Skip to content

L07 D2 Lang

DodaTech 4 min read

title: "D2 Lang — Modern Diagram-as-Code Language" weight: 7 description: "Learn D2 for modern diagram-as-code: concise syntax, automatic layout, multiple diagram types, styling, and integration with documentation pipelines for fast diagram creation." date: 2026-06-28 lastmod: 2026-06-28 tags: [technical-writing, diagram-as-code] }

D2 is a modern diagram-as-code language that emphasizes concise syntax and automatic layout, making it faster to write and producing cleaner diagrams than many alternatives.

In this lesson, you will learn D2 syntax, creating flowcharts, sequence diagrams, and container diagrams, styling options, automatic layout features, and rendering for documentation.

What You'll Learn

You will learn D2 basics, create multiple diagram types, apply styling, leverage automatic layout, and integrate D2 with your documentation build pipeline for automated diagram generation.

Why It Matters

D2 offers the best developer experience among diagram-as-code tools. Its syntax is intuitive, the automatic layout produces professional results, and it compiles quickly.

Real-World Use

DodaTech's engineering team uses D2 for quick architecture sketches during design discussions. The fast feedback loop and automatic layout make it ideal for rapid iteration.

User -> DodaZIP: Compress file
DodaZIP -> File System: Read input
DodaZIP -> DodaZIP: Apply algorithm
DodaZIP -> File System: Write output
DodaZIP -> User: Return compressed file
def create_d2_diagram(nodes, edges, layout="dagre"):
    """Generate D2 diagram syntax."""
    lines = [f"# D2 diagram with {layout} layout"]
    for node_id, label in nodes:
        lines.append(f'{node_id}: "{label}"')
    for source, target, label in edges:
        if label:
            lines.append(f'{source} -> {target}: "{label}"')
        else:
            lines.append(f'{source} -> {target}')
    return "\n".join(lines)

diagram = create_d2_diagram(
    [("client", "Client"), ("api", "API Server"), ("db", "Database")],
    [("client", "api", "HTTP request"), ("api", "db", "SQL query")]
)
print(diagram)
def add_d2_containers(diagram_text, container_name, inner_nodes):
    """Group nodes inside a container in D2."""
    result = diagram_text + f'\n{container_name}: "{container_name}" {{\n'
    for node_id, label in inner_nodes:
        result += f'  {node_id}: "{label}"\n'
    result += "}"
    return result

diagram = "app: Application"
diagram = add_d2_containers(diagram, "app", [
    ("web", "Web Server"), ("worker", "Background Worker")
])
print(diagram)
def style_d2_node(diagram_text, node_id, style_options):
    """Apply styling to a D2 node."""
    style_str = ".".join(style_options)
    return diagram_text + f'\n{node_id}.style: {style_str}'

diagram = "server: API"
diagram = style_d2_node(diagram, "server",
                        ["fill: #2563eb", "color: white", "bold: true"])
print(diagram)

Teacher Mindset

Think of D2 as the streamlined sports car of diagram-as-code. It gets you where you need to go fast, looks good doing it, and requires less maintenance than bulkier alternatives. If Mermaid is a reliable sedan and PlantUML is a construction truck, D2 is the sleek coupe. It is not for every job, but when it fits, it is a joy to use.

Common Mistakes in D2

1. Expecting Mermaid-Like Syntax

D2 uses -> for arrows, not -->. The syntax is similar but different. Read the D2 quickstart before writing your first diagram.

2. Not Using Containers for Grouping

D2 containers group related elements visually and semantically. Without containers, related nodes are not visually grouped.

3. Overriding Automatic Layout

D2's automatic layout is one of its best features. Manually positioning nodes with coordinates defeats this advantage. Trust the layout engine.

4. Forgetting to Set the Layout Engine

D2 supports multiple layout engines (dagre, elk, tala). The default works for most cases. For complex diagrams, try different engines.

5. Not Exporting to SVG

D2 exports to SVG by default. SVG diagrams scale perfectly and support styling. Use SVG for documentation embedding.

Practice Questions

1. What is the basic syntax for a D2 diagram? Define nodes with name: "Label" and edges with source -> target: "Label". Containers group nodes with curly braces.

2. How does D2's automatic layout work? D2 uses layout engines (dagre by default) that position nodes and route edges automatically. You describe the structure, and D2 handles the visual arrangement.

3. How do you style nodes in D2? Use the .style property: node.style: fill: #color. Styles include fill, color, bold, italic, stroke, and border radius.

4. What diagram types does D2 support? D2 supports flowcharts, sequence diagrams, container diagrams, network diagrams, and custom diagrams. It is not limited to specific diagram types.

5. Challenge: Create a D2 diagram of a microservices architecture with at least 5 services, 2 containers, and styled elements. Render it to SVG and embed in documentation.

FAQ

Is D2 free?

Yes. D2 is open source with a permissive license. The CLI is free to use. A cloud rendering service with additional features is available.

How does D2 compare to Mermaid?

D2 has more concise syntax and better automatic layout. Mermaid has wider adoption and built-in Markdown support. Choose D2 for new projects where layout quality matters.

Can D2 render in the browser?

Yes. D2 compiles to WASM and can render in the browser. The d2js library enables browser-based rendering.

Does D2 support dark mode?

Yes. Use the --theme flag with dark theme. D2 adjusts colors automatically for dark backgrounds.

What is the output format for D2?

SVG by default. Also supports PNG and PDF. SVG is recommended for documentation because it scales and supports embedded styles.

Mini Project

Take an existing architecture diagram and rewrite it in D2. Use containers for each subsystem, style nodes for different types (service, database, external), and let D2's auto-layout arrange it. Compare the output with the original.

What's Next

Diagrams Python in the next lesson.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro