Inferensys

Prompt

Parallel Fetch and Merge Prompt for Multiple Data Sources

A practical prompt playbook for full-stack AI engineers aggregating results from independent APIs or databases. Produces a parallel execution plan with merge strategy, conflict resolution rules, and result normalization schema. Includes handling for partial failures and timeout coordination.
Cinematic overhead of a WeWork creative suite room with multiple curved monitors showing AI decision dashboards, executives in casual attire reviewing data, dramatic pendant lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal scenario, required context, and boundaries for using the parallel fetch and merge prompt in an agent orchestration layer.

This prompt is designed for full-stack AI engineers building agent or copilot systems that must aggregate data from multiple independent sources concurrently. The job-to-be-done is generating a structured execution plan before any tool calls are dispatched. Use it when your system has a defined set of tools—such as API wrappers, database connectors, or internal service clients—that do not depend on each other's outputs, and you need the model to produce a plan specifying which tools to call in parallel, how to merge their results, and how to handle partial failures. This prompt belongs in the orchestration layer, acting as a planner that outputs a machine-readable execution graph, not as a runtime executor that makes the calls itself.

The ideal user has already defined their tool schemas and needs the model to reason about concurrency, conflict resolution, and result normalization. Required context includes the full list of available tools with their input schemas, the user's original request, and any operational constraints such as timeout budgets or rate limits. The prompt is not suitable when tool calls have sequential dependencies—use a dependency graph construction prompt instead. It is also not appropriate for simple single-tool lookups, where the overhead of planning adds latency without benefit. Do not use this prompt after results have already arrived; it is a pre-execution planning step. If the user's request is ambiguous about which data sources to query, resolve that ambiguity with a clarification prompt before invoking this planning step.

Before wiring this into production, ensure you have a validation layer that checks the output plan for correctness: verify that all specified tools exist, that parallel groups contain only independent calls, and that the merge strategy handles schema mismatches explicitly. Common failure modes include the model hallucinating tool names, proposing parallel calls that actually share hidden state, or producing merge logic that silently drops conflicting fields. Start by testing with two or three known-independent data sources, then scale to broader tool sets. If any tool in the plan performs writes or state mutations, route through a human approval gate or a side-effect isolation prompt instead of executing directly from this plan.

PRACTICAL GUARDRAILS

Use Case Fit

Where the parallel fetch and merge prompt works, where it breaks, and what inputs and operational conditions are required before wiring it into a production agent.

01

Good Fit: Independent Data Sources

Use when: the target APIs, databases, or endpoints do not depend on each other's output. Each call can be constructed from the initial user input alone. Guardrail: validate independence by checking that no tool's input schema references another tool's output field before marking it parallel-safe.

02

Bad Fit: Hidden Write Dependencies

Avoid when: one data source must be queried to obtain an ID, token, or filter value required by another. Risk: the model may still attempt parallel calls, causing one to fail with a missing argument. Guardrail: use a dependency annotation preflight to detect required-output-of relationships before execution planning.

03

Required Input: Normalized Merge Schema

Risk: without a defined output schema, the model merges results inconsistently, drops fields, or invents keys. Guardrail: provide an explicit [OUTPUT_SCHEMA] with field names, types, nullability rules, and a conflict resolution strategy (e.g., 'prefer source A for field X'). Validate merged output against this schema before returning to the user.

04

Operational Risk: Partial Failure Cascades

Risk: one parallel call times out or returns an error, and the merge step either discards all results or hallucinates missing data. Guardrail: define a [PARTIAL_FAILURE_POLICY] that specifies which results to keep, which to discard, and how to annotate missing data in the final output. Never let the model invent data to fill gaps.

05

Operational Risk: Timeout Coordination

Risk: parallel calls have different latency profiles, and the merge step proceeds before all results arrive or waits too long for a straggler. Guardrail: set an explicit [TIMEOUT_BUDGET] per call group and a [RESULT_COMPLETENESS_THRESHOLD] (e.g., 'proceed with 80% of results after 3 seconds'). Log which sources were included or excluded.

06

Bad Fit: Rate-Limited or Costly APIs

Avoid when: fanning out to many parallel calls would exceed rate limits, incur high costs, or trigger throttling. Risk: the model optimistically parallelizes and the system hits a 429 or budget cap mid-execution. Guardrail: pass [RATE_LIMIT_HEADROOM] and [COST_BUDGET] as constraints in the prompt so the model can reduce fan-out or sequence calls when limits are tight.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that generates a parallel execution plan for fetching data from multiple independent sources and merging the results.

This prompt template instructs the model to act as an execution planner. It takes a list of independent data sources, a merge strategy, and operational constraints, then produces a structured execution plan. The plan includes parallel fetch groups, a merge specification, conflict resolution rules, and a normalized output schema. Use this as the core instruction set for an agent or orchestration service that must reliably aggregate data from APIs, databases, or internal services without sequential bottlenecks.

code
You are an execution planner for a data aggregation system. Your job is to produce a parallel execution plan for fetching data from multiple independent sources and merging the results into a single, consistent output.

## INPUT
- Data Sources: [DATA_SOURCES]
- Merge Strategy: [MERGE_STRATEGY]
- Output Schema: [OUTPUT_SCHEMA]
- Operational Constraints: [CONSTRAINTS]

## INSTRUCTIONS
1. Analyze the list of data sources. Identify which sources are completely independent of each other and can be fetched in parallel.
2. Group independent sources into parallel fetch groups. Each group can execute concurrently.
3. For each group, define:
   - The source identifier
   - The expected data shape
   - A timeout budget in milliseconds
   - A retry policy (max attempts, backoff strategy)
4. Define the merge specification:
   - The primary key or entity used to join results
   - The strategy for combining fields (e.g., first-write-wins, last-write-wins, union, custom logic)
   - Explicit conflict resolution rules for overlapping or contradictory data
5. Define the result normalization schema. Map raw source fields to the final [OUTPUT_SCHEMA] fields.
6. Define partial failure handling:
   - The minimum number of sources that must succeed for the plan to return a partial result
   - The fallback value or behavior for each field when a source fails or times out
   - The structure of the error report included in the final output
7. Output the complete execution plan as a valid JSON object matching the ExecutionPlan schema below.

## EXECUTION PLAN SCHEMA
{
  "plan_id": "string",
  "parallel_groups": [
    {
      "group_id": "string",
      "sources": [
        {
          "source_id": "string",
          "endpoint": "string",
          "timeout_ms": "number",
          "retry_policy": {
            "max_attempts": "number",
            "backoff": "string"
          },
          "expected_schema": {}
        }
      ]
    }
  ],
  "merge_spec": {
    "join_key": "string",
    "strategy": "string",
    "conflict_rules": [
      {
        "field": "string",
        "resolution": "string",
        "priority_source": "string"
      }
    ]
  },
  "normalization_map": [
    {
      "target_field": "string",
      "source_field": "string",
      "source_id": "string",
      "transform": "string"
    }
  ],
  "failure_handling": {
    "min_successful_sources": "number",
    "field_fallbacks": {},
    "error_report_schema": {}
  }
}

## CONSTRAINTS
- Do not create sequential dependencies where none exist.
- If a merge conflict cannot be resolved automatically, flag it for human review in the plan.
- All timeout values must respect the global deadline in [CONSTRAINTS].
- The plan must be valid JSON. Do not include comments or markdown fences in the output.

To adapt this template, replace the placeholders with concrete values. [DATA_SOURCES] should be a structured list of available sources, each with an identifier, endpoint, and known schema. [MERGE_STRATEGY] defines the business rule for combining records (e.g., "prioritize the CRM source for contact fields, but use the billing system for financial fields"). [OUTPUT_SCHEMA] is the target schema your application expects. [CONSTRAINTS] should include a global deadline, rate limits, and any required human-review triggers. After generating the plan, validate it programmatically: check for cycles in dependencies, ensure all target fields in the output schema have a mapped source, and confirm that timeout budgets sum to less than the global deadline. For high-stakes data (financial, clinical, legal), route the generated plan through a human approval step before execution.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Parallel Fetch and Merge prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[DATA_SOURCES]

List of independent data sources to query in parallel, each with an identifier, endpoint, and authentication reference

source:customer-db, type:postgres, query:SELECT * FROM users WHERE id=123; source:orders-api, type:rest, endpoint:/orders?user_id=123

Must be a valid JSON array of source objects. Each source requires id, type, and connection fields. Reject if any source is missing required fields or contains duplicate ids.

[MERGE_STRATEGY]

Rule for combining results when multiple sources return data for the same entity or key

strategy:latest-wins, timestamp_field:updated_at, conflict_keys:[user_id, email]

Must be one of: latest-wins, source-priority, union, intersection, manual-review. If source-priority, a priority_ordering array is required. Reject unrecognized strategies.

[OUTPUT_SCHEMA]

Target schema for the merged result set, defining fields, types, and normalization rules

fields:[{name:user_id, type:string, required:true}, {name:email, type:string, normalize:lowercase}]

Must be a valid JSON schema array. Each field requires name and type. Optional normalize, default, and required flags. Reject if field names collide after normalization.

[TIMEOUT_MS]

Maximum wait time in milliseconds for each parallel fetch before treating it as a partial failure

5000

Must be a positive integer between 100 and 30000. Values outside this range should be clamped with a warning. Null allowed if no timeout is desired, but not recommended for production.

[CONFLICT_RESOLUTION]

Rule for handling contradictory values from different sources for the same field

field:status, rule:source-priority, priority:[orders-api, customer-db]; field:address, rule:manual-review

Must be a valid JSON array of per-field rules. Each rule requires field and rule type. Supported rules: source-priority, latest-wins, manual-review, keep-all. Reject unknown rule types.

[PARTIAL_FAILURE_POLICY]

Instruction for handling sources that timeout, error, or return empty results

policy:include-with-flag, flag_field:_fetch_status, continue_on:timeout, abort_on:auth_error

Must be one of: abort-all, omit-failed, include-with-flag, partial-ok. If include-with-flag, flag_field is required. Abort conditions must reference known error categories.

[RESULT_NORMALIZATION_RULES]

Transformations to apply to raw source results before merging, such as field renaming, type coercion, or unit conversion

rules:[{source:orders-api, map:{cust_id:user_id, total:amount_cents}, coerce:{amount_cents:int}}]

Must be a valid JSON array of per-source normalization maps. Each map requires source id matching a [DATA_SOURCES] entry. Coercion types must be: int, float, string, bool, iso-date. Reject unknown coercion types.

[DEDUPLICATION_KEYS]

Fields used to identify duplicate records across sources for merging or conflict resolution

keys:[user_id, email]

Must be a non-empty array of field names present in [OUTPUT_SCHEMA]. Reject if any key is missing from the output schema. Order matters for composite key matching.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the parallel fetch and merge prompt into an application with validation, retries, logging, and failure handling.

The Parallel Fetch and Merge prompt is designed to sit inside an orchestration layer that receives a user request, identifies independent data sources, and dispatches concurrent tool calls. The prompt itself produces a structured execution plan—not the actual fetched data. Your application must parse this plan, execute the specified tool calls in parallel, collect results (including partial failures and timeouts), and then feed everything into a second merge-and-normalize step. Do not treat this prompt as a one-shot answer generator; it is a planner that requires a reliable executor and a separate merge prompt or deterministic merge function downstream.

Execution flow: (1) Receive user query and available tool schemas. (2) Populate the prompt template with [USER_QUERY], [AVAILABLE_TOOLS], [CONSTRAINTS] (timeout budgets, rate limits, max concurrency), and [OUTPUT_SCHEMA] (the expected execution plan structure). (3) Call the model with response_format set to the parallel plan schema—require fields like parallel_groups, merge_strategy, conflict_resolution, and timeout_coordination. (4) Validate the plan: check that each tool in the plan exists in your registry, that no tool depends on another tool's output within the same parallel group, and that timeout budgets sum to less than your total SLA. Reject plans that reference unknown tools or create circular dependencies. (5) Execute each parallel group with Promise.all (or equivalent), wrapping each call in a timeout and error boundary. Capture partial results, error types, and latency per call. (6) Feed the raw results, the original plan, and any error metadata into a merge prompt or deterministic merge function that applies the specified merge_strategy and conflict_resolution rules. (7) Return the merged result to the user, including a partial_failure flag and unavailable_sources list when some fetches failed.

Validation and safety gates: Before executing any tool call, validate that each argument matches the tool's schema—type-check required fields, enforce enums, and reject calls with missing mandatory parameters. For read-only fetches, this is a correctness gate; for tools that could mutate state, this is a safety requirement. Log the full execution plan, validation results, and per-call outcomes to your observability pipeline. Include a plan_id or trace_id so you can correlate the plan with its execution results during debugging. If the model produces a plan that fails validation, retry once with the validation errors injected into the prompt as [PREVIOUS_PLAN_ERRORS]. If the retry also fails, fall back to a sequential execution mode or escalate to a human operator. Never execute an invalid plan silently.

Model choice and performance: This prompt works best with models that support structured outputs and have strong instruction-following for multi-step reasoning—GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro are good starting points. Smaller models may struggle with dependency detection and produce plans that look valid but contain subtle ordering bugs. If latency is critical, consider caching the execution plan for repeated query patterns with different parameters. The merge step can often be handled deterministically (e.g., concatenation, field-level union with timestamp-based conflict resolution) rather than requiring a second model call—reserve the model for complex semantic merging or conflict resolution that requires judgment. Always set explicit max_tokens and timeout values on both the planning call and each tool execution to prevent a single slow source from blocking the entire fan-out.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the parallel execution plan produced by the prompt. Use this contract to parse, validate, and integrate the model output into your orchestration engine.

Field or ElementType or FormatRequiredValidation Rule

execution_plan.parallel_groups

Array of arrays of tool_call objects

Must be non-empty. Each inner array must contain at least one tool_call. No tool_call ID may appear in more than one group.

execution_plan.parallel_groups[].tool_call.id

String matching ^[a-zA-Z0-9_-]+$

Must be unique within the plan. Must match an ID from the input tool registry.

execution_plan.parallel_groups[].tool_call.function_name

String

Must exactly match a function name declared in the input tool schemas. Case-sensitive.

execution_plan.parallel_groups[].tool_call.arguments

Valid JSON object

Must conform to the input JSON Schema for the named function. Required fields must be present. No extra fields allowed unless schema permits additionalProperties.

execution_plan.merge_strategy

String enum: [union, priority_ordered, keyed_merge, custom]

Must be one of the allowed enum values. custom requires a non-empty merge_instructions field.

execution_plan.merge_strategy_details.priority_order

Array of strings

Required when merge_strategy is priority_ordered. Must list tool_call IDs in descending priority. No duplicates.

execution_plan.merge_strategy_details.merge_key

String

Required when merge_strategy is keyed_merge. Must reference a field name present in all tool output schemas.

execution_plan.conflict_resolution

String enum: [first_wins, last_wins, majority_vote, confidence_weighted, manual_review]

Must be one of the allowed enum values. manual_review triggers a human-in-the-loop gate.

execution_plan.timeout_coordination.max_total_ms

Integer

Must be a positive integer. Must be greater than or equal to the sum of max_per_group_ms across all groups.

execution_plan.timeout_coordination.max_per_group_ms

Integer

Must be a positive integer. Applied to each parallel group independently.

execution_plan.partial_failure_policy

String enum: [fail_all, return_partial, retry_failed_only, escalate]

Must be one of the allowed enum values. escalate requires a non-empty escalation_target field.

execution_plan.result_normalization_schema

Valid JSON Schema object

Must be a valid JSON Schema draft-07 or later. Must define the unified output structure after merging.

execution_plan.plan_rationale

String

If present, must be a non-empty string explaining parallelism decisions, dependency analysis, and merge choices.

PRACTICAL GUARDRAILS

Common Failure Modes

Parallel fetch and merge prompts fail in predictable ways. These are the most common production failure modes and the specific guardrails that prevent them.

01

Silent Merge Conflicts

What to watch: Two parallel calls return conflicting values for the same entity field, and the merge logic picks one arbitrarily without surfacing the conflict. The user sees a coherent but wrong result. Guardrail: Add a conflict detection pass that compares overlapping keys across parallel results, flags mismatches, and either surfaces both values with source attribution or applies a declared resolution strategy (e.g., latest timestamp wins, primary source overrides).

02

Partial Failure Cascades

What to watch: One parallel call times out or returns an error, and the merge step either fails entirely or produces a corrupted aggregate. Independent results get discarded because one dependency broke. Guardrail: Design the merge schema to accept partial results with explicit nullability. Include a partial_results flag and per-source error metadata so downstream consumers can decide whether partial data is usable.

03

Schema Drift Across Sources

What to watch: Two APIs return semantically equivalent data under different field names, types, or nesting structures. The merge prompt maps them incorrectly or drops fields it doesn't recognize. Guardrail: Define an explicit normalization schema with field mappings per source before the merge step. Validate that every required output field has a mapping from at least one source, and log unmapped source fields as warnings.

04

Timeout Mismatch Deadlocks

What to watch: The merge prompt waits for all parallel calls to complete, but one source has a longer latency profile. Fast sources sit idle while the slowest call blocks the entire aggregate. Guardrail: Set per-source timeout budgets and a global deadline. Use a timeout_behavior field per source: required, optional, or degraded. If a required source times out, fail the merge. If optional, proceed with partial results and flag the gap.

05

Duplicate Record Inflation

What to watch: Two sources return the same logical record with slightly different identifiers or formatting. The merge prompt treats them as distinct entities, inflating result counts and confusing downstream consumers. Guardrail: Include a deduplication key in the merge schema (e.g., dedup_on: [email, external_id]). Apply match rules with a similarity threshold and merge strategy for near-duplicates before returning the final result set.

06

Stale Data Propagation

What to watch: One parallel call returns cached or stale data while another returns fresh results. The merge produces an inconsistent snapshot where related fields don't align temporally. Guardrail: Require each source to return a fetched_at timestamp. The merge prompt should compare timestamps across correlated fields and flag discrepancies exceeding a staleness threshold. For read-after-write consistency, sequence dependent calls instead of parallelizing them.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Parallel Fetch and Merge Prompt before deploying it to production. Each criterion targets a specific failure mode in parallel execution plans, merge logic, or partial failure handling.

CriterionPass StandardFailure SignalTest Method

Parallel-safe classification

All tool calls in a parallel group are correctly labeled as independent (no read-after-write dependency on another call in the same group)

A tool call that requires the output of another call in the same group is marked parallel-safe

Run 10 dependency-injection test cases with known read-after-write pairs; assert zero false-parallel classifications

Merge strategy completeness

Every field in [OUTPUT_SCHEMA] has a defined merge rule (last-write-wins, concatenate, union, or custom resolver)

A field in the merged output is null or missing because no merge rule was specified for it

Parse the merge plan and diff against [OUTPUT_SCHEMA] field list; assert 100% field coverage

Conflict resolution rule application

When two parallel calls return different values for the same field, the specified conflict rule is applied and the resolution is logged

Conflicting values are silently dropped, or an arbitrary value is chosen without logging the conflict

Inject 5 test cases with known conflicting field values; assert the correct resolution rule fires and a conflict log entry is generated

Partial failure handling

If one parallel call fails or times out, the merge plan produces a valid partial result with failed-source markers and does not discard successful results

A single failure causes the entire merge to abort or return an empty result

Simulate 3 scenarios with 1-of-N call failures; assert successful results are preserved and failed sources are annotated with error codes

Timeout coordination

The execution plan specifies a global deadline and per-call timeout budgets; the merge logic includes a staleness threshold for late-arriving results

The plan omits timeout budgets, or the merge logic waits indefinitely for a timed-out call

Validate the plan JSON for presence of global_deadline_ms and per_call_timeout_ms fields; assert merge logic includes stale_after_ms check

Result normalization consistency

All parallel results are normalized to [OUTPUT_SCHEMA] types and units before merging; type mismatches are coerced or flagged

A numeric field from one source is merged as a string from another source without conversion, producing a type-inconsistent output

Feed 3 sources with intentionally mismatched types (e.g., string vs integer for the same field); assert output types match [OUTPUT_SCHEMA] or a coercion warning is logged

Deduplication accuracy

Duplicate records across parallel calls are detected and merged using the specified match key; no duplicate rows appear in the final output

The merged output contains duplicate records that share the same [DEDUP_KEY] value

Run a test with 2 sources returning overlapping records; assert final row count equals unique key count

Error isolation boundary

An error in one parallel call does not propagate to independent calls; the error is contained and reported per-source

An unhandled exception in one call causes the entire parallel group to fail or return a generic error

Inject a fatal error in 1 of 4 parallel calls; assert the other 3 results are processed normally and the error is scoped to the failing source

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small set of 2-3 mock data sources. Remove strict schema validation from the prompt and focus on getting the merge logic right. Use a simple JSON output with sources, merged_results, and conflicts arrays. Test with synthetic data that includes obvious conflicts and partial failures.

code
[SYSTEM]: You are a data merge assistant. Given results from multiple independent data sources, produce a merged output with conflict notes.

[INPUT]:
- Source A: [SOURCE_A_RESULT]
- Source B: [SOURCE_B_RESULT]
- Merge strategy: [STRATEGY]

[OUTPUT]: JSON with merged_results and conflicts arrays.

Watch for

  • Missing conflict resolution when two sources return different values for the same field
  • Silent data loss when one source returns null and the other returns a value
  • Overly broad merge instructions that produce inconsistent output shapes
Prasad Kumkar

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.