keepcalculator

06 Numbers and Powers

Event Sourcing vs Pure Reducers for Game State

Card No. 06·81510 · Updated · Standard formula, shown below

For multiplayer game state, pure reducers win for most games because they are deterministic, testable, and simple to reason about, while event sourcing adds value only when you need audit trails, time travel, or complex undo. This article compares the two approaches, explains how each works, and gives concrete guidance for choosing between them.

Background: The Two Paradigms

Pure reducers come from functional programming and the Redux pattern. A reducer is a pure function that takes the current state and an action, and returns a new state. It has no side effects, so the same input always produces the same output. In multiplayer games, the server can run the same reducer for all clients, and as long as everyone processes the same actions in the same order, they all converge on the same state.

Event sourcing is a different persistence model. Instead of storing the current state, you store a log of every event that ever happened. The current state is derived by replaying all events from the beginning. This is like a bank statement: you don’t store the balance, you store every transaction and compute the balance by summing them.

The two are not mutually exclusive. Many systems use a reducer to compute state from an event log, which is essentially event sourcing with a functional core. The real question is whether you need the event log at all, or whether a snapshot of current state is enough.

How Pure Reducers Work

In a pure reducer architecture, the server holds the authoritative state, and clients send actions (e.g., “move left”, “fire weapon”). The server validates each action, applies it to the state via a reducer, and broadcasts the new state to all clients.

  • Deterministic: The same sequence of actions always produces the same state, so debugging is straightforward.
  • Simple: You only store the current state, which is easy to serialize, backup, and load.
  • Fast: No replay is needed; the state is always available in memory.
  • Testable: You can unit-test the reducer with a given state and action, and assert the output.

Example: A simple position reducer in JavaScript:

function reducer(state = {x: 0, y: 0}, action) {
  switch (action.type) {
    case 'MOVE':
      return {x: state.x + action.dx, y: state.y + action.dy};
    default:
      return state;
  }
}

This is clean, but it forgets history. If you need to know what happened in the last 10 seconds (e.g., for a replay feature), you have to store that separately.

How Event Sourcing Works

In event sourcing, every change to the game state is captured as an immutable event. Events are stored in an append-only log. To get the current state, you replay all events from the beginning (or from a snapshot).

  • Audit trail: You have a complete history of every action, which is useful for cheating detection, debugging, and analytics.
  • Time travel: You can reconstruct the state at any point in time by replaying events up to that point.
  • Complex undo: You can revert to a previous state by replaying events up to a certain point, or by applying compensating events.
  • Event-driven: Other systems can subscribe to the event stream for real-time analytics or projections.

Example: Instead of storing the player’s position, you store events like PlayerMoved with coordinates and timestamp. The current position is computed by summing all movement events.

The main cost is complexity. You need to manage event versioning, snapshots (to avoid replaying millions of events), and eventual consistency.

How to Choose: Key Factors

Ask yourself these questions:

  1. Do you need a full history? If you need to audit player actions for anti-cheat, or provide a replay feature, event sourcing is a natural fit. If not, pure reducers are simpler.
  2. How complex is your state? If your state is huge (e.g., a full world with thousands of entities), storing only the current state is much more efficient than replaying a long event log.
  3. What is your team’s experience? Event sourcing has a steep learning curve. If your team is new to functional programming, pure reducers are easier to adopt.
  4. Do you need real-time consistency? Pure reducers give you immediate consistency. Event sourcing often involves eventual consistency, which can be problematic for fast-paced multiplayer games.
  5. What is your scaling strategy? Event sourcing can be scaled by partitioning the event log, but it’s complex. Pure reducers can be scaled by sharding the state, but you need to handle cross-shard actions.

In general, for a typical multiplayer game (e.g., a battle royale, MMO, or MOBA), pure reducers are the better starting point. You can always add an event log later if you need it.

Common Problems and Pitfalls

Both approaches have known issues.

With pure reducers:

  • State explosion: If you store too much in state (e.g., every entity’s full position history), memory usage grows. But you can store only the current state and keep a separate log for replays.
  • Action ordering: In multiplayer, actions arrive at different times. You need a consistent ordering mechanism (e.g., server timestamps, sequence numbers) to ensure all clients apply actions in the same order.
  • Rollback: If an action is invalid (e.g., a player tries to move through a wall), you need to reject it before applying it. With pure reducers, you can validate before calling the reducer, but you must be careful not to partially apply.

With event sourcing:

  • Event versioning: As your game evolves, event schemas change. You need to handle migrations (e.g., upcasting old events to new formats).
  • Snapshotting: Replaying millions of events is slow. You need periodic snapshots to start replay from a recent point.
  • Eventual consistency: If you use projections (read models) that are updated asynchronously, players may see stale data.
  • Complexity: Debugging is harder because you have to trace through the event log.

A common misconception is that event sourcing is inherently slower. In practice, if you use snapshots and keep the event log in memory, it can be fast. But it’s still more complex.

Comparison: When to Use Which

Here’s a quick comparison table:

Feature Pure Reducers Event Sourcing
Determinism Yes, by construction Yes, if replay is deterministic
Audit trail No (unless you log separately) Yes, built-in
Time travel No (unless you store snapshots) Yes
Complexity Low High
Memory usage Low (only current state) High (event log)
Scaling Moderate (shard state) Hard (partition log)
Best for Fast-paced, real-time games Turn-based, RPGs, games with heavy replay/analytics

In practice, many games use a hybrid: they use pure reducers for the live simulation, and also write events to an append-only log for replays and analytics. This gives you the best of both worlds, at the cost of maintaining two systems.

Costs and Trade-offs

Development cost: Pure reducers are simpler to implement and test. Event sourcing requires more upfront design and ongoing maintenance (event schemas, migrations, snapshots).

Operational cost: Event sourcing requires storage for the event log, which can grow large. For a popular game, you might generate millions of events per day. You’ll need to manage retention policies and possibly archive old events.

Latency: Pure reducers can process actions in a single round-trip. Event sourcing with projections may introduce lag between an event being stored and the read model being updated.

Debugging: With pure reducers, you can reproduce a bug by replaying the exact sequence of actions. With event sourcing, you can also replay, but you need to ensure your replay logic is deterministic and that you have the exact event order.

Alternatives to Both

If you don’t need the full power of event sourcing, there are lighter alternatives:

  • State snapshots with periodic logging: Store the current state every few seconds, plus a log of recent actions. This gives you some history without the full event sourcing complexity.
  • Command Query Responsibility Segregation (CQRS): Separate the write model (commands) from the read model (queries). This can be used with either pure reducers or event sourcing.
  • Deterministic lockstep: Used in RTS games, where all clients run the same simulation and exchange only player inputs. This is a form of pure reducer, but with the simulation running on each client.
  • Server-authoritative with periodic snapshots: The server sends snapshots of the world state to clients, and clients interpolate between them. This is not event sourcing, but it’s a common approach for MMOs.

Frequently Asked Questions

Can I use event sourcing with a pure reducer?

Yes, and it’s a common pattern. The reducer processes events to produce the current state. The event log is the source of truth, and the reducer is the projection. This gives you the benefits of both: deterministic state from a pure function, and a full history from the log.

Which is better for a fast-paced shooter?

Pure reducers are generally better because they provide immediate consistency and low latency. Event sourcing’s eventual consistency can cause players to see different states, which is unacceptable in a shooter. You can still log events for replays, but the live simulation should use a pure reducer.

How do I handle undo in a multiplayer game?

With pure reducers, you can store a stack of previous states (or inverse actions) to implement undo. With event sourcing, you can replay events up to a certain point, or apply compensating events. The latter is more flexible but more complex.

Is event sourcing worth it for a small indie game?

Probably not. The added complexity is hard to justify unless you have a specific need for audit trails or time travel. A simple pure reducer with a database snapshot is usually sufficient for a small game.

Can event sourcing help with cheating detection?

Yes, because you have a record of every action. You can analyze the event log for patterns that indicate cheating, such as impossible speeds or impossible actions. However, this requires additional tooling, and it’s not a silver bullet.

What about performance? Is event sourcing slower?

It can be, if you have to replay a long log. But with snapshots, you can start from the latest snapshot and only replay events since then. In memory, replaying a few hundred events is fast. The bigger cost is storage and complexity, not raw speed.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →