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

# Loop

> Iterate over arrays and process multiple items with the same logic.

<img src="https://mintcdn.com/langdock-34/SMXXZ0UbsQ3UbG3u/images/workflows/nodes/loop.jpg?fit=max&auto=format&n=SMXXZ0UbsQ3UbG3u&q=85&s=62a076715fcbb40838809f68a0ec6c2f" alt="Loop" width="1982" height="786" data-path="images/workflows/nodes/loop.jpg" />

## Overview

The Loop node processes arrays of data - iterate through lists of customers, orders, files, or any collection, applying the same logic to each item.

<Info>
  **Best for**: Batch processing, processing multiple records, generating
  individual reports, and iterating over lists.
</Info>

## Configuration

**Input Array**: Select the array to loop over

```handlebars theme={null}
{{ trigger.output.customers }}
{{ api_response.output.items }}
{{ google_sheets.output.rows }}
```

**Max Iterations**: Safety limit (default: 200, max: 2000)

### Advanced Options

**Concurrency**: Enable parallel processing of loop iterations

When enabled, all iterations run simultaneously instead of one after another. This significantly speeds up loops but requires that iterations don't depend on each other.

| Concurrency       | Behavior                                                           | Best For                                  |
| ----------------- | ------------------------------------------------------------------ | ----------------------------------------- |
| **Off** (default) | Sequential - each iteration waits for the previous one to complete | Dependent operations, rate-limited APIs   |
| **On**            | Parallel - all iterations run at the same time                     | Independent operations, faster processing |

<Warning>
  With concurrency enabled, iterations may complete in any order. Don't use concurrency if later iterations depend on results from earlier ones.
</Warning>

**Collect Outputs**: Gather all iteration results into a single array

When enabled, the loop end node outputs an array containing results from every iteration. This is useful for aggregating data processed in the loop.

```handlebars theme={null}
{{ loop_end.output.iterations }}            → Array of all iteration data
{{ loop_end.output.iterations[0].item }}    → First iteration's input item
{{ loop_end.output.iterations[0].executions }}  → Nodes executed in first iteration
{{ loop_end.output.total }}                 → Total number of iterations
```

**Collected Output Structure:**

```json theme={null}
{
  "iterations": [
    {
      "index": 0,
      "item": { "original": "data" },
      "executions": [
        {
          "nodeId": "abc123",
          "nodeSlug": "agent",
          "nodeType": "agent",
          "input": { ... },
          "output": { "result": "processed" }
        }
      ]
    }
  ],
  "total": 10
}
```

<Tip>
  Use **Collect Outputs** when you need to aggregate results, create reports from all iterations, or pass loop results to a downstream node for final processing.
</Tip>

## Inside the Loop

The loop node's slug becomes your variable name. Access the current item and iteration info:

```handlebars theme={null}
{{ customer.output.currentItem }}           // The full current item
{{ customer.output.currentItem.name }}      // Access item properties
{{ customer.output.currentItem.email }}
{{ customer.output.currentIndex }}          // Current iteration (0-based)
{{ customer.output.total }}                 // Total items in array
```

## Example Use Cases

### Process Customer List

```text theme={null}
Loop over {{ trigger.output.customers }}
  Loop node slug: customer

  → Agent: Analyze {{ customer.output.currentItem.feedback }}
  → Condition: Check {{ customer.output.currentItem.score }}
    → High: Send thank you email
    → Low: Create follow-up task
```

### Batch Update Records

```text theme={null}
Loop over {{ api_response.output.records }}
  Loop node slug: record

  → Code: Transform {{ record.output.currentItem.data }}
  → HTTP Request: Update record {{ record.output.currentItem.id }}
```

### Generate Individual Reports

```text theme={null}
Loop over {{ trigger.output.team_members }}
  Loop node slug: member

  → HTTP Request: Fetch {{ member.output.currentItem.id }} data
  → Agent: Generate report for {{ member.output.currentItem.name }}
  → Action: Email report to {{ member.output.currentItem.email }}
```

### Parallel Image Processing (Concurrency)

```text theme={null}
Loop over {{ trigger.output.images }}
  Loop node slug: image
  Parallel Execution: On

  → Agent: Analyze {{ image.output.currentItem.url }}
  → Code: Extract metadata
```

All images are analyzed simultaneously, completing much faster than sequential processing.

### Aggregate Results (Collect Outputs)

```text theme={null}
Loop over {{ trigger.output.documents }}
  Loop node slug: doc
  Collect Outputs: On

  → Agent: Summarize {{ doc.output.currentItem.content }}
  → Code: Extract key points

→ Agent: Create master summary from {{ loop_end.output.iterations }}
→ Action: Send combined report
```

The final Agent receives all summaries at once to create a comprehensive report.

## Best Practices

<AccordionGroup>
  <Accordion title="Always Set Max Iterations">
    Prevent infinite loops and runaway costs. Set a reasonable maximum.
  </Accordion>

  <Accordion title="Batch When Possible">
    Instead of 100 individual agent calls, batch items into groups of 10.
  </Accordion>

  <Accordion title="Handle Empty Arrays">
    Add a condition before the loop to check if array has items.
  </Accordion>

  <Accordion title="Monitor Costs">
    Loops with AI agents can be expensive. Calculate: cost per item × number of
    items.
  </Accordion>
</AccordionGroup>

## Cost Warning

<Warning>
  Loops can consume significant credits when processing many items with AI
  agents. A loop with 100 items and an agent call at $0.10 each = $10 per run.
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Agent Node" icon="brain" href="/en/using-langdock/workflows/nodes/agent-node">
    Process items with AI
  </Card>

  <Card title="Cost Management" icon="dollar-sign" href="/en/using-langdock/workflows/guides/cost-management">
    Optimize loop costs
  </Card>
</CardGroup>
