How to Create State Diagrams in Confluence (Mermaid Examples)
State diagrams (also called state machine diagrams) model how a system transitions between discrete states in response to events. They are essential for documenting order lifecycles, user authentication flows, CI/CD pipelines, IoT device behavior, and any system where the current state determines what happens next. If your team uses Confluence for technical documentation, embedding state diagrams directly on your pages keeps your design decisions alongside runbooks, architecture decision records, and sprint planning notes.
In this tutorial, you will learn how to create state diagrams in Confluence using the Mermaid stateDiagram-v2 syntax. Every example is copy-paste ready, so you can drop it straight into a Confluence page and see the rendered result immediately.
Why State Diagrams in Confluence?
Teams reach for state diagrams when they need to answer the question: "What states can this thing be in, and how does it move between them?" Unlike flowcharts that emphasize decision branches, or sequence diagrams that focus on message ordering, state diagrams focus on the lifecycle of a single entity. This makes them ideal for:
- Order and fulfillment systems where an order moves through states like Placed, Paid, Shipped, Delivered, and Cancelled, and the valid transitions depend on the current state
- User authentication and session management where a user account moves through Unverified, Active, Locked, and Suspended states based on login attempts, email verification, and admin actions
- CI/CD pipelines where a build progresses through Triggered, Building, Testing, Deploying, and Completed or Failed states
- IoT and embedded systems where a device switches between Idle, Processing, Error, and Maintenance states in response to sensor readings and timeouts
- Workflow engines where a ticket or request follows a defined state machine with approval gates, escalation rules, and rollback paths
Confluence is where this context already lives. Adding rendered state diagrams directly on those pages eliminates the friction of linking out to external diagramming tools or attaching exported images that go stale the moment the code changes. Mermaid is the most popular text-to-diagram language, and with Mermaid Plus for Confluence you get a first-class editing experience right inside the Confluence editor.
Step-by-Step: Create Your First State Diagram
Follow these five steps to go from a blank Confluence page to a fully rendered state diagram.
Step 1 -- Install Mermaid Plus for Confluence
Head to the Atlassian Marketplace and search for Mermaid Plus for Confluence. Click Get App and follow the installation prompts. Once installed, the Mermaid Plus macro becomes available on every space in your Confluence instance. The app supports both Confluence Cloud and Confluence Data Center.
If your organization requires admin approval for marketplace apps, send the link to your Confluence administrator.
Step 2 -- Insert the Mermaid Macro on a Confluence Page
Open any Confluence page in edit mode. Type /mermaid in the editor and select Mermaid Plus for Confluence from the dropdown. A configuration panel opens with a three-column layout:
- Left column: Live Preview, which renders your diagram in real time as you type
- Middle column: Quick Templates for all 26 supported diagram types
- Right column: Settings (font, colors, theme, output size) and the Code Editor
Step 3 -- Write the stateDiagram-v2 Header and Define States
Start every state diagram with the stateDiagram-v2 keyword. This is the updated version of the state diagram syntax and supports all modern features including composite states and notes. Define your states by name, and use [*] to mark the initial (start) and final (end) states:
stateDiagram-v2
[*] --> Idle
Idle --> Processing
Processing --> Done
Done --> [*]
The [*] symbol on the left side of a transition marks the starting point. On the right side, it marks a terminal state. You can have multiple terminal states in a single diagram if your system has more than one end condition.
Step 4 -- Add Transitions, Composite States, and Notes
This is where state diagrams get powerful. Label your transitions with trigger events, group related states into composite (nested) states, and annotate states with notes:
stateDiagram-v2
[*] --> Idle
state Active {
[*] --> Running
Running --> Paused : pause
Paused --> Running : resume
}
Idle --> Active : start
Active --> Idle : stop
Running --> Error : exception
note right of Error
Requires manual
intervention to reset
end note
Step 5 -- Save and Publish the Diagram
Check the live preview in the left column to verify the diagram renders correctly. Adjust the theme, colors, or output size in the right column if needed. When you are satisfied, click Save to insert the macro into the page, then Publish the Confluence page.
To edit the diagram later, click on the rendered diagram in view mode and select Edit. All your code and settings are preserved.
Mermaid State Diagram Syntax Reference
Before diving into the full examples, here is a quick-reference for the syntax elements you will use most often.
Basic Elements
| Element | Syntax | Description |
|---|---|---|
| State declaration | StateName | A state is created implicitly when referenced in a transition |
| Start state | [*] | The black-circle initial pseudo-state |
| End state | [*] | The bullseye final pseudo-state (same symbol, on the right side of a transition) |
| Transition | StateA --> StateB | Arrow from StateA to StateB |
| Labeled transition | StateA --> StateB : event | Arrow with an event or action label |
| Composite state | state "Name" { ... } | A state containing nested sub-states |
| Note | note left/right of State | Annotation attached to a state |
| Note (multiline) | note ... end note | Multi-line note block |
| Direction | direction LR or direction TB | Control layout direction inside a composite state |
| Comment | %% This is a comment | Inline comment, not rendered |
Transition Syntax
Transitions are the backbone of any state diagram. The basic form is:
SourceState --> TargetState : trigger / action
The part after the colon is optional. You can include a trigger event, an action, or both separated by a slash. In practice, most teams use the label to describe what causes the transition:
Idle --> Processing : onTaskReceived
Processing --> Done : onComplete
Processing --> Error : onException
Error --> Idle : onReset
You can also create self-transitions (a state transitioning to itself), which are useful for modeling retry logic or periodic updates:
Polling --> Polling : onTimeout
Composite (Nested) States
Composite states let you group related sub-states inside a parent state. This is essential for managing complexity in real-world state machines. The outer state defines shared behavior, while inner states define the details:
stateDiagram-v2
[*] --> Off
state On {
[*] --> Starting
Starting --> Running : initialized
Running --> Stopping : shutdown
Stopping --> [*]
}
Off --> On : powerOn
On --> Off : powerOff
Composite states can nest deeply. A composite state can contain other composite states, allowing you to model hierarchical state machines. However, keep nesting to two or three levels for readability.
Fork and Join
Mermaid supports fork and join pseudo-states for modeling concurrent transitions. A fork splits one transition into multiple parallel transitions, and a join synchronizes multiple parallel transitions into one:
stateDiagram-v2
[*] --> Waiting
state fork_state <<fork>>
state join_state <<join>>
Waiting --> fork_state
fork_state --> StateA
fork_state --> StateB
StateA --> join_state
StateB --> join_state
join_state --> Finished
Finished --> [*]
Direction Control
By default, state diagrams render top-to-bottom. Inside composite states, you can change the direction using the direction keyword:
state On {
direction LR
[*] --> Starting
Starting --> Running
}
Valid directions are LR (left-to-right), RL (right-to-left), TB (top-to-bottom), and BT (bottom-to-top). Use direction LR inside composite states when the sub-states have a natural left-to-right progression.
State Aliases
If a state name contains spaces or special characters, wrap it in quotes and optionally assign an alias:
state "Awaiting Approval" as AwaitApproval
Idle --> AwaitApproval : submit
AwaitApproval --> Approved : approve
Notes
Notes add context without cluttering the diagram. Use them to explain non-obvious rules, timeout durations, or error conditions:
note left of Locked
Account locks after 5
consecutive failed attempts
end note
Notes can also span multiple lines using the note ... end note block syntax, which is useful for longer explanations.
Concurrent States
You can model parallel regions inside a composite state by using the -- separator between state groups:
stateDiagram-v2
[*] --> Active
state Active {
[*] --> TaskRunning
TaskRunning --> TaskDone : finish
--
[*] --> Monitoring
Monitoring --> Alert : thresholdExceeded
Alert --> Monitoring : resolved
}
Active --> [*]
Each region separated by -- operates independently, which is how you represent truly concurrent behavior in a state machine.
3 Copy-Paste State Diagram Examples
Below are three practical examples you can paste directly into the Mermaid Plus macro in Confluence. Each example demonstrates a different real-world scenario with progressively more advanced features.
Example 1 -- E-Commerce Order Lifecycle
This diagram models the complete lifecycle of an e-commerce order, from creation through fulfillment or cancellation. It covers the most common states and transitions that any online store needs to handle.
stateDiagram-v2
[*] --> Draft : customer creates cart
Draft --> Submitted : checkout
Submitted --> PaymentPending : validateOrder
state PaymentPending {
[*] --> AwaitingPayment
AwaitingPayment --> PaymentSuccess : paymentApproved
AwaitingPayment --> PaymentFailed : paymentDeclined
PaymentFailed --> AwaitingPayment : retryPayment
}
PaymentPending --> Confirmed : paymentSuccess
PaymentPending --> Cancelled : paymentTimeout
Confirmed --> Processing : warehousePickup
Processing --> Shipped : carrierPickedUp
state Delivery {
[*] --> InTransit
InTransit --> OutForDelivery : atLocalFacility
OutForDelivery --> Delivered : deliveryConfirmed
OutForDelivery --> DeliveryFailed : deliveryException
DeliveryFailed --> InTransit : reschedule
}
Shipped --> Delivery : trackingActive
Delivery --> Completed : deliveryConfirmed
Delivery --> Returned : returnRequested
Completed --> [*]
Cancelled --> [*]
Returned --> Refunded : refundProcessed
Refunded --> [*]
note right of Processing
Warehouse allocates inventory
and prepares shipment
end note
note right of Cancelled
Order can be cancelled
before shipment only
end note
This diagram demonstrates several key features:
- Composite states --
PaymentPendingandDeliverygroup related sub-states into logical phases of the order lifecycle - Multiple terminal states -- The order can end in
Completed,Cancelled, orRefundeddepending on the path taken - Notes -- Annotations on
ProcessingandCancelledexplain business rules that are not obvious from the state names alone - Self-transitions within composites --
PaymentFailed --> AwaitingPayment : retryPaymentshows a loop inside a composite state - Cross-composite transitions --
Delivery --> Returnedshows a transition out of a composite state to an external state
Use this diagram as a starting point for your own order management documentation. Add states for backorders, split shipments, partial refunds, or fraud review as your business requires.
Example 2 -- User Authentication Flow
This diagram models a user account state machine covering registration, email verification, login attempts, account locking, and administrative actions. It is representative of what you would document for a SaaS product's identity and access management system.
stateDiagram-v2
[*] --> Unregistered : userVisitsSignup
Unregistered --> PendingVerification : submitRegistration
PendingVerification --> Active : verifyEmail
PendingVerification --> Unregistered : verificationExpired
state Active {
[*] --> LoggedOut
LoggedOut --> LoggedIn : loginSuccess
LoggedIn --> LoggedOut : logout
state LoggedIn {
[*] --> Browsing
Browsing --> Editing : openEditor
Editing --> Browsing : saveOrDiscard
Browsing --> Idle : timeout
Idle --> Browsing : resumeActivity
}
}
LoggedOut --> Locked : failedAttemptLimit
state Locked {
[*] --> AutoLocked
AutoLocked --> UnlockRequested : requestUnlock
UnlockRequested --> Unlocked : adminApproves
UnlockRequested --> AutoLocked : adminDenies
}
Locked --> Active : unlockSuccess
Locked --> Suspended : lockTimeout
Active --> Suspended : adminSuspends
Suspended --> Active : adminReactivates
Suspended --> Deleted : adminDeletes
Deleted --> [*]
note right of Locked
Triggered after 5 consecutive
failed login attempts
end note
note left of Suspended
Account is frozen.
User cannot log in.
Admin action required.
end note
note right of PendingVerification
Verification link expires
after 24 hours
end note
This diagram introduces:
- Nested composite states --
ActivecontainsLoggedIn, which itself containsBrowsing,Editing, andIdle, demonstrating three levels of nesting - Cross-state transitions --
LoggedOut --> Lockedcrosses from insideActiveintoLocked, showing how state machines model events that move entities between major lifecycle phases - Multiple notes -- Notes on
Locked,Suspended, andPendingVerificationexplain business rules without cluttering the transition labels - Admin-driven transitions -- Several transitions (
adminSuspends,adminReactivates,adminDeletes) show that not all state changes are user-driven - Timeout-based transitions --
verificationExpiredandlockTimeoutmodel time-based state changes common in authentication systems
Example 3 -- CI/CD Pipeline States
This diagram models a continuous integration and deployment pipeline, from code commit through build, test, deploy, and either success or failure. It is the kind of diagram you would include in a DevOps runbook or platform engineering documentation.
stateDiagram-v2
[*] --> Triggered : codePush / PRMerge / schedule
state Build {
direction LR
[*] --> Queued
Queued --> Building : agentAssigned
Building --> BuildSuccess : exitCode0
Building --> BuildFailed : exitCodeNonZero
}
Triggered --> Build : pipelineStart
state Test {
[*] --> UnitTests
UnitTests --> IntegrationTests : unitPass
IntegrationTests --> E2ETests : integrationPass
state E2ETests {
[*] --> Provisioning
Provisioning --> Running : environmentReady
Running --> E2EPass : allTestsPass
Running --> E2EFail : testFailure
}
}
Build --> Test : buildSuccess
Build --> Failed : buildFailed
Test --> Deploy : allTestsPass
Test --> Failed : testFailure
state Deploy {
direction LR
[*] --> Staging
Staging --> Canary : stagingHealthy
Canary --> Production : canaryMetricsHealthy
Canary --> Rollback : canaryMetricsDegraded
Rollback --> Staging : rollbackComplete
}
Deploy --> Completed : deploySuccess
Deploy --> Failed : deployFailure
Failed --> [*] : pipelineTerminated
Completed --> [*]
state Cleanup {
[*] --> TearingDown
TearingDown --> Done : resourcesReleased
}
Completed --> Cleanup : autoCleanup
Failed --> Cleanup : autoCleanup
Cleanup --> [*]
note right of Canary
5% traffic for 10 minutes.
Rollback on error rate > 1%
or p99 latency > 500ms
end note
note right of Failed
Notifications sent to:
- Commit author via Slack
- #ci-alerts channel
- PagerDuty (on-call)
end note
note left of Rollback
Automatic rollback preserves
the last known-good deployment
end note
This diagram is the most complex of the three and demonstrates the full power of Mermaid state diagrams:
- Multiple composite states --
Build,Test,E2ETests,Deploy, andCleanupeach encapsulate a distinct pipeline phase - Direction control --
direction LRinsideBuildandDeployrenders the sub-states horizontally for better readability when the sub-states are sequential - Nested composites --
E2ETestsis a composite state nested inside theTestcomposite state, showing two levels of nesting - Rollback loops --
Canary --> Rollback --> Stagingmodels a recovery loop within the deployment phase - Shared cleanup path -- Both
CompletedandFailedconverge intoCleanup, demonstrating how state machines model shared teardown logic - Multiple entry triggers -- The
Triggeredstate accepts three different triggers (codePush,PRMerge,schedule), showing how a state can respond to multiple events - Rich notes -- Notes on
Canary,Failed, andRollbackexplain operational policies and alerting rules
Tips for Building Effective State Diagrams
Start with the States, Then Add Transitions
Begin by listing all the states your entity can be in. Write them as bullet points or a simple list first. Once you have the complete set, draw the transitions between them. This two-pass approach prevents you from missing edge-case states like Error, TimedOut, or Cancelled.
Use Composite States to Manage Complexity
Any state diagram with more than eight or ten flat states becomes hard to follow. Group related states into composite states. A good rule of thumb: if a set of states shares a common entry or exit transition, they belong in a composite state.
Label Every Transition
Unlabeled transitions (Idle --> Running) are ambiguous. What triggers the change? Always add a label (Idle --> Running : onStartCommand). The label should describe the event or condition that causes the transition.
Include Error and Timeout States
Real systems fail, time out, and get interrupted. Every state diagram should account for error paths and timeout transitions. If your diagram only shows the happy path, it is incomplete. Add Error, Failed, TimedOut, and Cancelled states alongside the normal flow.
Use Notes for Business Rules
Notes are the right place for business rules that do not fit neatly into a transition label. Examples: timeout durations, retry limits, approval requirements, and notification rules. Keep notes short -- two or three lines at most.
Keep the Diagram Focused on One Entity
A state diagram should model the lifecycle of a single entity: one order, one user account, one pipeline run. If you find yourself modeling interactions between two different entities, use a sequence diagram instead. See how to create sequence diagrams in Confluence for that use case.
Use Themes for Visual Consistency
Mermaid Plus for Confluence offers four built-in themes: Default, Dark, Forest, and Neutral. Pick one theme for all state diagrams in a space and use it consistently. The Default theme lets you customize node, text, border, line, and background colors to match your company brand. For detailed configuration options, refer to the Mermaid Plus for Confluence usage guide.
Common Mistakes and How to Fix Them
Using stateDiagram instead of stateDiagram-v2. The original stateDiagram keyword lacks support for composite states, notes, and direction control. Always use stateDiagram-v2 for full feature support.
Forgetting [*] start and end markers. Every state machine should have at least one start state ([*]) and at least one end state (a transition to [*]). Without them, the diagram has no clear entry or exit point, which makes the lifecycle ambiguous.
Missing transition labels. An unlabeled transition tells the reader that the change happens, but not why. Always add a label: Idle --> Running : onStart is clearer than Idle --> Running.
Overcrowding with too many states. A flat state diagram with 15 or more states becomes unreadable. Use composite states to group related sub-states. If the diagram is still too complex, split it into two diagrams: one showing the high-level lifecycle and another showing the details of a specific phase.
Inconsistent naming conventions. Pick one naming style and stick with it. If your states are PascalCase, use PascalCase for all of them. Mixing camelCase, snake_case, and PascalCase in the same diagram looks unprofessional and makes the diagram harder to scan.
Notes that are too long. A note should be a brief annotation, not a paragraph. If you need more than three lines to explain a state, the explanation belongs in the surrounding Confluence page text, not in the diagram itself.
When to Use State Diagrams vs Other Diagram Types
State diagrams are not the right tool for every situation. Here is a quick guide to help you choose the right diagram type for your documentation:
- State diagram -- Use when documenting entity lifecycles, state machines, order statuses, and any system where the current state determines what transitions are valid
- Sequence diagram -- Use when documenting message flows between services, API interactions, and step-by-step communication protocols. See how to create sequence diagrams in Confluence
- Class diagram -- Use when documenting static structure: class hierarchies, domain models, and object relationships. See how to create class diagrams in Confluence
- Flowchart -- Use when documenting processes, decision trees, and algorithmic logic with branching paths
- ER diagram -- Use when documenting database schemas and entity relationships without behavioral semantics
Many architecture documents benefit from combining diagram types. A state diagram shows what states an order can be in, a sequence diagram shows how the services communicate during each transition, and a class diagram shows the domain model that underpins the whole system.
Advanced: Styling State Diagrams
Mermaid supports inline styling with the style keyword. You can highlight critical states, error states, or the current state in a snapshot diagram by changing colors:
stateDiagram-v2
[*] --> Idle
Idle --> Running
Running --> Error
Error --> Idle
style Error fill:#ffcccc,stroke:#ff0000,stroke-width:2px
style Running fill:#ccffcc,stroke:#00aa00,stroke-width:2px
Apply styling judiciously. One or two highlighted states draw attention to the most important parts of the diagram. Highlighting every state creates visual noise.
You can also use the Mermaid Plus for Confluence theme settings to control the overall color palette. The Default theme gives you five customizable color slots (node, text, border, line, and background) that apply across the entire diagram. This is a better approach than inline styles when you want consistent branding across all diagrams in a space.
Related Resources
- Mermaid Plus for Confluence usage guide -- configuration panel walkthrough, theme settings, font and color customization, and all 26 supported diagram types
- How to create sequence diagrams in Confluence -- document message flows between services with copy-paste Mermaid examples
- Mermaid syntax cheat sheet for Confluence -- quick reference for all Mermaid diagram types supported in Confluence
- How to create class diagrams in Confluence -- document domain models and class hierarchies with Mermaid class diagrams
State diagrams are one of the most effective ways to communicate the behavioral logic of your system. They capture the "what state is this in, and what happens next" question that prose alone struggles to answer clearly. With Mermaid Plus for Confluence, creating and maintaining state diagrams is as simple as writing text. Install the app, paste one of the examples above into a Confluence page, and start documenting your system's state machines where they belong -- alongside everything else your team needs.