# Composing Complex Diagram Sets > **Back to [Style Guide](../mermaid_style_guide.md)** โ€” This file covers how to combine multiple diagram types to document complex systems comprehensively. **Purpose:** A single diagram captures a single perspective. Real documentation often needs multiple diagram types working together โ€” an overview flowchart linked to a detailed sequence diagram, an ER schema paired with a state machine showing entity lifecycle, a Gantt timeline complemented by architecture before/after views. This file teaches you when and how to compose diagrams for maximum clarity. --- ## When to Compose Multiple Diagrams | What you're documenting | Diagram combination | Why it works | | ------------------------ | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | Full system architecture | C4 Context + Architecture + Sequence (key flows) | Context for stakeholders, infrastructure for ops, sequences for developers | | API design documentation | ER (data model) + Sequence (request flows) + State (entity lifecycle) | Schema for the database team, interactions for backend, states for business logic | | Feature specification | Flowchart (happy path) + Sequence (service interactions) + User Journey (UX) | Process for PM, implementation for engineers, experience for design | | Migration project | Gantt (timeline) + Architecture (before/after) + Flowchart (migration process) | Schedule for leadership, topology for infra, steps for the migration team | | Onboarding documentation | User Journey + Flowchart (setup steps) + Sequence (first API call) | Experience map for product, checklist for new hires, technical walkthrough for devs | | Incident response | State (alert lifecycle) + Sequence (escalation flow) + Flowchart (decision tree) | Status tracking for on-call, communication for management, triage for responders | --- ## Pattern 1: Overview + Detail **When to use:** You need both the big picture AND the specifics. Leadership sees the overview; engineers drill into the detail. The overview diagram shows high-level phases or components. One or more detail diagrams zoom into specific phases showing the internal interactions. ### Overview โ€” Release Pipeline ```mermaid flowchart LR accTitle: Release Pipeline Overview accDescr: High-level four-phase release pipeline from code commit through build, staging, and production deployment subgraph source ["๐Ÿ“ฅ Source"] commit[๐Ÿ“ Code commit] --> pr_review[๐Ÿ” PR review] end subgraph build ["๐Ÿ”ง Build"] compile[โš™๏ธ Compile] --> test[๐Ÿงช Test suite] test --> scan[๐Ÿ” Security scan] end subgraph staging ["๐Ÿš€ Staging"] deploy_stg[โ˜๏ธ Deploy staging] --> smoke[๐Ÿงช Smoke tests] smoke --> approval{๐Ÿ‘ค Approved?} end subgraph production ["โœ… Production"] canary[๐Ÿš€ Canary **5%**] --> rollout[๐Ÿš€ Full **rollout**] rollout --> monitor[๐Ÿ“Š Monitor metrics] end source --> build build --> staging approval -->|Yes| production approval -->|No| source classDef phase_start fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a5f classDef phase_test fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12 classDef phase_deploy fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d class commit,pr_review,compile phase_start class test,scan,smoke,approval phase_test class deploy_stg,canary,rollout,monitor phase_deploy ``` _The production deployment phase involves multiple service interactions. See the detail sequence below for the canary rollout process._ ### Detail โ€” Canary Deployment Sequence ```mermaid sequenceDiagram accTitle: Canary Deployment Service Interactions accDescr: Detailed sequence showing how the CI server orchestrates a canary deployment through the container registry, Kubernetes cluster, and monitoring stack with automated rollback on failure participant ci as โš™๏ธ CI Server participant registry as ๐Ÿ“ฆ Container Registry participant k8s as โ˜๏ธ Kubernetes participant monitor as ๐Ÿ“Š Monitoring participant oncall as ๐Ÿ‘ค On-Call Engineer ci->>registry: ๐Ÿ“ค Push tagged image registry-->>ci: โœ… Image stored ci->>k8s: ๐Ÿš€ Deploy canary (5% traffic) k8s-->>ci: โœ… Canary pods running ci->>monitor: ๐Ÿ“Š Start canary analysis Note over monitor: โฐ Observe for 15 minutes loop ๐Ÿ“Š Every 60 seconds monitor->>k8s: ๐Ÿ” Query error rate k8s-->>monitor: ๐Ÿ“Š Metrics response end alt โœ… Error rate below threshold monitor-->>ci: โœ… Canary healthy ci->>k8s: ๐Ÿš€ Promote to 100% k8s-->>ci: โœ… Full rollout complete ci->>monitor: ๐Ÿ“Š Continue monitoring else โŒ Error rate above threshold monitor-->>ci: โŒ Canary failing ci->>k8s: ๐Ÿ”„ Rollback to previous k8s-->>ci: โœ… Rollback complete ci->>oncall: โš ๏ธ Alert: canary failed Note over oncall: ๐Ÿ“‹ Investigate root cause end ``` ### How these connect - The **overview flowchart** shows the full pipeline with subgraph-to-subgraph connections โ€” leadership reads this to understand the release process - The **detail sequence** zooms into "Canary 5% โ†’ Full rollout" from the Production subgraph, showing the actual service interactions an engineer would debug - **Naming is consistent** โ€” "Canary" and "Monitor metrics" appear in both diagrams, creating a clear bridge between overview and detail --- ## Pattern 2: Multi-Perspective Documentation **When to use:** The same system needs to be documented for different audiences โ€” database teams, backend engineers, and product managers each need a different view of the same feature. This example documents a **User Authentication** feature from three perspectives. ### Data Model โ€” for database team ```mermaid erDiagram accTitle: Authentication Data Model accDescr: Five-entity schema for user authentication covering users, sessions, refresh tokens, login attempts, and MFA devices with cardinality relationships USER ||--o{ SESSION : "has" USER ||--o{ REFRESH_TOKEN : "owns" USER ||--o{ LOGIN_ATTEMPT : "produces" USER ||--o{ MFA_DEVICE : "registers" SESSION ||--|| REFRESH_TOKEN : "paired with" USER { uuid id PK "๐Ÿ”‘ Primary key" string email "๐Ÿ“ง Unique login" string password_hash "๐Ÿ” Bcrypt hash" boolean mfa_enabled "๐Ÿ”’ MFA flag" timestamp last_login "โฐ Last active" } SESSION { uuid id PK "๐Ÿ”‘ Primary key" uuid user_id FK "๐Ÿ‘ค Session owner" string ip_address "๐ŸŒ Client IP" string user_agent "๐Ÿ“‹ Browser info" timestamp expires_at "โฐ Expiration" } REFRESH_TOKEN { uuid id PK "๐Ÿ”‘ Primary key" uuid user_id FK "๐Ÿ‘ค Token owner" uuid session_id FK "๐Ÿ”— Paired session" string token_hash "๐Ÿ” Hashed token" boolean revoked "โŒ Revoked flag" timestamp expires_at "โฐ Expiration" } LOGIN_ATTEMPT { uuid id PK "๐Ÿ”‘ Primary key" uuid user_id FK "๐Ÿ‘ค Attempting user" string ip_address "๐ŸŒ Source IP" boolean success "โœ… Outcome" string failure_reason "โš ๏ธ Why failed" timestamp attempted_at "โฐ Attempt time" } MFA_DEVICE { uuid id PK "๐Ÿ”‘ Primary key" uuid user_id FK "๐Ÿ‘ค Device owner" string device_type "๐Ÿ“ฑ TOTP or WebAuthn" string secret_hash "๐Ÿ” Encrypted secret" boolean verified "โœ… Setup complete" timestamp registered_at "โฐ Registered" } ``` ### Authentication Flow โ€” for backend team ```mermaid sequenceDiagram accTitle: Login Flow with MFA accDescr: Step-by-step authentication sequence showing credential validation, conditional MFA challenge, token issuance, and failure handling between browser, API, auth service, and database participant B as ๐Ÿ‘ค Browser participant API as ๐ŸŒ API Gateway participant Auth as ๐Ÿ” Auth Service participant DB as ๐Ÿ’พ Database B->>API: ๐Ÿ“ค POST /login (email, password) API->>Auth: ๐Ÿ” Validate credentials Auth->>DB: ๐Ÿ” Fetch user by email DB-->>Auth: ๐Ÿ‘ค User record Auth->>Auth: ๐Ÿ” Verify password hash alt โŒ Invalid password Auth->>DB: ๐Ÿ“ Log failed attempt Auth-->>API: โŒ 401 Unauthorized API-->>B: โŒ Invalid credentials else โœ… Password valid alt ๐Ÿ”’ MFA enabled Auth-->>API: โš ๏ธ 202 MFA required API-->>B: ๐Ÿ“ฑ Show MFA prompt B->>API: ๐Ÿ“ค POST /login/mfa (code) API->>Auth: ๐Ÿ” Verify MFA code Auth->>DB: ๐Ÿ” Fetch MFA device DB-->>Auth: ๐Ÿ“ฑ Device record Auth->>Auth: ๐Ÿ” Validate TOTP alt โŒ Invalid code Auth-->>API: โŒ 401 Invalid code API-->>B: โŒ Try again else โœ… Code valid Auth->>DB: ๐Ÿ“ Create session + tokens Auth-->>API: โœ… 200 + tokens API-->>B: โœ… Set cookies + redirect end else ๐Ÿ”“ No MFA Auth->>DB: ๐Ÿ“ Create session + tokens Auth-->>API: โœ… 200 + tokens API-->>B: โœ… Set cookies + redirect end end ``` ### Login Experience โ€” for product team ```mermaid journey accTitle: Login Experience Journey Map accDescr: User satisfaction scores across the sign-in experience for password-only users and MFA users showing friction points in the multi-factor flow title ๐Ÿ‘ค Login Experience section ๐Ÿ” Sign In Navigate to login : 4 : User Enter email and password : 3 : User Click sign in button : 4 : User section ๐Ÿ“ฑ MFA Challenge Receive MFA prompt : 3 : MFA User Open authenticator app : 2 : MFA User Enter 6-digit code : 2 : MFA User Handle expired code : 1 : MFA User section โœ… Post-Login Land on dashboard : 5 : User See personalized content : 5 : User Resume previous session : 4 : User ``` ### How these connect - **Same entities, different views** โ€” "User", "Session", "MFA Device" appear in the ER diagram as tables, in the sequence as participants/operations, and in the journey as experience touchpoints - **Each audience gets actionable information** โ€” the DB team sees indexes and cardinality, the backend team sees API contracts and error codes, the product team sees satisfaction scores and friction points - **The journey reveals what the sequence hides** โ€” the sequence diagram shows MFA as a clean conditional branch, but the journey map shows it's actually the worst part of the UX (scores 1-2). This drives the product decision to invest in WebAuthn/passkeys --- ## Pattern 3: Before/After Architecture **When to use:** Migration documentation where stakeholders need to see the current state, the target state, and understand the transformation. ### Current State โ€” Monolith ```mermaid flowchart TB accTitle: Current State Monolith Architecture accDescr: Single Rails monolith handling all traffic through one server connected to one database showing the scaling bottleneck client([๐Ÿ‘ค All traffic]) --> mono[๐Ÿ–ฅ๏ธ Rails **Monolith**] mono --> db[(๐Ÿ’พ Single PostgreSQL)] mono --> jobs[โฐ Background **jobs**] jobs --> db classDef bottleneck fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d classDef neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#1f2937 class mono,db bottleneck class client,jobs neutral ``` > โš ๏ธ **Problem:** Single database is the bottleneck. Monolith can't scale horizontally. Deploy = full restart. ### Target State โ€” Microservices ```mermaid flowchart TB accTitle: Target State Microservices Architecture accDescr: Decomposed microservices architecture with API gateway routing to independent services each with their own data store and a shared message queue for async communication client([๐Ÿ‘ค All traffic]) --> gw[๐ŸŒ API **Gateway**] subgraph services ["โš™๏ธ Services"] user_svc[๐Ÿ‘ค User Service] order_svc[๐Ÿ“‹ Order Service] product_svc[๐Ÿ“ฆ Product Service] end subgraph data ["๐Ÿ’พ Data Stores"] user_db[(๐Ÿ’พ Users DB)] order_db[(๐Ÿ’พ Orders DB)] product_db[(๐Ÿ’พ Products DB)] end gw --> user_svc gw --> order_svc gw --> product_svc user_svc --> user_db order_svc --> order_db product_svc --> product_db order_svc --> mq[๐Ÿ“ฅ Message Queue] mq --> user_svc mq --> product_svc classDef gateway fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764 classDef service fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a5f classDef datastore fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d classDef infra fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12 class gw gateway class user_svc,order_svc,product_svc service class user_db,order_db,product_db datastore class mq infra ``` > โœ… **Result:** Each service scales independently. Database-per-service eliminates the shared bottleneck. Async messaging decouples service dependencies. ### How these connect - **Same layout, different complexity** โ€” both diagrams use `flowchart TB` so the structural transformation is visually obvious. The monolith is 4 nodes; the target is 11 nodes with subgraphs. - **Color tells the story** โ€” the monolith uses red (danger) on the bottleneck components. The target uses blue/green/purple to show healthy, differentiated components. - **Prose bridges the diagrams** โ€” the โš ๏ธ problem callout and โœ… result callout explain _why_ the architecture changes, not just _what_ changed. --- ## Linking Diagrams in Documentation When composing diagrams in a real document, follow these practices: | Practice | Example | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | **Use headers as anchors** | `See [Authentication Flow](#authentication-flow-for-backend-team) for the full login sequence` | | **Reference specific nodes** | "The **API Gateway** from the overview connects to the services detailed below" | | **Consistent naming** | Same entity = same name in every diagram (User Service, not "User Svc" in one and "Users API" in another) | | **Adjacent placement** | Keep related diagrams in consecutive sections, not scattered across the document | | **Bridging prose** | One sentence between diagrams explaining how they connect: "The sequence below zooms into the Deploy phase from the pipeline above" | | **Audience labels** | Mark sections: "### Data Model โ€” _for database team_" so readers skip to their view | --- ## Choosing Your Composition Strategy ```mermaid flowchart TB accTitle: Diagram Composition Decision Tree accDescr: Decision flowchart for choosing between single diagram, overview plus detail, multi-perspective, or before-after composition strategies based on audience and documentation needs start([๐Ÿ“‹ What are you documenting?]) --> audience{๐Ÿ‘ฅ Multiple audiences?} audience -->|Yes| perspectives[๐Ÿ“ Multi-Perspective] audience -->|No| depth{๐Ÿ“ Need both summary and detail?} depth -->|Yes| overview[๐Ÿ” Overview + Detail] depth -->|No| change{๐Ÿ”„ Showing a change over time?} change -->|Yes| before_after[โšก Before / After] change -->|No| single[๐Ÿ“Š Single diagram is fine] classDef decision fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12 classDef result fill:#dbeafe,stroke:#2563eb,stroke-width:2px,color:#1e3a5f classDef start_style fill:#ede9fe,stroke:#7c3aed,stroke-width:2px,color:#3b0764 class audience,depth,change decision class perspectives,overview,before_after,single result class start start_style ```