Agent Application DevelopmentAccount
Knowledge catalogChoose core direction and segmented content
knowledge unit 05AdvancedImplementationAbout 18 minutes

Understand → Implement → Debug → Design

Algebra and business semantics of parallel state merging

Examine state modeling, reducers, concurrent merging and message deduplication.

LangGraphReducerConcurrency status

Knowledge content check2026-10-03 · Check the source of the original question2026-10-02

Which step do you want to learn from this knowledge point?

Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.

Understand first

New to this knowledge point

Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.

Start with core principles →

Realize again

Prepare to write the principles into code

Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.

View the code example →

Will troubleshoot

Need to handle failures and changes in conditions

Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.

Continue to delve deeper into the problem →

Able to choose

Need to design or review plans

Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.

Analyze engineering scenarios →
Knowledge unit directory

LEARN · PRACTICE · REFLECT

Knowledge learning and personal records

My notes and review ↗

First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.

Answers and personal notes

Each modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.

Core concept · Algebra and business semantics of parallel state merging

Understand the core principles first

Preparatory concepts:immutable data, unique identifier, concurrent updates

The reducer defines how deltas become shared facts. Replay requires that repeated input does not change the result, and parallelism requires that it does not rely on accidental arrival order; but deduplication, sorting, and conflict handling must obey business semantics, and all lists cannot be mechanically turned into sets.

Think of reducers as update semantics

Two nodes start from the same state and return new evidence. Replacing the full list may lose one update; appending both may duplicate retried results. A reducer specifies how field updates merge. LangGraph supports these merge functions for state fields.

Check the relevant algebraic properties

Associativity removes dependence on batch grouping; commutativity removes dependence on arrival order; idempotency prevents duplicate input from changing the result. Frameworks do not grant these properties automatically. Evidence IDs can deduplicate records, but conflicting text under one ID still requires a version or conflict rule. “Last response wins” lets network timing determine the fact.

Preserve each field’s meaning

Evidence may deduplicate by ID, whereas logs may retain every attempt. Amount increments need unique event IDs, and conversation messages need ordering rules. A generic append reducer cannot serve every field. Prefer deterministic pure merges, keeping external effects in nodes or tools so replaying a merge cannot send another message.

Check understanding with a question

LangGraph parallel nodes update status at the same time. How to avoid overwriting, duplication and serial tasks?

Separate immutable inputs, node outputs, and control state with explicit field ownership. Parallel branches can write results by stable subtask ID for deterministic merging. Appending is not idempotent; replacing may lose updates. Deduplicate callbacks and replay by event ID, and test recovery and concurrency against the actual framework version.

Realization and trade-offs

Start with field ownership

Draw the run_id, input version, task list, branch results, errors, and final state on the whiteboard. The input is written once by the entrance, the branch can only write its own results, and the final state is controlled by the summary node. Don't have multiple branches changing the same "Final Answer" field. For graph frameworks, first confirm whether the field uses a default update or an explicit reducer. Do not assume that the framework will automatically understand the business merge rules.

Merger should express business semantics

Assuming that two nodes return evidence lists, direct appending can retain two copies of the results, but repeated recovery may produce the same evidence; using stable evidence_id to deduplicate is more reliable. Assuming that the node returns the account balance, it cannot be simply summed, because it may be different snapshots of the same account, which should be saved by account and data version, and then selected by business rules. For out-of-order parallel completion, the merge function preferably does not depend on arrival order; it must be explicitly sorted or serialized when ordering is required.

Handling retries and cross-run pollution

The result key uses run_id, subtask ID, and input version. Retries of the same task write the same logical record, and new tasks cannot reuse old cache keys. When a branch fails, record the failure status instead of pretending to be successful with an empty list. If all needs to be completed, the summary node verifies that the task list is consistent with the result list; when partial results are allowed, the missing items are output. Preferences shared across tasks are put into independent storage and are not mixed into temporary state.

Verify the design

Construct four event sequences: A is completed first, B is completed first, A is completed repeatedly, and A is retried after failure. The final valid evidence for asserting different orders is consistent, repeated events do not change the count, and old input versions cannot overwrite new input. The focus of the interview is whether the candidate can specify the data merge contract; simply answering "add a Reducer" is not enough to demonstrate the ability to handle real conflicts.

code example

Deduplication and reject conflicts by stable evidence ID

Pure function example demonstrates idempotent collection merging; version selection rules should be defined separately when the business allows multiple versions.

def merge_evidence(*batches):
    merged = {}
    for batch in batches:
        for item in batch:
            key = item["id"]
            if key in merged and merged[key] != item:
                raise ValueError("conflicting evidence: " + key)
            merged[key] = dict(item)
    return [merged[key] for key in sorted(merged)]

a = [{"id": "e1", "version": 1, "text": "approved"}]
b = [{"id": "e2", "version": 1, "text": "checked"}]
assert merge_evidence(a, b, a) == merge_evidence(b, a)
print([x["id"] for x in merge_evidence(a, b, a)])
try:
    merge_evidence(a, [{"id": "e1", "version": 2, "text": "changed"}])
except ValueError:
    print("conflict rejected")

expected output

['e1', 'e2']
conflict rejected

Engineering deduction

scene
Interview hypothesis: Both retrieval nodes update results, and half of the references are accidentally lost online.
design decisions
Store results by branch and merge with evidence ID, verify branch status when aggregating.
Verify target
Different completion orders will obtain the same set of valid evidence, and retry will not add duplicate entries.
applicable boundary
Data such as balances and sorting messages cannot be copied and merged from sets, and independent rules need to be defined.

Continuous questions and answers

Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.

Draw inferences from one example: If the conditions change, how to deduce it?

First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.

Counter increment

Changing conditions:Collection records become re-deliverable amount events

Extended question:How do I combine "increase by 100" without double counting?

Derivation and reference solutions

A stable event_id is assigned to each real business event, and the ledger first removes duplicate events and then sums them. Two different legal increases must be included even if the amount is the same, so they cannot be deduplicated by numerical value. If correction is needed, use new events related to the original events to retain the original facts; production atomicity is guaranteed by database constraints.

The principles that remain unchanged:What is repeated is the same business event, not the same content.

An orderly dialogue is required

Changing conditions:Parallel evidence becomes causally ordered news

Extended question:Can I use unordered set reducer directly?

Derivation and reference solutions

No. Save the message identity, parent calling relationship and determinable sequence number, and then merge them to build a view based on causal constraints. Parallel independent responses can be displayed in a stable order, but the tool results must be associated with the correct call and cannot be allowed to be relegated to another question by sorting. Explicitly preserve concurrency relationships when ordering is not determined.

The principles that remain unchanged:The nature of the merger must serve business implications and causation cannot be sacrificed to satisfy commutativity.

Easy to make mistakes

  • Append all fields uniformly
  • Depends on task completion order
  • Mix user preferences with temporary results in the same status field

References

It is designed based on public technical information; the reference materials support the technical mechanism, and the scenarios and scoring standards are designed by this website and do not represent the original interview questions of a certain company. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.

Check how far you understand

After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.

Basic standards met
Can identify parallel coverage and define field ownership.
Intermediate and advanced signals
Deduplication, versioning and summary completion conditions are given.
Senior Signal
Can use out-of-order, conflict and replay counterexamples to prove merge semantics.

View verification records for independent examples

Hands-on verificationComplete on demand · Suggestions15 minutes

Implement the pseudo code to merge two batches of evidence by evidence_id, and explain the processing of different versions with the same ID.

Expand acceptance requirements and checkpoints
  • Repeated entry does not change the result
  • Merge is not affected by branch completion order
  • Conflicts are handled explicitly

Key inspections

  • Distinguish between field ownership and merge rules
  • Understanding deduplication keys and input versions
  • Verify out-of-order and replay behavior