DEV Community

Cover image for Your callback ran twice, and your state never recovered
Abhishek Kumar Dutta
Abhishek Kumar Dutta

Posted on

Your callback ran twice, and your state never recovered

The Callback Trap: Inversion of Control in Modern Architectures Callback hell was never really about nesting. The lasting danger is inversion of control: the moment you pass a function to someone else's code, you stop deciding when it runs, how often it runs, or whether it runs at all.

The trading dashboard looked correct in every demo. Positions updated, the P&L ticker moved, and fills appeared in the blotter as they arrived. Then, on busy mornings, a trader would report that a position was wrong. Not by much, and not consistently. Refreshing the page fixed it. Nothing threw, and nothing showed up in the error tracker.

The cause was easy to see once I read the code and hard to have predicted. Several callbacks were registered independently: one on the order-fill socket, one on a price stream, and one on a REST snapshot request that ran after every reconnect. Each of them mutated the same module-level positions object directly. The order they ran in was decided by when network packets happened to arrive. When a reconnect snapshot landed after a handful of newer fills, it overwrote them with older data, and the UI rendered the result without complaint.

The team's first diagnosis blamed the framework's rendering. The rendering was fine. The real problem was that nothing owned the order of events. Every callback was a separate writer to shared state, and the code had handed control over when those writers ran to the network.

Most engineers believe callback problems were solved when Promises and async/await arrived. What got solved was the geometry: the nested pyramid of doom. Callbacks themselves never left. They moved into event handlers, observers, state subscriptions, stream listeners, and higher-order functions. In 2026 the risk isn't how callback code looks. It's inversion of control and the untracked side effects that follow from it.

By the end of this post you'll know exactly what authority you surrender when you pass a callback, the three failure modes that follow, and three patterns for taking control back.

The mechanism: what you hand over when you pass a callback

Synchronous control: Your code ──> function ──> return value
Inversion of control: Your code ──> external system (invokes if and when it chooses)──> your callback

When you call a function yourself, you decide when it runs and how many times. The result, or the exception, comes back to the line that called it. When you pass a callback, you give those decisions to the receiver, and with them three guarantees that are easy to assume:

  • How many times it runs. Once, never, or twice after a retry or reconnect. The contract is whatever the receiver's implementation does, not what you assumed when you wrote the handler.

  • When and where it runs. It may run synchronously inside your registration call, on a later task, or in a different execution context. The code that registered it has usually long since returned.

  • Where its errors go. An exception thrown in your callback travels into the receiver's stack, or into nowhere.

// You wrote this expecting one call per update
thirdPartyLib.onUpdate((data) => {
  applyUpdate(data);
});
Enter fullscreen mode Exit fullscreen mode

Nothing in that code says how many times applyUpdate runs. That is decided by code you don't own.

Higher-order functions spread the problem. A debounce, throttle, or withRetry wrapper is a function that takes your callback and returns a new one, and each wrapper changes call count and timing again. A retry wrapper around a handler is, by design, a mechanism for calling your code more than once.

The real-world cost: three failure modes

Double invocation
Reconnects, retries, and at-least-once delivery all mean the same message can reach your handler twice. A server that resends unacknowledged fills after a reconnect is behaving correctly. Your handler is what turns that correct behavior into a bug:

// Applies the fill every time it is delivered
socket.on('fill', (fill) => {
  positions[fill.symbol] += fill.qty;
});
Enter fullscreen mode Exit fullscreen mode

If fill #4821 arrives twice, the position is doubled for that fill. No error is raised, and the number on the screen is simply wrong.

Exceptions that escape your try/catch

A try/catch only covers the synchronous call stack that is running when it executes. A callback that fires later runs on a fresh stack, and the block you wrapped around the registration has already exited:

try {
  setTimeout(() => {
    JSON.parse(badPayload); // throws later, on a different call stack
  }, 0);
} catch (err) {
  // never runs: the callback executes after this block is gone
}
Enter fullscreen mode Exit fullscreen mode

What happens next depends on the receiver. In Node's EventEmitter, a listener that throws stops the remaining listeners from running and propagates out of emit(). In the browser, an exception in a DOM event listener is reported to window.onerror, and the other listeners still run. Third-party code sitting between you and the throw may be left half-updated. You don't control any of this, which is the point.

Races between callbacks that share state

This is the failure from the opening. Two independent callbacks write to the same object, and arrival order decides the outcome:

let positions = {};

// Callback 1: live fills from the socket
socket.on('fill', (fill) => {
  positions[fill.symbol] = (positions[fill.symbol] ?? 0) + fill.qty;
  render(positions);
});

// Callback 2: full snapshot after a reconnect
fetchSnapshot((snapshot) => {
  positions = snapshot.positions; // overwrites any fills that arrived while the request was in flight
  render(positions);
});
Enter fullscreen mode Exit fullscreen mode

If three fills arrive while the snapshot request is in flight, the snapshot callback replaces positions with data that predates them. The fills are lost, and nothing logs it. Both callbacks are individually correct. The bug exists only in the interleaving, and the interleaving is set by the network.

(Anonymous callbacks that can't be removed and closures that capture stale state are separate callback problems. They were covered earlier in this series, in The Lexical Illusion and The Stale State Tax.)

The fix: three patterns for taking control back

Guard the boundary: at-most-once, idempotent, and error-contained.
Treat every callback you hand to external code as untrusted input at the boundary. Three small guards cover most of the damage.

For a callback that must fire at most once, such as a completion handler:

function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (called) return result;
    called = true;
    result = fn.apply(this, args);
    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode

For a stream where duplicates are possible, make the handler idempotent by keying on an ID:

const processed = new Set();

function onFill(fill) {
  if (processed.has(fill.id)) return; // duplicate delivery: ignore
  processed.add(fill.id);
  store.dispatch({ ...fill, type: 'FILL' });
}
Enter fullscreen mode Exit fullscreen mode

Keep that set bounded, for example, a sliding window of recent IDs, or it becomes the next memory problem (see The Allocation Tax). To contain exceptions, wrap the handler before you register it:

function safe(handler, onError) {
  return (...args) => {
    try {
      const result = handler(...args);
      if (result && typeof result.catch === 'function') {
        result.catch(onError); // async handlers fail through a rejected promise
      }
    } catch (err) {
      onError(err);
    }
  };
}

socket.on('fill', safe(onFill, reportError));
Enter fullscreen mode Exit fullscreen mode

The wrapper means a throwing handler can no longer damage the receiver, because the error is handled before it crosses back over the boundary.

Callbacks dispatch events; one reducer decides.

The race in the trading dashboard disappears once callbacks stop mutating shared state and only report what happened. A single reducer then applies events in the order it receives them:

const initialState = { seq: 0, positions: {} };

function reducer(state, action) {
  switch (action.type) {
    case 'SNAPSHOT':
      if (action.seq < state.seq) return state; // older than what we already have
      return { seq: action.seq, positions: action.positions };

    case 'FILL': {
      if (action.seq <= state.seq) return state; // stale or duplicate: ignore
      const current = state.positions[action.symbol] ?? 0;
      return {
        seq: action.seq,
        positions: { ...state.positions, [action.symbol]: current + action.qty },
      };
    }

    default:
      return state;
  }
}

socket.on('fill', safe((fill) => store.dispatch({ ...fill, type: 'FILL' }), reportError));
fetchSnapshot().then((snap) => store.dispatch({ ...snap, type: 'SNAPSHOT' }));
Enter fullscreen mode Exit fullscreen mode

Now a late snapshot can't erase newer fills, because both carry a sequence number, and the reducer is the only place state changes. Every transition goes through one function you can log, replay, and unit-test. One caveat: this handles duplicates and stale updates. If your feed can have gaps, with sequence 102 arriving before 101, you also need to buffer out-of-order events or ask the server to replay what was missed.

Prefer async iterators for high-frequency streams

Raw listeners fire whenever the source decides to. An async iterator inverts that back: the consumer asks for the next event when it's ready, so events are handled strictly one at a time, in order, inside a plain for await loop that your normal control flow and error handling can wrap.

function toAsyncIterable(subscribe, { maxBuffer = 100 } = {}) {
  const buffer = [];
  let pending = null; // resolver for a waiting consumer
  let closed = false;

  const unsubscribe = subscribe((event) => {
    if (closed) return;
    if (pending) {
      pending({ value: event, done: false });
      pending = null;
    } else {
      if (buffer.length >= maxBuffer) buffer.shift(); // drop oldest under pressure
      buffer.push(event);
    }
  });

  return {
    [Symbol.asyncIterator]() { return this; },
    next() {
      if (buffer.length) return Promise.resolve({ value: buffer.shift(), done: false });
      if (closed) return Promise.resolve({ value: undefined, done: true });
      return new Promise((resolve) => { pending = resolve; });
    },
    return() {
      closed = true;
      unsubscribe();
      if (pending) pending({ value: undefined, done: true });
      pending = null;
      return Promise.resolve({ value: undefined, done: true });
    },
  };
}

const ticks = toAsyncIterable((cb) => {
  socket.on('tick', cb);
  return () => socket.off('tick', cb);
});

for await (const tick of ticks) {
  store.dispatch({ ...tick, type: 'TICK' }); // consumed one at a time, at your pace
}
Enter fullscreen mode Exit fullscreen mode

Be precise about what this buys you. A WebSocket pushes whether or not you're ready, so the iterator can't slow the sender down. What it gives you is sequential consumption, a bounded buffer with an explicit drop policy, and a clean unsubscribe when the loop exits, including through break or an exception. True backpressure, where the producer is slowed, needs a pull-based source such as a ReadableStream or a fetch response body, covered in The Era of Dependency Deletion.

Key takeaway

Callbacks are the foundation of JavaScript's functional nature, and nothing here is an argument against them. The argument is against handing off execution authority without safeguards. Every callback you pass to a library, an event stream, or a wrapper is a decision to let someone else control call count, timing, and error routing for your code. Most engineers make that decision without noticing.

The senior habit is to treat that handoff as a boundary. Guard it so duplicates and exceptions stop there. Route what comes through it into one place that owns ordering. Use pull-based consumption where the source allows it. Do that, and the order your state changes in no longer depends on which network packet arrived first.

What to audit this week

# Callbacks registered with external systems: check each one for guards and for direct state mutation
grep -rn "\.on(\|addEventListener(\|\.subscribe(" src/

# try/catch blocks that wrap async registration (they usually don't protect the callback itself)
grep -rn -A6 "try {" src/ | grep -E "setTimeout|\.on\(|\.subscribe\("

# Module-level mutable state that callbacks may be writing to concurrently
grep -rn "^let \|^var " src/ --include="*.ts" --include="*.tsx"
Enter fullscreen mode Exit fullscreen mode

For each hit in the first search, ask three questions. What happens if this runs twice? What happens if it throws? What happens if it runs before the callback registered next to it? If you can't answer all three from the code alone, that callback is a candidate for the boundary pattern above.

Top comments (0)