VOOZH about

URL: https://dev.to/adelan/state-drift-in-a-polymarket-trading-system-using-event-sourcing-1gk8

⇱ State Drift in a Polymarket Trading System Using Event Sourcing - DEV Community


When building a real-time trading system for Polymarket, I assumed strategy and execution would be the hardest parts.

I was wrong.

The real issue was state drift - the system slowly stopped matching reality.

  1. What state drift looked like
  2. Incorrect positions
  3. Duplicate exposure
  4. Mismatch between bot state and real market state

There was no crash, only silent inconsistency.

  1. Why it happens
  2. WebSocket missing updates
  3. Delayed API responses
  4. Partial order fills
  5. Duplicate events
  6. Missing events
  7. In-memory state assumptions

  8. Core problem
    The system trusted runtime memory instead of reality.

  9. Solution: Event Sourcing

Store events instead of state:

  • trade events
  • order events
  • fill events

State is always rebuilt from history.

  1. Architecture

Event Log → State Rebuild → Current State

This makes the system deterministic and replayable.

  1. Reconciliation layer

Periodically:

  • fetch real positions
  • compare with internal state
  • correct drift
  1. Result
  2. No silent inconsistencies
  3. Easier debugging
  4. System can rebuild from scratch
  5. Reliable state tracking

  6. Key lesson
    State in trading systems is not stored - it is reconstructed.