Shared State
In a multi-agent system, agents may need to read and write shared state. Shared state must be managed carefully to prevent conflicts and ensure consistency.
6 min•By Priygop Team•Updated 2026
Shared State Design
- Single writer principle: only one agent writes to a given section of state at a time
- Namespace isolation: each agent writes to its own namespace (e.g., 'researcher/', 'analyser/')
- Read-only access for workers: worker agents can read from shared state but cannot overwrite other agents' outputs
- Coordinator as state manager: the coordinator reads all agent outputs and writes the synthesised result
- Atomic writes: when an agent updates state, all related fields should be written together
Namespaced Shared State
Namespaced Shared State
# Shared state with namespace isolation for multi-agent systems
class MultiAgentState:
def __init__(self, workflow_id: str):
self.workflow_id = workflow_id
self._state = {
"meta": {"workflow_id": workflow_id, "status": "running"},
"coordinator": {}, # Coordinator's data
"agents": {}, # Per-agent namespaces
"shared": {}, # Read-only shared data
}
self._write_log = []
def agent_write(self, agent_name: str, key: str, value):
"""Each agent writes only to its own namespace."""
if agent_name not in self._state["agents"]:
self._state["agents"][agent_name] = {}
self._state["agents"][agent_name][key] = value
self._write_log.append({"agent": agent_name, "key": key})
def agent_read(self, agent_name: str, key: str, default=None):
"""Read from own namespace."""
return self._state["agents"].get(agent_name, {}).get(key, default)
def read_agent_output(self, agent_name: str) -> dict:
"""Coordinator reads any agent's output."""
return self._state["agents"].get(agent_name, {})
def set_shared(self, key: str, value):
"""Write to shared read-only space (coordinator only)."""
self._state["shared"][key] = value
def get_shared(self, key: str, default=None):
"""All agents can read shared data."""
return self._state["shared"].get(key, default)
state = MultiAgentState("WF-001")
state.agent_write("researcher_1", "findings", ["Django", "FastAPI"])
state.agent_write("researcher_2", "findings", ["Flask", "Tornado"])
state.set_shared("all_findings", state.read_agent_output("researcher_1")["findings"] +
state.read_agent_output("researcher_2")["findings"])
print("Agent 1 findings:", state.agent_read("researcher_1", "findings"))
print("All findings:", state.get_shared("all_findings"))
print("Write log:", state._write_log)Key Takeaways
- In a multi-agent system, agents may need to read and write shared state.
- Single writer principle: only one agent writes to a given section of state at a time
- Namespace isolation: each agent writes to its own namespace (e.g., 'researcher/', 'analyser/')
- Read-only access for workers: worker agents can read from shared state but cannot overwrite other agents' outputs