Skip to content

L04 Mermaid C4 Diagrams

DodaTech 5 min read

title: "Mermaid C4 Diagrams — Software Architecture Visualization" weight: 4 description: "Learn Mermaid C4 diagrams for software architecture: System Context, Container, Component, and Code diagrams following the C4 model for clear hierarchical architecture documentation." date: 2026-06-28 lastmod: 2026-06-28 tags: [technical-writing, diagram-as-code] }

Mermaid C4 diagrams implement the C4 model for software architecture visualization, providing four levels of abstraction from system context down to code-level components.

In this lesson, you will learn the C4 model concepts, how to create System Context, Container, Component, and Code diagrams with Mermaid, and how to use them for architecture documentation.

What You'll Learn

You will learn the C4 model hierarchy, create diagrams at each level using Mermaid C4 syntax, use relationships and boundaries, and apply C4 diagrams to real architecture documentation.

Why It Matters

The C4 model is the industry standard for software architecture diagrams. It provides a consistent, hierarchical view that works for both technical and non-technical stakeholders.

Real-World Use

DodaZIP's architecture is documented with C4 diagrams. The System Context diagram is shared with product managers. The Container and Component diagrams guide developers implementing new features.

C4Context
    title System Context - DodaZIP
    Enterprise_Boundary(b0, "DodaTech") {
        Person(user, "User", "Compresses and extracts files")
        System(dodazip, "DodaZIP", "File compression and extraction tool")
        System_Ext(fs, "File System", "Local storage for archives")
    }
    Rel(user, dodazip, "Uses")
    Rel(dodazip, fs, "Reads/Writes files")
def create_c4_context_diagram(system_name, actors, systems):
    """Generate C4 Context diagram in Mermaid syntax."""
    lines = ["C4Context", f'    title System Context - {system_name}']
    for actor in actors:
        lines.append(f'    Person({actor["id"]}, "{actor["name"]}", "{actor["desc"]}")')
    for sys in systems:
        ext = "_Ext" if sys.get("external") else ""
        lines.append(f'    System{ext}({sys["id"]}, "{sys["name"]}", "{sys["desc"]}")')
    for rel in actors[0].get("relationships", []):
        lines.append(f'    Rel({rel["from"]}, {rel["to"]}, "{rel["label"]}")')
    return "\n".join(lines)

diagram = create_c4_context_diagram("DodaZIP",
    [{"id": "u", "name": "User", "desc": "File compression user",
      "relationships": [{"from": "u", "to": "dz", "label": "Uses"}]}],
    [{"id": "dz", "name": "DodaZIP", "desc": "Compression tool"},
     {"id": "fs", "name": "File System", "desc": "Local storage", "external": True}]
)
print(diagram)
def create_c4_container_diagram(system_name, containers):
    """Generate C4 Container diagram."""
    lines = ["C4Container", f'    title Container Diagram - {system_name}']
    for c in containers:
        lines.append(f'    Container({c["id"]}, "{c["name"]}", "{c["tech"]}", "{c["desc"]}")')
    for rel in containers:
        for target, label in rel.get("relationships", []):
            lines.append(f'    Rel({rel["id"]}, {target}, "{label}")')
    return "\n".join(lines)

diagram = create_c4_container_diagram("DodaZIP", [
    {"id": "ui", "name": "Web UI", "tech": "React", "desc": "User interface",
     "relationships": [("api", "API calls")]},
    {"id": "api", "name": "API Server", "tech": "Python/FastAPI", "desc": "Backend API",
     "relationships": [("db", "Queries")]},
    {"id": "db", "name": "Database", "tech": "PostgreSQL", "desc": "Metadata storage"},
])
print(diagram)
def create_c4_component_diagram(container_name, components):
    """Generate C4 Component diagram for a specific container."""
    lines = ["C4Component", f'    title Component Diagram - {container_name}']
    for comp in components:
        lines.append(f'    Component({comp["id"]}, "{comp["name"]}", "{comp["tech"]}", "{comp["desc"]}")')
    return "\n".join(lines)

Teacher Mindset

Think of C4 diagrams as zoom levels in a map application. At the country level (Context), you see the whole system and its users. Zoom into a city (Container), and you see the major applications and data stores. Zoom into a neighborhood (Component), and you see individual services. Zoom into a building (Code), and you see classes and interfaces. Each level serves a different audience.

Common Mistakes in C4 Diagrams

1. Mixing Levels in One Diagram

Putting code-level details in a System Context diagram defeats the purpose. Each diagram stays at its level. Create separate diagrams for different zoom levels.

2. Too Many External Systems in Context

The Context diagram should show the system boundary clearly. Including every external dependency clutters the diagram. Show only direct interactions.

3. Missing Technology Choices in Container Diagrams

Container diagrams should show technology choices (React, Python, PostgreSQL). This information helps architects assess the technology stack.

4. Component Diagrams That Are Too Detailed

Component diagrams should show major components and their interactions, not every class and interface. Save class-level detail for Code diagrams.

5. No Boundaries in Context Diagrams

Enterprise and system boundaries help readers distinguish what is inside versus outside the system. Always include boundaries.

Practice Questions

1. What are the four levels of the C4 model? System Context, Container, Component, and Code. Each level shows more detail about a smaller part of the system.

2. What information goes in a System Context diagram? The system being described, the users who interact with it, and the external systems it depends on. No internal details.

3. What is a Container in C4 terms? A container is an application or data store: web application, API server, database, file system. Not a Docker container. C4 containers = deployable units.

4. When would you create a Code-level diagram? For critical or complex components where the class structure is important for understanding the implementation.

5. Challenge: Create a 3-level C4 diagram set for an application you know: System Context, Container, and Component. Ensure each level stays within its scope and uses correct relationships.

FAQ

Do I need to create all four C4 levels?

No. Create the levels that add value. Most projects need Context and Container levels. Component is useful for complex subsystems. Code is rarely needed.

How do C4 diagrams differ from UML?

C4 is a simplified, practical approach focused on software architecture. UML is broader and more detailed. C4 is easier for non-technical stakeholders to understand.

Can I use C4 with other diagram-as-code tools?

Yes. Structurizr was built for C4. PlantUML also supports C4. D2 has C4 support. Mermaid added C4 in recent versions.

How do I keep C4 diagrams consistent across levels?

Use the same naming conventions for elements that appear in multiple levels. A container name in the Context diagram should match its name in the Container diagram.

Should C4 diagrams include deployment information?

The C4 model has a separate Deployment diagram level. Use it to show how containers map to infrastructure.

Mini Project

Document the architecture of an open-source project using C4 diagrams. Create a System Context diagram, a Container diagram with at least 4 containers, and a Component diagram for one container. Publish all three in a documentation page.

What's Next

PlantUML in the next lesson.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro