Distributed AI Agent Architecture: Local Orchestration and Remote Graph Execution
Learn how to separate agent workflow control from remote computation using a LangGraph-based math engine. This guide covers service boundaries, explicit state contracts, conditional routing, sequential versus parallel calls, and practical considerations for reliability and observability.
Distributed AI Agent Architecture: Local Orchestration and Remote Graph Execution
1. Why Split an Agent Service?
As an agent’s logic grows, putting every node into a single process creates several problems: compute-intensive tasks block the main workflow, state ownership becomes unclear, teams struggle to develop components independently, and scaling requires replicating the entire application.
A practical approach is to separate workflow control from computation:
- Local orchestrator: Owns the overall control flow and decides which remote capability to invoke, when to repeat a step, and when to stop.
- Remote graph service: Receives requests, performs specific computations, and returns results without managing the higher-level business workflow.
The main benefit is a clear separation of responsibilities. The orchestrator determines how the workflow proceeds; the service determines how each computation runs. State moves between them through explicit fields, reducing the hidden coupling caused by shared mutable state.
This separation also has costs. Network calls introduce latency and additional failure points, serialization adds overhead, and debugging becomes more difficult. The following example illustrates the architecture and the trade-offs between sequential and parallel orchestration.
2. Example Project: A Looping Math Engine
The example consists of two components:
- A remote graph service,
math_service, with two capabilities:- When
actionispick_operation, it randomly returns a mathematical operation or anendsignal. - When
actionisgenerate_number, it returns a random integer.
- When
- A local orchestration graph,
math_orchestrator, that accepts an initial number and enters a loop. Each nonterminal iteration calls the remote service twice—once for an operation and once for an operand—then applies the operation. The loop stops when the service returnsend.
The orchestrator has two versions to demonstrate an engineering trade-off:
- Sequential execution: Make the two remote calls one after the other.
- Parallel execution: Issue both calls concurrently.
3. Project Structure and Dependencies
Use a modern Python toolchain to manage the environment. The suggested directory structure is:
math_service/ # Remote graph service├── auth.py # Authentication/authorization (optional)├── graph.py # Graph definition├── langgraph.json # Service configuration└── .env # Environment variablesmath_orchestrator/ # Local orchestrator├── sequential.py # Sequential version└── parallel.py # Parallel version
Example dependency configuration in pyproject.toml:
[project]name = "distributed-math-engine"version = "0.1.0"requires-python = "==3.13"dependencies = ["langgraph","langgraph-cli","langgraph-sdk"]
This example pins Python to 3.13 because of the Pydantic compatibility concerns with Python 3.14 and later noted in the original setup. Treat this as an environment constraint for the example rather than a permanent compatibility guarantee.
Both graphs run locally during development: the remote graph runs on a development server, while the local graph runs as an ordinary Python script. The architectural separation matches the production topology; only the deployment locations change.
4. Designing the Remote Graph Service
The key design choice is to use one graph with conditional routing for both operations, rather than creating two separate services. The incoming state’s action field selects the route:
import randomfrom typing import TypedDictfrom langgraph.graph import StateGraph, START, ENDclass MathServiceState(TypedDict):action: str # "pick_operation" or "generate_number"operation: str # Result: "add"/"subtract"/"multiply"/"divide"/"end"number: int # Result: a random integermanual_input_chance: float # Probability of requesting user input (0.0–1.0)ask_user: bool # Result: True means the orchestrator should prompt the user
Several details matter here.
Separate Input Intent from Output Results
The state carries both the request’s intent and the computation’s result. The caller supplies action as a routing signal, while nodes write results to operation or number. Keeping those meanings distinct makes the contract easier to understand and serialize.
Reserve Fields for Human-in-the-Loop Interaction
The manual_input_chance and ask_user fields reserve a way for the remote service to request user input through the orchestrator.
This is a common requirement in distributed agent systems: the computation service cannot interact with the user directly, so it returns an interaction request to the component that owns the user-facing channel. The minimal nodes below do not implement that interaction.
Let the Remote Service Return the Stop Signal
The remote service produces the end signal. Although the orchestrator owns the loop, it delegates this particular termination decision to the service and responds to the returned signal.
The node implementations and graph definition are straightforward:
def pick_operation(state: MathServiceState) -> dict:ops = ["add", "subtract", "multiply", "divide"]if random.random() < 0.1: # Stop with a fixed probabilityreturn {"operation": "end"}return {"operation": random.choice(ops)}def generate_number(state: MathServiceState) -> dict:return {"number": random.randint(1, 100)}def route(state: MathServiceState) -> str:return state["action"]builder = StateGraph(MathServiceState)builder.add_node("pick_operation", pick_operation)builder.add_node("generate_number", generate_number)builder.add_conditional_edges(START, route)builder.add_edge("pick_operation", END)builder.add_edge("generate_number", END)graph = builder.compile()
5. Local Orchestration: Sequential and Parallel Execution
The following excerpts illustrate the orchestration logic. The client.run(...) calls and omitted request fields are schematic rather than a complete SDK integration.
Sequential Version
Each iteration requests an operation first, then requests an operand if the operation is not end:
while True:op_result = await client.run(remote_graph, {"action": "pick_operation", ...})if op_result["operation"] == "end":breaknum_result = await client.run(remote_graph, {"action": "generate_number", ...})acc = apply(op_result["operation"], acc, num_result["number"])
This version is easy to follow and debug, and retry handling is relatively straightforward. Its main drawback is latency: a nonterminal iteration waits for both calls in sequence, so their durations add up. If the calls have no data dependency, that waiting time is avoidable.
Parallel Version
Because operation selection and number generation do not depend on each other’s results, the calls can run concurrently:
op_task = client.run(remote_graph, {"action": "pick_operation", ...})num_task = client.run(remote_graph, {"action": "generate_number", ...})op_result, num_result = await asyncio.gather(op_task, num_task)
The orchestrator then checks the returned operation, stops on end, or applies the operation to the accumulator and returned number.
Parallel execution reduces iteration latency to approximately the duration of the slower call, which can be valuable on high-latency networks. The trade-offs are more complicated error handling—especially when only one call fails—and twice the instantaneous call concurrency against the remote service.
Choosing Between the Two
- The calls have a data dependency: Use sequential execution when the second call needs the first call’s result.
- The calls are independent and the service can handle concurrent requests: Prefer parallel execution.
- Strict call ordering is needed to reproduce a random process: Use sequential execution.
6. Engineering Practices
Define the State Contract First
Treat the TypedDict state definition as a contract between services. Maintain and version it separately so the orchestrator and remote service do not drift apart.
Plan for Timeouts, Retries, and Idempotency
Remote calls need timeout and retry policies. Nodes that produce side effects must be idempotent so retries do not unintentionally repeat those effects.
Make Iterations Observable
Attach a trace ID to each remote call and record a state snapshot for every iteration on the orchestrator side. In looping systems, debugging often depends on understanding how state changes between iterations.
Keep Development and Production Architecturally Aligned
During development, run the remote graph on a local development server and the orchestrator as a script. At deployment time, replace the service address while preserving the same architectural boundaries.
7. Conclusion
Separating agent workflow control into a local orchestrator and computation into a remote graph service is a useful pattern for building maintainable, scalable distributed agent systems.
The core principles are to use explicit state fields as the service contract, use conditional routing to expose multiple capabilities through one remote graph, and return termination signals from the service to the orchestrator.
Sequential and parallel orchestration each have valid uses. Choose between them based on data dependencies, latency requirements, remote service capacity, and the need for predictable call ordering.
