10.1 Flowcharts, Sequences & Parallel Control Flow Patterns
Key Takeaways
Sequences suit linear steps, flowcharts suit branching decisions, and state machines suit named stages that repeat or recover.
Parallel schedules all branches at once but runs them on one workflow thread; branches interleave only when an activity goes idle, and CompletionCondition can cancel the remaining branches.
Pick starts every branch's trigger, runs only the Action of the first trigger to complete, and cancels the others.
Parallel For Each interleaves iterations the same way and supports a CompletionCondition; interactive UI activities should not run in parallel branches or iterations.
Give parallel branches their own variables and merge results afterwards, because shared objects such as DataTables are not safe for concurrent updates.
10.1 Flowcharts, Sequences & Parallel Control Flow Patterns
Core Concept: In enterprise UiPath automation, selecting the appropriate control flow paradigm dictates the maintainability, scalability, and execution performance of the entire robotic process. UiPath Studio provides three foundational top-level workflow structures—Sequences, Flowcharts, and State Machines—alongside advanced concurrent and event-driven branching constructs such as Parallel, Parallel For Each, and Pick. Knowing how each one schedules work lets developers coordinate waits on several services, handle multi-path business logic, and react to whichever UI state appears first.
Control flow defines the precise order in which individual activities execute within a software robot's execution context. While basic automation tasks can often be modeled in a straightforward procedural manner, enterprise-grade robotic automations demand sophisticated control structures that accommodate complex decision trees, asynchronous event monitoring, concurrent background data processing, and stateful lifecycle management.
1. The Three Primary Workflow Layouts
UiPath Studio organizes execution logic through three primary container layouts, each tailored to specific architectural complexities:
Workflow Control Flow Paradigms
├── Sequence: Linear, top-to-bottom, lowest execution overhead
├── Flowchart: 2D diagrammatic branching, multi-criteria FlowSwitch, cyclic loops
└── State Machine: Event-driven state transitions, initialization, transaction loop, finalization
1. Sequences: Linear Procedural Execution
A Sequence executes child activities in a strict, top-to-bottom procedural order.
- Execution Mechanics: The workflow runtime schedules each activity sequentially. Activity N+1 cannot initialize until Activity N completes its execution lifecycle (or yields its asynchronous completion callback).
- Performance Overhead: Sequences introduce the lowest CPU and memory execution overhead among all UiPath containers. Because there is no branching engine or state-tracking infrastructure, execution transitions between activities occur virtually instantaneously.
- Architectural Role: Sequences are optimal for atomic, predictable operations where step order is invariant. Examples include reading a local configuration file, preparing in-memory data structures, navigating a predefined series of form screens, or mapping database fields.
- Anti-Pattern Warning: Deeply nesting Sequences within Sequences (often called the "Arrow Anti-Pattern" or "Pyramid of Doom") rapidly degrades code readability and makes visual debugging cumbersome. When complex nested
If-Elseconditions proliferate inside a Sequence, developers should refactor the logic into a Flowchart or sub-workflows.
2. Flowcharts: 2D Diagrammatic Branching & Loops
A Flowchart provides a two-dimensional visual canvas where activities (nodes) are interconnected via directional execution arrows (transitions).
- Execution Mechanics: Control flows from the designated Start Node along connected lines. Flowcharts natively support branching through
FlowDecision(evaluating a boolean condition into True/False branches) andFlowSwitch<T>(evaluating a generic expression into multiple distinct outcome paths, analogous to a C# / VBswitchorSelect Casestatement). - Cyclic Logic and Retries: Unlike Sequences, which strictly enforce forward procedural progression, Flowcharts naturally support cyclic loops where an execution path loops back to an earlier activity. This makes Flowcharts exceptionally well-suited for modeling iterative retries, polling loops, and multi-path business validation rules.
- Architectural Role: Flowcharts excel at modeling high-level process orchestrations, decision trees with three or more alternative paths, and business logic where visual clarity of branching pathways is paramount for stakeholders and code reviewers.
3. State Machines: Event-Driven Lifecycle Architecture
A State Machine represents a system that exists in one of a finite number of discrete States at any given moment, transitioning between states in response to external events or internal conditions.
- Execution Mechanics: Each
Statecontains anEntryblock (executed upon entering the state), anExitblock (executed before leaving the state), and one or moreTransitions. Each transition defines aTrigger(optional event), aCondition(boolean guard), and anAction(logic executed during the state transfer). - Architectural Role: State Machines represent the architectural backbone of the enterprise UiPath Robotic Enterprise Framework (REFramework). They provide the industry-standard structure for robust, long-running transaction processing: initializing applications (
Init), fetching items (Get Transaction Data), executing transactions (Process Transaction), and closing applications (End Process).
Architectural Layout Comparison
| Dimension | Sequence | Flowchart | State Machine |
|---|---|---|---|
| Execution Model | Strict procedural (top-to-bottom) | 2D graph traversal (node-to-node) | Event/condition-driven state transitions |
| Runtime Overhead | Minimal (lowest overhead) | Moderate (graph node resolution) | Higher (state tracking & transition evaluation) |
| Branching Mechanism | Nested If / Switch activities | FlowDecision, FlowSwitch<T> | Transition conditions and triggers |
| Looping Flexibility | While, Do While, For Each | Native visual loops & cycles | Cyclic transitions between states |
| Ideal Scope | Atomic tasks, linear sub-workflows | Complex decision trees, process routing | Long-running transaction engines (REFramework) |
2. The Parallel Activity Architecture
The Parallel activity runs two or more branches concurrently. It helps most when branches spend their time waiting, for example on a service call or a UI element, so that the waits overlap.
+-------------------------------------------------------------------------------+
| PARALLEL CONTAINER |
| CompletionCondition: [ isServiceReady = True Or hasTimeoutElapsed = True ] |
| |
| +-----------------------+ +-----------------------+ +---------------------+ |
| | Branch 1: REST API | | Branch 2: Database | | Branch 3: Ping Mon | |
| | - Send HTTP Request | | - Execute Query | | - Delay 00:00:30 | |
| | - Parse JSON Data | | - Fill DataTable | | - Set Timeout Flag | |
| | - Set Flag = True | | - Set Flag = True | | | |
| +-----------------------+ +-----------------------+ +---------------------+ |
+-------------------------------------------------------------------------------+
Execution Mechanics: Concurrent, Not Multi-Threaded
UiPath workflows run on Windows Workflow Foundation, and its Parallel activity schedules every branch at the start on a single workflow thread:
- Interleaving on idle. Only one activity runs at a time. When an activity goes idle (for example, it waits on an asynchronous operation such as an HTTP call, a UI element to appear, or a Delay), the runtime moves on to the next scheduled activity in another branch.
- No idle, no interleaving. If none of the child activities ever goes idle, the Parallel activity behaves just like a Sequence, running the branches' activities one after another.
- Completion. Without a condition, the Parallel activity finishes when all branches have finished.
The CompletionCondition Property
The CompletionCondition is an optional Visual Basic or C# boolean expression defined at the container level of the Parallel activity.
- Evaluation Trigger: The runtime evaluates the
CompletionConditionexpression each time a branch completes. - Early Termination Mechanics: The instant the
CompletionConditionevaluates toTrue:- The workflow runtime immediately signals cancellation to all other currently running or scheduled branches.
- Running activities in non-completed branches receive a cancellation token and abort their remaining execution steps.
- Pending activities that have not yet started are removed from the execution queue.
- As soon as all active branches acknowledge cancellation and yield, the
Parallelcontainer terminates, and control passes directly to the next activity in the parent workflow.
- Enterprise Use Case: Racing redundant external services (e.g., querying two mirrored currency exchange APIs simultaneously and proceeding the moment either API responds), or implementing a strict operational timeout race where Branch 1 performs a heavy processing task while Branch 2 executes a
Delayactivity representing the maximum allowable SLA.
Shared State in Parallel Branches
Because branches interleave, their activities can run in an unpredictable order:
- Order-dependent logic breaks. If two branches read and update the same variable or append to the same DataTable, the final result depends on which activity happened to run first.
- Collections are shared objects. A
List(Of T)orDataTabletouched by several branches is one object, and DataTable is documented as safe only for concurrent reads. - Isolation pattern. Give each branch its own output variable (for example,
dt_ResultBranch1anddt_ResultBranch2), and merge the results in a single Sequence after the Parallel activity completes. - True parallelism. When independent work must really run at the same time, use separate jobs or robots, for example several performers on one queue, or an isolated invoked workflow in its own process.
3. Event-Driven Competitive Branching: Pick and PickBranch
While the Parallel activity executes all branches concurrently to completion, the Pick activity models a competitive, event-driven race between multiple alternatives where only one branch executes its payload.
+-------------------------------------------------------------------------------+
| PICK CONTAINER |
| |
| +-----------------------+ +-----------------------+ +---------------------+ |
| | PickBranch 1: Success | | PickBranch 2: Error | | PickBranch 3: Timer | |
| +-----------------------+ +-----------------------+ +---------------------+ |
| | TRIGGER: | | TRIGGER: | | TRIGGER: | |
| | Check App State: | | Check App State: | | Delay: | |
| | 'Dashboard Loaded' | | 'Access Denied Modal' | | 00:00:15 | |
| +-----------------------+ +-----------------------+ +---------------------+ |
| | ACTION: | | ACTION: | | ACTION: | |
| | - Extract Data Table | | - Log Security Alert | | - Throw Timeout | |
| | - Navigate to Orders | | - Send Admin Email | | Exception | |
| +-----------------------+ +-----------------------+ +---------------------+ |
+-------------------------------------------------------------------------------+
Anatomy of a PickBranch
A Pick container can host two or more PickBranch elements. Each PickBranch consists strictly of two distinct functional blocks:
Trigger: Holds one activity (which can be a Sequence) that waits for something to happen, such asCheck App Statewaiting for an element to appear, or aDelay. Avoid activities that finish immediately, such asElement Exists: they complete at once, returning True or False, so their branch wins the race every time.Action: Contains a sequence of one or more activities that execute only if this specific branch's trigger wins the race.
The Competition & Cancellation Lifecycle
The execution lifecycle of a Pick activity follows a strict competitive protocol:
- Simultaneous Trigger Initialization: Upon entering the
Pickcontainer, the workflow engine activates theTriggeractivity of every configuredPickBranchconcurrently. - The Event Race: All triggers listen asynchronously for their respective events or completion signals.
- Trigger Resolution & Branch Selection: The instant the first trigger activity successfully finishes its execution (e.g., an element appears on screen, a hotkey is pressed, or a delay timer lapses), that branch is declared the winner.
- Immediate Trigger Cancellation: The runtime immediately cancels and disposes of all competing triggers in all other branches.
- Action Execution: The runtime executes the
Actionsequence of the winningPickBranch. TheActionblocks of all losing branches are never executed. - Container Exit: Once the winning branch's
Actionsequence completes, thePickactivity terminates, and the workflow continues linearly.
Practical Enterprise Use Cases for Pick
- Dynamic Modal & Pop-up Handling: When logging into legacy client-server ERPs, the application might display the main dashboard, prompt a password expiration dialog, or display a system maintenance warning. Placing each check in a
PickBranchtrigger allows the robot to react dynamically to whichever screen appears first. - Human-in-the-Loop Hotkey Overrides: In attended automation, Branch 1's trigger listens for the user to press an emergency stop hotkey (
Ctrl + Alt + F12), while Branch 2 executes normal processing steps. - Resilient Action Timeouts: Pairing an asynchronous operation trigger in Branch 1 with a strict
Delayactivity trigger in Branch 2 ensures that an unresponsive UI control cannot cause an infinite robot hang.
4. Parallel For Each
The Parallel For Each activity schedules the body once for every item of a collection and lets the iterations interleave, following the same single-threaded rules as Parallel. It has its own CompletionCondition, which is checked after each iteration completes and cancels the remaining iterations when it becomes True.
Why Parallel UI Automation Goes Wrong
Placing UI activities (Click, Type Into, Select Item) in Parallel branches or in Parallel For Each is a classic source of errors:
- One foreground window. A Windows desktop session has a single active input focus. UI activities that wait for elements go idle, so the runtime interleaves them across branches, and one branch's keystrokes can land in the window another branch just activated.
- Unpredictable order. Interleaving means the sequence of clicks and keystrokes is no longer the one you designed.
- The rule. Keep interactive UI automation sequential. Use Parallel for independent waits, such as racing a timeout against an API call, and use more robots or jobs when you need throughput.
5. Architectural Comparison: Parallel vs. Parallel For Each vs. Pick
Choosing the proper concurrent control flow construct is essential for system stability, throughput, and predictability:
| Architectural Feature | Parallel | Parallel For Each | Pick |
|---|---|---|---|
| Core Paradigm | Concurrent multi-branch execution | Concurrent collection iteration | Competitive event-driven race |
| Number of Branches / Tasks | Fixed, statically defined in workflow | Dynamic, based on collection count | Fixed, statically defined in workflow |
| Execution Outcome | All branches execute to completion (unless condition met) | All collection items processed | Only ONE winning branch executes its Action |
| Early Termination | Supported via CompletionCondition | Supported via CompletionCondition | Automatic; first trigger win cancels all others |
| Concurrency Control | Branches interleave on one workflow thread when activities go idle | Iterations interleave the same way; CompletionCondition can stop early | Triggers wait together; only the winning Action runs |
| UI Automation Viability | Avoid for interactive foreground UI | Avoid for interactive foreground UI | Suited to waiting for competing UI states |
| Typical Enterprise Use Cases | Concurrent API calls, timeout racing, multi-service polling | High-volume API calls, batch PDF text parsing, bulk record validation | Dynamic application popups, attended hotkey interrupts, UI timeout races |
In a UiPath workflow, a Parallel activity contains three branches performing background REST API calls. The activity's CompletionCondition property is configured with the expression isDataRetrieved = True. What occurs at runtime the moment Branch 2 sets isDataRetrieved to True?
The Parallel activity immediately pauses Branch 2 and allows Branches 1 and 3 to finish before proceeding.
The runtime evaluates the CompletionCondition to True, initiates cancellation of the remaining active branches (Branch 1 and Branch 3), and exits the Parallel container once pending activities finalize.
An InvalidOperationException is thrown because shared variables cannot be evaluated inside a CompletionCondition.
Branches 1 and 3 continue executing in the background as orphaned background tasks while the main workflow advances.
How does the execution model of the Pick activity fundamentally differ from the Parallel activity in UiPath Studio?
Pick executes its branches sequentially in order of visual appearance, whereas Parallel executes all branches concurrently.
Pick requires all branch triggers to succeed before any action block can execute, whereas Parallel executes branches independently.
Parallel can only be used inside State Machines, whereas Pick can only be used inside Flowcharts.
Pick runs multiple event triggers concurrently in competition where only the first trigger to fire executes its corresponding Action block, whereas Parallel executes all branches concurrently to completion unless stopped by a condition.
An automation developer attempts to process a list of 500 invoices using a Parallel For Each activity. Inside the loop, the workflow executes Modern Click and Type Into activities using Hardware Events against an open desktop ERP client. What is the expected outcome in production?
The UI steps interleave unpredictably and fight over the single foreground window, causing missed keystrokes, clicks in the wrong window, and selector failures.
The robot automatically opens 500 isolated desktop sessions, one per invoice.
Studio refuses to compile the workflow because UI activities are not allowed in loops.
Execution becomes 500 times faster because each iteration runs on its own CPU core.
Sections you finish are checked off in the contents.