This prompt is designed for agent developers who need to parallelize a single logical task across multiple asynchronous tool calls and then aggregate the results. The core job-to-be-done is transforming a high-level objective into a structured dispatch plan that your application harness can execute concurrently. Use it when a task can be partitioned into independent shards, such as querying multiple databases with different parameters, calling several APIs to gather data for a comparison, or processing chunks of a large document in parallel to extract entities. The prompt instructs the model to generate a list of tool invocations, interpret the partial results as they return, handle individual shard failures gracefully, and produce a single consolidated output that answers the original objective.
Prompt
Async Tool Call Fan-Out and Scatter-Gather Prompt Template

When to Use This Prompt
Defines the ideal use case, required infrastructure, and clear boundaries for applying the async fan-out and scatter-gather prompt.
This playbook assumes you have an application harness that can receive the model's structured dispatch plan, execute the specified tool calls asynchronously, and return their results to the model's context for the gather step. The prompt is not a standalone magic function; it is a contract between the model's reasoning and your execution layer. You must provide the model with a precise list of available tools, their schemas, and any constraints like rate limits or timeouts. The model will then output a machine-readable plan, typically a JSON array of tool call definitions. Your harness parses this plan, fans out the calls, collects the responses, and feeds them back into the model with the original prompt for final aggregation. This separation of planning and execution is critical for reliability and testability.
Do not use this prompt for strictly sequential tool chains where each step depends on the previous output, as the fan-out pattern introduces non-deterministic ordering that will break dependency chains. It is also unsuitable for real-time streaming scenarios where incremental partial results must be surfaced to a user immediately, because the gather step requires all shards to complete before consolidation. Avoid this pattern when the cost of an unnecessary fan-out (e.g., spinning up 100 parallel calls for a task that could be done with 2) outweighs the latency benefit, or when the tools have side effects that cannot be safely parallelized. For high-risk operations, ensure your harness includes a human approval gate before executing the fan-out plan, especially when the tool calls involve destructive actions or access regulated data.
Use Case Fit
Where the Async Tool Call Fan-Out and Scatter-Gather pattern works and where it introduces more risk than value.
Good Fit: Embarrassingly Parallel Workloads
Use when: tasks are independent, share no mutable state, and can be executed concurrently without ordering constraints. Examples include parallel API calls for multi-source research, batch document processing, or simultaneous data enrichment across isolated records. Guardrail: validate that each shard's output schema is identical before aggregation to prevent merge failures.
Bad Fit: Sequential Dependencies
Avoid when: the output of one tool call is a required input for another. Fan-out patterns applied to sequential workflows create race conditions, deadlocks, and incorrect ordering. Guardrail: use a dependency graph to classify tasks as parallel or sequential before dispatch. If a task has upstream dependencies, it belongs in a sequential orchestration prompt, not a scatter-gather.
Required Inputs
Must have: a list of discrete sub-tasks with clear input payloads, a defined output schema per shard, a correlation ID for result matching, and a timeout threshold per async call. Guardrail: reject the fan-out if any sub-task is missing its input payload or schema contract. Dispatch with incomplete inputs produces silent partial failures that are hard to debug post-aggregation.
Operational Risk: Straggler Tasks
Risk: one slow shard blocks the entire gather phase, causing timeout cascades and stale partial results. This is the most common production failure in scatter-gather systems. Guardrail: implement a per-shard timeout with a degradation strategy—either proceed with partial results and flag missing shards, or escalate after a configurable deadline. Never let the gather phase wait indefinitely.
Operational Risk: Result Consistency
Risk: shards return results with conflicting facts, timestamps, or schema versions, making aggregation unreliable. Guardrail: include a consistency check in the reduce step that compares key fields across shards. When conflicts are detected, either apply a deterministic resolution rule (latest timestamp wins, majority vote) or escalate for human review rather than silently merging inconsistent data.
Operational Risk: Resource Exhaustion
Risk: unconstrained fan-out saturates API rate limits, exhausts connection pools, or triggers downstream throttling. Guardrail: enforce a maximum concurrency limit and a total shard count cap in the dispatch logic. Use a semaphore or token-bucket pattern to control parallelism, and surface rate-limit responses as partial-failure events rather than retrying blindly.
Copy-Ready Prompt Template
A copy-ready system prompt for an agent that fans out work across multiple async tool calls and gathers results with partial-failure tolerance.
This template gives an agent explicit instructions for dispatching parallel async tool calls, tracking in-flight requests, detecting completion, handling partial failures, and reducing results into a coherent final output. It is designed for agent developers who need reliable scatter-gather behavior when tools have variable latency and independent failure modes. Replace the square-bracket placeholders with your specific tool definitions, output schema, and operational constraints before use.
textYou are an async tool-call orchestrator. Your job is to fan out work across multiple independent tool calls, track their completion, handle partial failures, and reduce results into a single structured output. ## TOOLS AVAILABLE [TOOLS] ## FAN-OUT RULES 1. When given a task that can be parallelized, identify all independent work units. 2. Dispatch all tool calls simultaneously. Do not serialize independent calls. 3. For each dispatched call, record a correlation ID and the expected result shape. 4. If a tool requires input from another tool's output, sequence those calls explicitly and note the dependency. ## GATHER RULES 1. Track completion status for every dispatched call: `pending`, `completed`, `failed`, `timed_out`. 2. Do not proceed to final output until ALL calls have reached a terminal state OR the [GATHER_TIMEOUT] threshold is reached. 3. For calls that fail or time out, classify the failure: - `recoverable`: retry with backoff up to [MAX_RETRIES] times. - `non_recoverable`: mark as failed and continue with partial results. - `degraded`: accept partial or stale result if available. 4. If more than [CRITICAL_FAILURE_THRESHOLD] of calls fail, abort the gather and report the failure state. ## RESULT REDUCTION RULES 1. Merge successful results according to the output schema. 2. For failed calls, include a `partial_failures` block in the output with: - `call_id` - `failure_reason` - `impact_on_result`: what is missing or degraded 3. If a result conflicts with another result, apply the conflict resolution strategy: [CONFLICT_STRATEGY]. 4. Do not fabricate data for failed or missing calls. ## OUTPUT SCHEMA Your final output must conform to this schema: [OUTPUT_SCHEMA] ## CONSTRAINTS - Maximum concurrent tool calls: [MAX_CONCURRENCY] - Gather timeout: [GATHER_TIMEOUT] seconds - Max retries per call: [MAX_RETRIES] - Critical failure threshold: [CRITICAL_FAILURE_THRESHOLD] - Idempotency: generate and attach idempotency keys for all mutating calls ## BEFORE FINALIZING 1. Verify all terminal states are accounted for. 2. Confirm no fabricated data in partial-failure slots. 3. Validate output against the schema. 4. If [HUMAN_REVIEW_REQUIRED] is true for any failure class, pause and request review before returning the final output.
To adapt this template, start by defining your tool set in the [TOOLS] block with clear schemas, argument descriptions, and failure modes. Set [GATHER_TIMEOUT] based on your p99 tool latency plus buffer. Choose [CONFLICT_STRATEGY] from options like last-write-wins, majority-vote, manual-resolution, or fail-on-conflict. For high-risk workflows such as financial transactions or clinical data, set [HUMAN_REVIEW_REQUIRED] to true for any non-recoverable failure class. Wire the output into a validation layer that checks schema compliance and flags missing required fields before the result reaches downstream consumers.
Prompt Variables
Required inputs for the Async Tool Call Fan-Out and Scatter-Gather prompt. Each placeholder must be populated by the application harness before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_CALL_SPECS] | Array of tool definitions to fan out, each with tool_name, arguments, and optional timeout_ms | [{"tool_name": "search_inventory", "arguments": {"sku": "SKU-123"}, "timeout_ms": 5000}] | Schema check: array of objects with required tool_name string, arguments object, optional timeout_ms integer. Reject if empty array or missing tool_name. |
[FAN_OUT_STRATEGY] | Strategy for dispatching calls: parallel, batched, or dependency-ordered | parallel | Enum check: must be one of parallel, batched, dependency_ordered. Default to parallel if null. Reject unknown values. |
[MAX_CONCURRENCY] | Maximum number of in-flight tool calls allowed simultaneously | 8 | Type check: positive integer. Null allowed if FAN_OUT_STRATEGY is parallel (unbounded). Reject values below 1 or above system limit. |
[GATHER_STRATEGY] | How to aggregate results: all_success, any_success, majority, or custom_reduce | all_success | Enum check: must be one of all_success, any_success, majority, custom_reduce. Reject unknown values. If custom_reduce, [REDUCE_FUNCTION] must be provided. |
[REDUCE_FUNCTION] | Custom aggregation logic applied to collected results when GATHER_STRATEGY is custom_reduce | concatenate field 'summary' from each result, skip nulls | Required if GATHER_STRATEGY is custom_reduce. Must be a parseable instruction string. Null allowed otherwise. Validate that instruction references valid result fields. |
[PARTIAL_FAILURE_POLICY] | Behavior when some tool calls fail: fail_fast, collect_all, or threshold_pct | collect_all | Enum check: must be one of fail_fast, collect_all, threshold_pct. If threshold_pct, [FAILURE_THRESHOLD_PCT] must be provided. Reject unknown values. |
[FAILURE_THRESHOLD_PCT] | Percentage of failed calls that triggers overall failure when PARTIAL_FAILURE_POLICY is threshold_pct | 30 | Required if PARTIAL_FAILURE_POLICY is threshold_pct. Type check: integer 0-100. Null allowed otherwise. Reject values outside 0-100 range. |
[OUTPUT_SCHEMA] | Expected structure for the final aggregated result | {"status": "string", "results": "array", "errors": "array", "completion_pct": "number"} | Schema check: valid JSON Schema or example shape. Must include fields for status, results, errors, and completion metadata. Reject if missing error-reporting fields. |
Implementation Harness Notes
How to wire the async fan-out and scatter-gather prompt into a production application with validation, retries, and observability.
This prompt template is designed to sit at the orchestration layer of an agent application, not as a standalone chat interaction. The application is responsible for providing the list of available async tools, their schemas, the user's objective, and any constraints. The model's output is a structured dispatch plan that the application must parse, validate, and execute. The prompt does not make the tool calls itself; it produces the instructions for the application's execution engine to fan out work, collect results, and decide on a gather strategy. The application must treat the model's output as a plan to be verified, not as executable code to be run blindly.
The implementation harness requires several components working together. First, a schema validator must confirm the model's output matches the expected JSON structure, including the fan_out array of tool call specifications, the gather_strategy object, and the failure_policy block. Each tool call in the fan-out must reference a tool that exists in the application's tool registry, with arguments that conform to that tool's input schema. Second, a dispatch executor must issue the async calls with generated correlation IDs, respecting any concurrency limits and rate limits defined in the application configuration. Third, a result collector must track in-flight calls, handle partial completions, and detect stragglers using configurable timeouts. Fourth, a reduce function must apply the gather strategy—whether it's a simple concatenation, a voting mechanism, a merge with conflict resolution, or a weighted aggregation—to produce the final aggregated result. Each of these components should emit structured logs with trace IDs for observability.
For production reliability, implement a straggler timeout per fan-out batch. If any tool call exceeds the timeout, the gather strategy must proceed with partial results, and the application must log the missing shard with its correlation ID for later reconciliation. Add a result freshness check that compares the completion timestamp of each result against a configurable staleness threshold; stale results should be discarded or flagged. For high-risk domains, insert a human review gate before the final aggregated output is returned to the user or downstream system, especially when the gather strategy involves conflict resolution or when partial failures occurred. The review gate should present the original objective, the individual tool results, the proposed aggregation, and any failure flags. Do not rely on the model to self-report errors; the application harness must independently verify output completeness and consistency.
When wiring this into an existing agent framework, avoid the temptation to let the agent loop freely on fan-out decisions. Instead, treat the prompt as a single-turn planning step: the model produces the dispatch plan, the application executes it, and a separate reduce step produces the final output. If the gather step detects irreconcilable conflicts or missing critical shards, the application can re-invoke the prompt with the partial results and a specific request for conflict resolution, but this should be a deliberate retry with a bounded loop, not an open-ended agent cycle. Log every dispatch, every result, every timeout, and every reduce decision so that production failures can be traced to a specific shard or gather logic error rather than requiring a full replay of the agent's reasoning.
Expected Output Contract
Defines the structure, types, and validation rules for the scatter-gather agent's final aggregated response. Use this contract to parse, validate, and route the model's output before it enters downstream systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
fan_out_summary | object | Must contain dispatched_count, completed_count, failed_count, and pending_count as integers. dispatched_count must equal the sum of completed, failed, and pending. | |
fan_out_summary.dispatched_count | integer | Must be greater than 0 and match the number of [TOOL_CALLS] dispatched. Parse check: non-negative integer. | |
fan_out_summary.completed_count | integer | Must be less than or equal to dispatched_count. Parse check: non-negative integer. | |
fan_out_summary.failed_count | integer | Must be less than or equal to dispatched_count. Parse check: non-negative integer. | |
fan_out_summary.pending_count | integer | Must equal dispatched_count - (completed_count + failed_count). If greater than 0, the response is incomplete and requires a retry or timeout escalation. | |
results | array | Each element must contain tool_call_id, status, result, and error fields. Array length must equal dispatched_count. Schema check: validate each element against the result_item schema. | |
results[].tool_call_id | string | Must match a tool_call_id from the original [TOOL_CALLS] dispatch list. Citation check: no orphan or fabricated IDs allowed. | |
results[].status | string (enum) | Must be one of: completed, failed, timed_out, cancelled. Enum check: reject any other value. If status is not completed, the error field must be non-null. | |
results[].result | object | null | Required when status is completed. Must conform to the expected output schema for that specific tool call. Schema check: validate against the tool's declared output contract. Null allowed only when status is not completed. | |
results[].error | object | null | Required when status is failed, timed_out, or cancelled. Must contain code (string) and message (string). Null allowed only when status is completed. Schema check: code must be a non-empty string. | |
reduce_result | object | string | The aggregated output from the reduce step. If [REDUCE_STRATEGY] is merge, must be a single merged object. If [REDUCE_STRATEGY] is summary, must be a string. Schema check: validate against the declared reduce output schema. | |
reduce_method | string (enum) | Must match the [REDUCE_STRATEGY] provided in the prompt. Enum check: must be one of merge, summary, vote, rank, or custom. Reject if the method does not match the expected strategy. | |
straggler_handling | object | Must contain timeout_threshold_ms (integer), stragglers_present (boolean), and action_taken (string enum: waited, ignored, escalated). If stragglers_present is true, pending_count must be greater than 0. | |
partial_failure_handling | object | Must contain failures_detected (boolean) and policy_applied (string enum: fail_fast, partial_results, retry_and_merge, escalate). If failures_detected is true, failed_count must be greater than 0. Approval required if policy_applied is escalate. | |
confidence_score | number (0.0-1.0) | Overall confidence in the aggregated result. Must be between 0.0 and 1.0. If below [CONFIDENCE_THRESHOLD], the response should trigger human review. Range check: 0.0 <= score <= 1.0. |
Common Failure Modes
Fan-out patterns multiply throughput but also multiply failure surfaces. These are the most common production failure modes when scattering async tool calls and gathering results.
Straggler Shard Blocks Aggregation
What to watch: A single slow shard (straggler) holds up the entire gather step, causing timeouts upstream. This is the most common fan-out failure in production. Guardrail: Implement a gather deadline with partial-result acceptance. Define a max_wait_ms per batch and a min_completion_ratio (e.g., 0.8) that allows proceeding with incomplete results while logging missing shards for async backfill.
Silent Partial Failure Masking
What to watch: Some shards fail with errors, but the aggregation logic treats missing results as empty or zero, producing a plausible but incorrect final output. Guardrail: Require explicit failure signaling per shard. Each shard result must include a status field (success, error, timeout). The reduce step must count failures and refuse to produce a final result if the failure ratio exceeds a configured threshold.
Result Inconsistency Across Shards
What to watch: Different shards return structurally incompatible results (schema drift, conflicting facts, different units) that cannot be safely merged. Guardrail: Enforce a strict per-shard output schema with a schema_version field. Run a pre-merge consistency check that validates schema compatibility across all completed shards before aggregation. Reject the batch if schema mismatch is detected.
Correlation ID Collision or Loss
What to watch: Async results arrive without a reliable way to match them to originating fan-out requests, causing orphaned results or incorrect aggregation. Guardrail: Generate a unique, non-colliding correlation_id per shard at dispatch time (UUIDv7 preferred for time-sortable properties). Validate that every incoming result carries a matching correlation_id and reject unmatched results with a logged warning.
Retry Storm on Transient Failures
What to watch: A downstream tool returns transient errors (429, 503), and the fan-out dispatcher retries all failed shards simultaneously, amplifying load and causing a cascading outage. Guardrail: Implement per-shard exponential backoff with jitter. Cap total concurrent retries across the fan-out batch. Use a circuit breaker that halts all retries for a tool if the error rate crosses a threshold within a short window.
Stale Result Incorporation
What to watch: A shard's async result arrives after the gather deadline but is later picked up by a retry or reconciliation loop and merged into an already-finalized output, corrupting downstream state. Guardrail: Attach a dispatched_at timestamp to each shard request and a gather_deadline to the batch. The reduce step must discard any result where completed_at > gather_deadline. Log discarded late results for observability.
Evaluation Rubric
Use this rubric to evaluate the quality of fan-out dispatch, gather-completion, and result-reduce logic before shipping the Async Tool Call Fan-Out and Scatter-Gather prompt template to production.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Fan-Out Dispatch Completeness | All [TOOL_CALLS] in the input array are dispatched exactly once with correct arguments and unique correlation IDs. | Missing dispatch for one or more calls; duplicate correlation IDs; argument mismatch between input and dispatched call. | Run with a known set of 10 tool calls. Verify dispatch log contains exactly 10 entries with unique IDs and matching arguments. |
Gather Completion Detection | Prompt correctly identifies when all dispatched calls have returned (success or failure) and triggers the reduce step without premature finalization. | Reduce step triggers before all results arrive; prompt waits indefinitely for a call that already failed; straggler timeout is ignored. | Simulate 8 calls where 2 return late. Verify reduce step waits for timeout or all results. Check that timeout does not exceed [MAX_WAIT_MS]. |
Partial Failure Handling | Failed tool calls are isolated, their errors are summarized, and successful results are preserved. The reduce step proceeds with partial data. | A single failure causes the entire gather to abort; error from one shard contaminates successful results; failure is silently ignored. | Inject 2 failures in a batch of 8. Verify output contains 6 successful results, 2 error summaries, and no null fields in the success payload. |
Result Consistency Across Shards | Results from different shards are normalized to a common schema before aggregation. Type mismatches are flagged, not silently coerced. | String and numeric fields are concatenated without warning; date formats differ across shards; enum values are inconsistent. | Dispatch calls that return different date formats (ISO 8601 vs Unix timestamp). Verify output normalizes to [OUTPUT_DATE_FORMAT] or flags the mismatch. |
Straggler Timeout Behavior | Calls exceeding [MAX_WAIT_MS] are marked as timed out, their partial results (if any) are discarded or flagged, and the reduce step proceeds. | Straggler blocks the entire gather indefinitely; timeout is ignored; timed-out result is treated as a successful completion. | Set [MAX_WAIT_MS] to 2000ms. Dispatch a call that responds in 5000ms. Verify it is marked as timed out and does not block the reduce step. |
Correlation ID Uniqueness and Traceability | Every dispatched call and its result are linked by a unique, non-colliding correlation ID present in both request and response logs. | Duplicate IDs cause result misattribution; missing ID in response prevents matching; ID format violates [CORRELATION_ID_PATTERN]. | Dispatch 100 concurrent calls. Verify all 100 correlation IDs are unique, match the pattern, and appear in both dispatch and result logs. |
Reduce Output Schema Compliance | The final aggregated output matches [OUTPUT_SCHEMA] exactly, with all required fields present and no extra fields. | Missing required fields; extra fields not in schema; array instead of object where schema expects object; null where schema forbids null. | Validate the reduce output against [OUTPUT_SCHEMA] using a JSON Schema validator. Require 100% compliance across 20 test runs with varied inputs. |
Idempotency Under Retry | Re-running the same fan-out with identical [TOOL_CALLS] and [IDEMPOTENCY_KEY] does not dispatch duplicate calls or double-count results. | Retry dispatches duplicate calls; results are double-counted in aggregation; idempotency key is ignored. | Run the same fan-out twice with the same idempotency key. Verify dispatch count equals the number of unique tool calls, not 2x. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with a single-model, single-tool fan-out. Replace the production dispatch logic with a flat list of tool calls and a simple gather loop. Use [TOOL_NAME] and [SHARD_KEY] placeholders directly in the prompt instead of generating them from a registry. Skip partial-failure handling; treat any failure as a full retry.
codeFan out [NUM_SHARDS] parallel calls to [TOOL_NAME] using [SHARD_KEY] ranges: [SHARD_RANGES]. Gather all results. If any call fails, retry the entire batch once. Return the merged result as [OUTPUT_SCHEMA].
Watch for
- Missing schema checks on gathered results
- Overly broad shard ranges causing duplicate work
- No timeout handling, leading to hung prototypes

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us