Skip to content

How to Visualize Your Codebase Architecture

Stop drawing architecture diagrams that are outdated before the ink dries. Here's how to generate visualizations from your actual code.

8 min read
Illustrative transparent architectural model revealing connected rooms and pathways.
On this page

I spent a week creating a beautiful architecture diagram in Lucidchart when I joined my third company. Color-coded boxes, clean arrows, labeled data flows. By the time I presented it to the team, two services had been renamed and a new database had been added. The diagram was wrong before it was finished.

That experience taught me something I should have learned years earlier: hand-drawn architecture diagrams are a maintenance burden disguised as documentation. Diagrams need a maintainable source and an owner. Generated views and versioned, text-based diagrams can both help.

Why Manual Diagrams Fail

Manual diagrams fail for the same reason all static documentation fails: code changes faster than docs. But diagrams are worse than written docs because they're harder to update. Editing a paragraph takes 30 seconds. Rearranging boxes and arrows in a diagramming tool takes 30 minutes.

The result is predictable. Teams create diagrams during planning, maybe update them once after launch, and then abandon them. Six months later, a new hire finds the diagram, assumes it's accurate, and builds mental models on a foundation of lies.

The Four Types of Useful Visualizations

Dependency graphs Imports C4 diagrams Audience and boundaries Data flows Data movement Hotspot maps Change frequency
Figure 1. Choose the view that answers the question you are investigating.

Not all visualizations are created equal. After experimenting with dozens of approaches, I've settled on four types that actually provide ongoing value.

Type 1: Dependency Graphs (Auto-Generated)

These show which modules import from which other modules. They're the most reliably useful visualization because they can be generated entirely from source code with zero manual input.[1]

For JavaScript/TypeScript:

bash
# Install madge and Graphviz (Ubuntu example)
npm install -g madge
sudo apt-get install graphviz

# Generate a dependency graph as SVG
madge --extensions ts,tsx --ts-config tsconfig.json --image dependency-graph.svg src/

# Find circular dependencies
madge --extensions ts,tsx --ts-config tsconfig.json --circular src/

# Generate a graph for a specific module
madge --extensions ts,tsx --ts-config tsconfig.json --image orders.svg src/orders/

Madge produces clean, readable graphs for projects up to about 200 modules. Beyond that, the graphs become spaghetti. For larger projects, filter by directory:

bash
# Only show dependencies within the orders module
madge --extensions ts,tsx --ts-config tsconfig.json --image orders-internal.svg --exclude "^(?!orders/)" --basedir src src/orders/

For Go:

bash
# List module dependencies with the built-in Go command
go mod graph
# Convert that edge list to DOT with a separate tool before Graphviz rendering.

For Python:

bash
pip install pydeps
pydeps myproject --max-bacon=2 --cluster

Type 2: C4 Model Diagrams (Semi-Automated)

The C4 model (Context, Containers, Components, Code) by Simon Brown provides four zoom levels for architecture visualization. The key insight is that you need different diagrams for different audiences.[2]

Level Audience Shows Update Frequency
Context Executives, new hires System + external actors Quarterly
Container Architects, DevOps Services, databases, queues Monthly
Component Developers Modules within a service As needed
Code Developers Classes/functions Never (use IDE)

For C4 diagrams, I use Structurizr DSL because it's code-based and lives in the repo:

workspace {
  model {
    user = person "Customer"
    system = softwareSystem "E-Commerce Platform" {
      webapp = container "Web App" "Next.js" "TypeScript"
      api = container "API Server" "Express" "TypeScript"
      db = container "Database" "" "PostgreSQL"
      cache = container "Cache" "" "Redis"
      queue = container "Message Queue" "" "RabbitMQ"
    }

    user -> webapp "Browses products, places orders"
    webapp -> api "API calls" "HTTPS/JSON"
    api -> db "Reads/writes data" "SQL"
    api -> cache "Caches sessions, product data"
    api -> queue "Publishes order events"
  }

  views {
    container system {
      include *
      autolayout lr
    }
  }
}

This DSL file lives in docs/architecture/workspace.dsl. Use Structurizr local to view the DSL workspace and adjust diagram layout. It is the current free, open-source equivalent of Structurizr Lite. Because it's code, it goes through PR review when updated.[3]

Type 3: Data Flow Diagrams (Manual but Stable)

Some visualizations need human judgment. Data flow diagrams show how data moves through the system: where it enters, how it transforms, where it persists. These change less frequently than code structure because data flows tend to be stable even as implementation details change.

I use Mermaid for these because it's text-based, renders in GitHub markdown, and is easy to update:[4]

graph LR
    A[Client Browser] -->|POST /api/orders| B[API Gateway]
    B -->|Validate + Auth| C[Order Service]
    C -->|Check stock| D[Inventory Service]
    C -->|Create order| E[(Orders DB)]
    C -->|Publish event| F[Message Queue]
    F -->|order.created| G[Payment Service]
    F -->|order.created| H[Notification Service]
    G -->|Payment result| E

Type 4: Hotspot Maps (Auto-Generated)

These visualize which parts of your codebase get the most attention. Built from git history, they show file size as bubble size and change frequency as color intensity.

bash
# Count file appearances in Git history
git log --format=format: --name-only --since="6 months ago" | \
  sed '/^$/d' | sort | uniq -c | sort -rn > churn.txt

# Combine with LOC counts for a treemap visualization
cloc --by-file --csv src/ > loc.csv

Tools like CodeScene generate these automatically and provide interactive treemaps. For a free alternative, you can feed the data into D3.js or use the git-of-theseus tool.

My Contrarian Take: Most Architecture Diagrams Should Be Ugly

I was wrong for years about diagram aesthetics. I spent hours making diagrams pretty: consistent colors, aligned boxes, curved arrows. Beautiful diagrams. Useless diagrams, because they were too expensive to update.

The diagrams that actually get maintained are the ugly ones. A Mermaid diagram in a markdown file. A text-based dependency graph. A whiteboard photo saved to the repo. These get updated because updating them takes 5 minutes, not 50.

Optimize for accuracy and maintainability, not beauty. A correct ugly diagram is worth infinitely more than a beautiful outdated one.

The Visualization Decision Tree

Use this to decide which visualization to create:

  1. Do you need to show module dependencies? Use auto-generated dependency graphs (madge, go mod graph).
  2. Do you need to explain the system to non-developers? Use C4 Context and Container diagrams.
  3. Do you need to show how data flows through the system? Use Mermaid data flow diagrams.
  4. Do you need to find refactoring targets? Use hotspot maps from git history.
  5. Do you need to show class relationships? Don't. Use your IDE's "Go to Definition" instead.

Setting Up Automated Visualization

Source changes Merge to main Generate Dependency graph Check Circular dependencies Commit Generated diagrams
Figure 2. Keep generation inputs and checks alongside the source code.

Here's a practical CI pipeline that generates architecture visualizations on every merge to main:[5]

yaml
# .github/workflows/architecture-viz.yml
name: Generate Architecture Visualizations
on:
  push:
    branches: [main]
    paths: ["src/**", "tsconfig.json", "package-lock.json", ".github/workflows/architecture-viz.yml"]
permissions:
  contents: write

jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history for git analysis

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - run: npm ci
      - run: npm install -g madge
      - run: sudo apt-get update && sudo apt-get install -y graphviz
      - run: mkdir -p docs/generated

      - name: Generate dependency graph
        run: madge --extensions ts,tsx --ts-config tsconfig.json --image docs/generated/dependency-graph.svg src/

      - name: Check for circular dependencies
        run: |
          CIRCULAR=$(madge --extensions ts,tsx --ts-config tsconfig.json --circular src/)
          if [ -n "$CIRCULAR" ]; then
            echo "::warning::Circular dependencies found"
            echo "$CIRCULAR"
          fi

      - name: Commit generated diagrams
        run: |
          git config user.name "github-actions"
          git config user.email "actions@github.com"
          git add docs/generated/
          git diff --staged --quiet || git commit -m "Update architecture visualizations"
          git push

This regenerates the dependency graph on matching changes. Review unresolved imports and check repository branch rules before allowing the workflow to push generated files.

Tools Worth Your Time

Tool Type Language Cost
madge Dependency graph JS/TS Free
Structurizr C4 diagrams Any Free (local)
Mermaid Flow diagrams Any Free
CodeScene Hotspot maps Any Commercial
Dependency Cruiser Dependency graph JS/TS Free
Arkit Architecture diagram JS/TS Free
code-maat Complexity analysis Any Free
Graphviz/dot Graph rendering Any Free

Start with one auto-generated dependency graph and one hand-drawn C4 Container diagram. That's enough for most teams. Add more visualizations only when you have a specific question that existing visualizations can't answer.

The goal isn't to create diagrams. It's to make the codebase understandable. Sometimes the best visualization is a three-line Mermaid diagram in a README. Sometimes it's a generated SVG in CI. Match the tool to the need.

Frequently asked questions

Which architecture diagram should I create first?

Start with a system boundary view and a dependency graph for the area you are changing. Together they show the outside connections and the internal imports, giving you a basis for asking more detailed questions.

Can dependency graphs explain runtime behaviour?

Import graphs show structural relationships in source code. Use a separate data-flow view to explain requests, queues and persistence, and check the running system when the diagram needs to describe actual behaviour.

What does Madge need to generate TypeScript diagrams?

Install Graphviz for image output and configure the TypeScript extensions and project configuration. Run Madge against the directory or entry point you intend to inspect and review warnings about unresolved imports.

How can architecture diagrams stay current?

Keep diagram definitions or generation commands in the repository and review them with code changes. A CI job can generate diagrams, while the team checks that the selected view still answers its intended question.

Sources

  1. [1]GitHub - pahen/madge: Create graphs from your CommonJS, AMD or ES6 module dependencies · Madge maintainers
  2. [2]The C4 model for visualising software architecture · Simon Brown, C4 model
  3. [3]local · Structurizr
  4. [4]Flowcharts Syntax · Mermaid
  5. [5]Use GITHUB_TOKEN for authentication in workflows · GitHub Docs

Checked against these sources on

Related Articles