skip to content

A gameplay event bus dispatches immediately: what breaks when a listener is destroyed or raises another event mid-dispatch, and what does deferred dispatch change?

level: middleimportance: must knowfreq 52%

answer

  1. who owns the subscription
  2. list mutated while iterating
  3. nested dispatch, half-updated state
  4. queue now, flush at a fixed point

basics

~20 s

Immediate dispatch runs listeners inside the sender's call, so a destroyed listener becomes a dangling callback and a listener that raises events recurses mid-update. Deferred dispatch queues events and flushes them at a fixed point, trading latency for safety.

solid answer

~50 s

An event bus lets a quest hear `EnemyKilled` without combat code knowing quests exist. With **immediate dispatch** each `raise` calls every listener on the spot, which causes three classic bugs: a listener destroyed without unsubscribing leaves a **dangling callback**; a listener that subscribes or unsubscribes during dispatch **mutates the list being iterated**; and a listener that raises another event **re-enters** the bus, so handlers run nested, in an order nobody designed, against state the sender has only half updated, sometimes in a cycle. The fixes are subscription tokens tied to the listener's lifetime, iterating a snapshot, and **deferred dispatch**: events are copied into a queue and flushed at a defined point in the frame. That costs some latency (later in the frame or the next frame), means payloads must carry values and handles rather than raw pointers, and needs a cap on events raised during a flush.

code

pseudocode · 14 lines
pseudocode
function post(event):
    queue_next.append(copy_of(event))        # values and handles only

function flush():
    passes = 0
    while queue_next is not empty and passes < MAX_PASSES:
        current = queue_next
        queue_next = new empty queue          # events posted by listeners land here
        for event in current:
            for sub in snapshot(listeners[event.type]):
                if is_alive(sub.handle):      # generation check, skip dead listeners
                    sub.callback(event)
        passes = passes + 1
    # anything still in queue_next waits for the next frame's flush

go deeper

for a junior

Say what an event bus decouples: senders raise events, listeners subscribe, and neither knows the other. Name one gameplay example.

for a middle

Walk through dangling listeners, list mutation during dispatch and re-entrancy under immediate dispatch, and the fixes for each.

for a senior

Contrast immediate and deferred dispatch: flush point, value-and-handle payloads, a pass cap for cycles, and which events justify which mode.

for a principal

Decide where the bus belongs in the frame, which systems may talk through it versus direct calls, and what tooling keeps implicit control flow debuggable.

## Why games use an event bus at all An **event bus** (or message bus) is a dispatcher where senders **raise** typed events and listeners **subscribe** to event types. The sender does not know who listens. That decoupling is the reason it exists in a game: - a quest that a designer scripts, such as "collect five relics", listens for `ItemPickedUp` without the inventory code knowing quests exist; - audio, achievements, UI and analytics all react to `EnemyKilled` without the combat code calling each one; - a state machine driving an enemy can receive its transition triggers, and a perception layer its noise and sight stimuli, through the same bus. The cost is that control flow becomes **implicit**. A direct call shows in a stack trace and a code search; an event shows neither, so ordering, lifetime and re-entrancy become things the bus has to define. ## Immediate dispatch and its three classic bugs With **immediate** (synchronous) dispatch, `raise(event)` loops over the listeners and calls each before returning to the sender. 1. **Dangling listeners.** A listener object is destroyed but its callback is still registered. The next raise calls into freed memory, or into a managed object that is logically dead. The fix is ownership: `subscribe` returns a **subscription token** owned by the listener, and destroying the token unsubscribes. Alternatively the bus stores a **handle** (an index plus generation) and checks it is still valid before each call. 2. **Mutating the list during iteration.** A listener reacting to `DoorOpened` subscribes a new listener or unsubscribes itself. Depending on the container this skips a listener, calls one twice, or invalidates the iterator and crashes. The fix is to iterate a **snapshot**, or to mark removals and apply additions and removals after the loop. 3. **Re-entrancy.** A listener raises a second event while the first is still being dispatched. The bus now runs a nested dispatch inside the first one: - listeners of the first event that have not run yet will run **after** listeners of the second, an order nobody designed; - the original sender may be halfway through its own update, so the nested listeners read **half-updated state**; - two events that raise each other produce **unbounded recursion**. ## Deferred dispatch **Deferred** (queued) dispatch changes the contract: `post(event)` **copies** the event into a queue and returns immediately. At a defined point in the frame, often after the simulation update, the engine **flushes** the queue and delivers events in order. | Property | Immediate dispatch | Deferred dispatch | |---|---|---| | When listeners run | Inside the sender's call | At the flush point | | State listeners see | Whatever the sender has done so far | A consistent point between updates | | Re-entrancy | Nested dispatch | New events join the queue | | Latency | None | Until the flush, possibly the next frame | | Payload | May reference live objects | Must survive until the flush | | Veto or return value | Possible, such as "can this door open?" | Not possible; the sender has moved on | Deferral brings its own rules: - **payloads hold values and handles**, never raw pointers, because the sender or subject can be destroyed before the flush; - events posted **during** a flush either go to the next frame's queue or are processed in the same flush up to a **cap**, so a cycle cannot hang the frame; - listeners still need lifetime-safe subscriptions, since a listener can be destroyed between post and flush. ## Choosing per event Many engines end up offering both. Use **immediate** dispatch for queries that need an answer now and for events whose listeners are cheap and do not raise further events. Use **deferred** dispatch for gameplay notifications that many systems react to, such as deaths, pickups and quest-state changes, where consistency matters more than a fraction of a frame of latency. A debug view that logs every event with sender, frame number and listener count recovers some of the traceability that direct calls had.

  • Why should a deferred event carry an entity handle rather than a pointer to the entity?
    The entity can be destroyed between the post and the flush. A handle with a generation count can be checked at flush time and found stale, so the listener skips or handles it; a raw pointer would be dereferenced after the memory was freed or reused by another object.
  • When is immediate dispatch still the right choice?
    When the sender needs an answer before continuing, such as asking listeners whether an action is allowed, and when listeners are cheap, do not raise further events and cannot outlive the sender's call. Even then, subscriptions should be lifetime-safe and the bus should iterate a snapshot.
  • How do you stop event-driven code from becoming impossible to debug?
    Give the bus an event log or trace view listing each event, its sender, the frame it was posted and flushed, and which listeners ran. Typed events instead of string names also let a code search find every sender and listener.

  • Listeners can be raw function pointers with no lifetime tracking
  • Raising an event inside a listener is always safe
  • Deferred events can hold raw pointers to the sender
  • An event bus removes all coupling, so ordering never matters
  • Deferred dispatch has no latency cost