State Synchronization
When multiple agents share state, synchronisation ensures they read consistent data and do not overwrite each other's updates.
Shared State Challenges
When two agents write to the same state simultaneously, one write may overwrite the other — a race condition.
Example:
- Agent A reads: {'inventory': 10}
- Agent B reads: {'inventory': 10}
- Agent A writes: {'inventory': 9} (decremented by 1)
- Agent B writes: {'inventory': 9} (also decremented by 1 from the old value)
- Result: inventory is 9, but should be 8
Solutions:
1. Optimistic locking: include a version number. If the version has changed since you read, reject the write.
2. Pessimistic locking: lock the state before reading, unlock after writing. Slower but always consistent.
3. Atomic operations: use database-level atomic increments/decrements (no read-modify-write cycle).
4. Single writer: designate one coordinator agent as the only writer. Workers send updates as requests.