Graph-Based Orchestration for a Distributed Math Service: A Practical Guide
This article explains how to split an AI agent application into a local orchestration graph and a remote service graph, using a random math operation scenario. It covers the architecture and responsibility boundaries, conditional routing within a single service graph, iteration and termination logic in the orchestrator, engineering setup, fault tolerance, observability, security, and deployment and scaling recommendations.
1. Background: Why a Two-Graph Structure
When building AI agent applications, a single graph often struggles to handle both interaction orchestration and capability supply. The former needs to stay close to the user and interact frequently with external input; the latter needs to be stable, independently deployable, and reusable across multiple callers. Splitting these into a local orchestration graph and a remote service graph balances responsibility boundaries, deployment models, and reusability.
This article uses random math operations as the example scenario. The remote service graph receives an action field and returns either a random math operation or a random integer. After receiving an initial number, the local orchestration graph calls the remote graph twice per iteration, requesting “pick operation” and “generate number” respectively, completes one operation, and stops when the result is a termination marker.
Note that both graphs in the example run in a local environment: the remote graph is hosted on a development server, and the local graph runs as a regular script. Here, “remote” is a logical boundary, not a physical distance.
2. Overall Architecture and Responsibilities
- Local orchestration graph (Orchestrator): Maintains session-level state and handles iteration control, termination checks, and user interaction.
- Remote service graph (Service): Has no session-state preference, returns results based on the requested action, and is easy to scale horizontally and reuse.
- Communication layer: Uses structured requests and responses, with the action field driving server-side routing.
The key benefit of this split is that the service graph does not care who calls it or how many times, while the orchestration graph does not care how intermediate results are produced. The two sides are decoupled through a clear contract.
3. Remote Service Graph Design: Conditional Routing with Multiple Actions in One Graph
The remote graph uses a single state structure to carry input and output. Core fields include action, operation result, random integer, manual input probability, and whether user confirmation is needed. The action field determines the routing direction: pick an operation or generate a number.
Illustrative code (structure only, not tied to a specific framework API):
from typing import TypedDictfrom langgraph.graph import StateGraph, START, ENDimport randomclass ServiceState(TypedDict):action: str # "pick_operation" / "generate_number"operation: str # add/subtract/multiply/divide/endnumber: intmanual_input_chance: floatask_user: booldef route(state: ServiceState) -> str:return "pick" if state["action"] == "pick_operation" else "gen"def pick_operation(state: ServiceState) -> ServiceState:ops = ["add", "subtract", "multiply", "divide", "end"]return {"operation": random.choice(ops)}def generate_number(state: ServiceState) -> ServiceState:return {"number": random.randint(1, 100)}g = StateGraph(ServiceState)g.add_node("pick", pick_operation)g.add_node("gen", generate_number)g.add_edge(START, "pick") # The entry is actually chosen by conditional routingg.add_edge("pick", END)g.add_edge("gen", END)
Design highlights:
- Conditional routing at the entry: Split traffic based on the action field to avoid maintaining multiple graphs.
- Separate output fields from input fields: Input only handles the action, and output only writes results, reducing state pollution.
- External termination semantics: Whether to stop is expressed by a termination marker in the operation result; the service graph itself holds no loop.
4. Local Orchestration Graph Design: Iteration, Termination, and Human Input
The local graph maintains an accumulated value and a round counter. Each round makes two remote calls: the first fetches the operation, and the second fetches the number. If the operation is the termination marker, it ends; otherwise, it applies the operation and moves to the next round. The manual input probability field determines whether to request user confirmation, improving controllability.
Illustrative code:
class OrchState(TypedDict):value: intround: intdone: boolask_user: booldef step(state: OrchState) -> OrchState:op = remote_call({"action": "pick_operation"})["operation"]if op == "end":return {"done": True}n = remote_call({"action": "generate_number"})["number"]v = apply(op, state["value"], n)return {"value": v, "round": state["round"] + 1}
Key constraints:
- The termination condition must be explicit and decidable to avoid infinite iteration.
- The two calls per round should run serially to keep the “operation first, then number” semantics consistent.
- Human input is an optional branch and should not block the main flow.
5. Engineering Setup: Configuration, Environment, and Dependencies
Project metadata should specify the runtime version and the minimal set of dependencies. The example declares only the basic packages needed for orchestration and remote calls, keeping dependencies minimal. Environment variables centrally manage sensitive configuration, and a configuration file describes the graph structure and entry points, making it easy to migrate across environments.
Recommendations:
- Dependency layering: Separate core orchestration dependencies from optional extension dependencies.
- Externalized configuration: Graph structure, routing rules, and timeout thresholds should all be configurable.
- Environment isolation: Development, testing, and pre-release should use separate configurations and keys.
6. Fault Tolerance, Observability, and Security
- Fault tolerance: Remote calls need timeouts and retry limits; abnormal termination caused by randomness should be explainable.
- Observability: Log the action, input/output summary, and duration of each round to form a traceable chain.
- Security: Remote interfaces should enforce identity verification and access control; sensitive configuration should not be committed to the code repository.
- Idempotency and consistency: Keep generation-type interfaces stateless, and snapshot orchestration state for recovery.
7. Deployment and Scaling Recommendations
In a cloud deployment, the service graph can run on a container platform with a load balancer and logging service in front; the orchestration graph can run as a task-based script or a long-running service. Use a monitoring and alerting system to track call success rate, latency, and termination rate. For elasticity, scale the service graph horizontally while keeping session affinity on the orchestration side.
8. Conclusion
The two-graph model of “local orchestration plus remote service” achieves separation of responsibilities through a clear contract, reduces the number of graphs through conditional routing, and ensures controllability through explicit termination. This model suits agent systems that need reusable capabilities and decoupled interaction and computation, and it is a general practice path for building scalable graph orchestration applications.
