> ## Documentation Index
> Fetch the complete documentation index at: https://docs.noxus.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Subflows

> Build modular, reusable workflow components with subflows

Subflows enable you to break complex workflows into modular, reusable components. Think of them as "functions" that can be called from other workflows, promoting code reuse and cleaner workflow design.

## What are Subflows?

A **subflow** is a workflow that can be invoked from another workflow. It:

* Accepts inputs from the parent workflow
* Executes its own nodes independently
* Returns outputs back to the parent workflow
* Can be reused across multiple workflows

### Benefits

**Modularity**: Break complex workflows into manageable pieces

**Reusability**: Build once, use in many workflows

**Maintainability**: Update logic in one place, affects all usages

**Clarity**: Keep parent workflows clean and readable

**Testing**: Test components independently

**Collaboration**: Team members can own specific subflows

## Subflow Node Types

### Invoke Subflow Node (V2) - Recommended

The modern, recommended way to use subflows.

**Features**:

* Isolated execution context (own result pool)
* Proper error propagation
* Resume support (works with HITL)
* Nested subflows (unlimited depth)
* Progress mirroring to parent
* Efficient parallel execution

**Use Cases**:

* Production workflows
* Complex nested logic
* Human-in-the-loop workflows
* Workflows requiring resume capability

### Subflow Node (Legacy)

The older implementation, still supported for legacy workflows.

**Features**:

* Flattens subflow into parent graph
* Shared result pool
* Simpler execution model

**Limitations**:

* No isolation between parent and child
* Resume issues with HITL
* Harder to debug
* No nested subflow support

**Recommendation**: Use Invoke Subflow V2 for all new workflows.

## Creating a Subflow

### Step 1: Design the Subflow

Identify logic to extract:

* Repeated operations
* Complex multi-step processes
* Domain-specific logic
* Reusable components

**Example**: Customer data enrichment

```
Input: Customer email
Process: Lookup company, get industry, find contact info
Output: Enriched customer object
```

### Step 2: Create the Subflow Workflow

1. Create a new workflow
2. Add **Input Node** for each subflow input
3. Build the subflow logic
4. Add **Output Node** for each subflow output
5. Test the subflow independently

**Example Subflow: "Enrich Customer"**

```
Input Node (customer_email)
    ↓
API Request (lookup company by email domain)
    ↓
API Request (get company industry)
    ↓
API Request (get additional contacts)
    ↓
Compose Text (format enriched data)
    ↓
Output Node (enriched_data)
```

### Step 3: Use the Subflow

In your parent workflow:

1. Add **Invoke Subflow Node**
2. Select the subflow workflow
3. Map inputs to subflow input nodes
4. Connect subflow outputs to downstream nodes

## Input and Output Mapping

### Defining Subflow Inputs

Use **Input Nodes** in the subflow:

```
Input Node Configuration:
- Name: customer_email
- Type: Text
- Required: Yes
- Default: (optional, for testing)
```

Multiple inputs:

```
Input Node 1: customer_email
Input Node 2: company_name
Input Node 3: industry
```

### Defining Subflow Outputs

Use **Output Nodes** in the subflow:

```
Output Node Configuration:
- Name: enriched_customer
- Connected to: Final processing node
```

Multiple outputs:

```
Output Node 1: customer_data
Output Node 2: company_data
Output Node 3: confidence_score
```

### Mapping in Parent Workflow

When you add an Invoke Subflow Node:

**Inputs automatically appear** based on subflow Input nodes:

```
Invoke Subflow Node Inputs:
├─ customer_email (connect data source)
├─ company_name (connect data source)
└─ industry (connect data source or leave empty for optional)
```

**Outputs automatically appear** based on subflow Output nodes:

```
Invoke Subflow Node Outputs:
├─ enriched_customer (connect to downstream node)
├─ company_data (connect to downstream node)
└─ confidence_score (connect to downstream node)
```

## Execution Model

### Isolated Execution

Invoke Subflow V2 runs in an **isolated context**:

**Parent Workflow**:

```
Parent result pool: {node1: "A", node2: "B"}
```

**Subflow Execution**:

```
Subflow result pool: {subflow_node1: "X", subflow_node2: "Y"}
```

Subflow cannot access parent results directly, only through inputs.

### Shared TaskRunner

While result pools are isolated, subflows share the parent's TaskRunner:

* Efficient resource usage
* Parallel execution across parent and subflow
* Respects concurrency limits globally

### Progress Mirroring

Subflow progress updates reflect in the parent:

* Parent UI shows subflow execution
* Real-time status updates
* Error states propagated

## Common Patterns

### Pattern 1: Data Enrichment

**Subflow**: Enrich single record
**Parent**: Iterate over list

```
Parent Workflow:
List of Customers
    ↓
Invoke Subflow (Enrich Customer) - iterates per customer
    ↓
List of Enriched Customers
    ↓
Write to Database
```

### Pattern 2: Multi-Stage Processing

**Subflow 1**: Extract data
**Subflow 2**: Validate data
**Subflow 3**: Transform data
**Parent**: Orchestrate the pipeline

```
Parent Workflow:
Document Input
    ↓
Invoke Subflow (Extract Data)
    ↓
Invoke Subflow (Validate Data)
    ↓
Conditional (check validation result)
    ├─ Valid: Invoke Subflow (Transform Data)
    └─ Invalid: Send to review
    ↓
Output
```

### Pattern 3: Conditional Subflow Execution

**Subflows**: Different processing logic
**Parent**: Route to appropriate subflow

```
Parent Workflow:
Request Input
    ↓
Switch Node (check request type)
    ├─ Type A: Invoke Subflow (Process Type A)
    ├─ Type B: Invoke Subflow (Process Type B)
    └─ Type C: Invoke Subflow (Process Type C)
    ↓
Consolidate Outputs
```

### Pattern 4: Retry Logic

**Subflow**: Operation that might fail
**Parent**: Retry on failure

```
Parent Workflow:
Input
    ↓
Loop (max 3 iterations)
    ├─ Invoke Subflow (Risky Operation)
    ├─ Conditional (check success)
    │   ├─ Success: Exit loop
    │   └─ Failure: Continue loop
    └─ (retry with different parameters)
```

### Pattern 5: Parallel Processing

**Subflows**: Independent operations
**Parent**: Execute in parallel

```
Parent Workflow:
Input
    ├─ Invoke Subflow (Process A) ┐
    ├─ Invoke Subflow (Process B) ├─ Execute in parallel
    └─ Invoke Subflow (Process C) ┘
         ↓
    Gather Results
         ↓
    Output
```

## Nested Subflows

Invoke Subflow V2 supports unlimited nesting depth:

```
Main Workflow
    ↓
Invoke Subflow A
    ↓
Invoke Subflow B (inside Subflow A)
    ↓
Invoke Subflow C (inside Subflow B)
```

**Use Cases**:

* Complex hierarchical logic
* Deeply modular designs
* Recursive-like processing

**Considerations**:

* Each level adds execution overhead
* Debugging nested flows requires drilling down
* Keep nesting reasonable (3-4 levels max recommended)

## Error Handling

### Error Propagation

Errors in subflows propagate to the parent:

```
Subflow Node X fails
    ↓
Invoke Subflow Node marks itself as errored
    ↓
Parent workflow stops (unless continue-on-error enabled)
```

### Continue on Error

Configure Invoke Subflow Node with "continue on error":

* Subflow errors don't stop parent
* Outputs are empty/default values
* Check for success downstream with conditionals

```
Parent Workflow:
Input
    ↓
Invoke Subflow (continue on error: true)
    ↓
Conditional (check if output is empty)
    ├─ Success: Continue normal flow
    └─ Error: Handle error case
```

### Error Context

Errors include subflow context:

```
Error: Node "API Request" in subflow "Enrich Customer" failed
Reason: API rate limit exceeded
```

## Human-in-the-Loop with Subflows

Subflows can include HITL nodes:

```
Subflow:
Input
    ↓
Extract Data
    ↓
Human in the Loop (review and approve)
    ↓
Process Approved Data
    ↓
Output
```

**Parent Workflow**:

```
List of Items
    ↓
Invoke Subflow (with HITL) - iterates per item
    ↓
(workflow pauses for each HITL task)
    ↓
Continues after all reviews complete
```

**Key Feature**: Invoke Subflow V2 properly handles workflow pause/resume for HITL.

## Performance Considerations

### Overhead

Subflows add small execution overhead:

* Subflow lookup/initialization
* Input/output mapping
* State management

**Impact**: Negligible for most workflows (\<100ms)

**Optimization**: Don't overuse subflows for trivial operations (e.g., simple text concatenation)

### Parallel Execution

Subflows leverage parallel execution:

* Multiple subflow invocations run concurrently
* Independent nodes within subflow run in parallel
* Efficient use of worker resources

### List Iteration

When a list connects to a non-list subflow input:

* Subflow executes once per list item
* Items processed in parallel (up to concurrency limit)
* Results consolidated into list

```
List of 100 customers → Invoke Subflow → List of 100 enriched customers
(processes 10 at a time in parallel by default)
```

## Debugging Subflows

### Testing Independently

Test subflows standalone before using in parent:

1. Open subflow workflow
2. Provide test input values
3. Run and verify outputs
4. Fix issues before integrating

### Execution Logs

View subflow execution in run history:

* Drill down into subflow execution
* See all node results within subflow
* Identify where failures occurred

### Progress Tracking

Monitor subflow progress in real-time:

* Parent workflow shows subflow status
* Real-time updates as subflow executes
* Visual feedback on current subflow node

## Best Practices

### Design

**Single Responsibility**: Each subflow should do one thing well

**Clear Inputs/Outputs**: Descriptive names, clear types

**Self-Contained**: Subflows shouldn't rely on parent workflow context beyond inputs

**Reusability**: Design for reuse, not just extraction

### Naming

**Descriptive Names**: "Enrich Customer Data" not "Subflow 1"

**Verb-Based**: Use action verbs (Process, Validate, Transform, Enrich)

**Domain-Specific**: Reflect business logic (Approve Loan, Score Lead, Send Invoice)

### Organization

**Folder Structure**: Group related subflows in workspace folders

**Documentation**: Add descriptions to subflow workflows

**Versioning**: Consider naming conventions for versions (V1, V2) if making breaking changes

### Testing

**Unit Test Subflows**: Test each subflow independently

**Integration Test Parents**: Test full workflow with subflows

**Edge Cases**: Test with empty inputs, invalid data, errors

## Migration from Legacy Subflow Node

To migrate legacy subflows to Invoke Subflow V2:

1. **Identify Legacy Subflow Nodes**: Find workflows using old Subflow node
2. **Replace Node**: Swap with Invoke Subflow V2 node
3. **Remap Inputs/Outputs**: Connect same inputs/outputs
4. **Test Thoroughly**: Verify behavior matches
5. **Handle State Differences**: Isolated state may require adjustments

**Breaking Changes**:

* Subflow can't access parent result pool (pass data via inputs)
* Different error handling (proper propagation)
* HITL behavior improved (may need to adjust logic)

## Example: Customer Onboarding Subflow

### Subflow Workflow: "Onboard Customer"

**Inputs**:

* `customer_email`: Email address
* `company_name`: Company name
* `plan_tier`: Plan level (free, pro, enterprise)

**Logic**:

```
Input Nodes (customer_email, company_name, plan_tier)
    ↓
Conditional (check if email already exists)
    ├─ Exists: Return error
    └─ New: Continue
    ↓
API Request (create user account)
    ↓
API Request (create company)
    ↓
Conditional (check plan tier)
    ├─ Free: Skip provisioning
    ├─ Pro: Provision standard resources
    └─ Enterprise: Invoke Subflow (Enterprise Setup)
    ↓
Email Node (send welcome email)
    ↓
Slack Node (notify team)
    ↓
Output Nodes (customer_id, account_status, welcome_email_sent)
```

### Parent Workflow: "Bulk Customer Onboarding"

```
CSV Upload (customer list)
    ↓
CSV to List
    ↓
Invoke Subflow (Onboard Customer) - iterates per row
    ↓
Filter List (successful onboardings)
    ↓
Generate Report (summary of onboarded customers)
    ↓
Email Report to Admin
```

## Example: Multi-Stage Document Processing

### Subflow 1: "Extract Document Metadata"

**Inputs**: `document_file`
**Outputs**: `title`, `author`, `date`, `page_count`

### Subflow 2: "Classify Document"

**Inputs**: `document_text`, `metadata`
**Outputs**: `category`, `tags`, `confidence`

### Subflow 3: "Index Document"

**Inputs**: `document_file`, `metadata`, `category`
**Outputs**: `kb_document_id`, `indexed_at`

### Parent Workflow: "Document Processing Pipeline"

```
Document Upload
    ↓
Invoke Subflow (Extract Metadata)
    ↓
File to Text
    ↓
Invoke Subflow (Classify Document)
    ↓
Conditional (confidence > 80%)
    ├─ High Confidence: Invoke Subflow (Index Document)
    └─ Low Confidence: Human Review → Manual Classification → Invoke Subflow (Index Document)
    ↓
Notification (document processed)
```

## Next Steps

> **[Conditionals](https://docs.noxus.ai/building/logic/conditionals)**
>
> Control flow with conditional branching

> **[Loops](https://docs.noxus.ai/building/logic/loops)**
>
> Iterate with loop nodes

> **[Error Handling](https://docs.noxus.ai/building/logic/error-handling)**
>
> Handle errors and failures gracefully

> **[List Handling](https://docs.noxus.ai/building/fundamentals/list-handling)**
>
> Understand automatic list iteration

***

Subflows are essential for building maintainable, scalable workflows. Master them to create modular, reusable automation components.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.