10 min read

Bots That Use Your Real API: A Reproducible Simulator for a Realtime App

Persona bots as state machines, a seeded RNG, a min-heap scheduler, events that only wake, and no blind retries: how to load-test a multi-user realtime app end to end.
cogs and gears
Photo by Tim Mossholder on Unsplash

Unit tests told me each endpoint of a multi-user realtime app worked. They did not tell me what happens when a dozen operators and a few hundred customers share one live queue for an afternoon: people joining, cancelling, not showing up, a desk dropping its connection mid-service. That is where the interesting bugs were, and I could not click through it by hand.

So I built a simulator: a crowd of bots, each playing a role, driving the product the way real users do. A few design rules turned out to matter far more than the bots' cleverness, and two bugs it surfaced were in the simulator itself. Both taught me something.

Rule one: bots use the real public API

The tempting shortcut is to write rows straight into the database. It is fast and you control everything. It also skips validation, permissions, rate limits, side effects and the realtime fan-out, which is to say most of the product.

My bots are just another client. They sign in the way users sign in, call the same endpoints the apps call, and listen on the same sockets. The simulator validates every response against the API's published schemas, so a response that no longer matches its contract shows up as an alert instead of a confusing bot failure three steps later. If a bot can do something, a user can do it too.

Rule two: each persona is a state machine

Each bot plays a role, such as an operator working a desk, a customer waiting in line or a manager watching the board, and each role is a small state machine. A turn always starts by reading the current state from the API, never by trusting what the bot remembers:

async function operatorTurn(bot: Bot, api: Api, rng: Rng): Promise<number> {
  const desk = await api.myDesk();        // re-read first, every turn
  bot.state = stateFrom(desk);

  switch (bot.state) {
    case "no_desk":
      await api.claimDesk();
      return rng.between(2_000, 5_000);  // ms until the next turn
    case "idle":
      if (rng.chance(bot.traits.breakChance)) {
        await api.goOnBreak();
        return rng.between(60_000, 300_000);
      }
      await api.callNext();
      return rng.lognormal(4_000, 0.5);
    case "serving":
      await api.finishCurrent();
      return rng.between(1_000, 3_000);
  }
}

The turn returns how long until the bot wants to act again. Traits like speed, patience and reliability change the weights, not the structure.

Rule three: a seeded RNG, forked by name

Every choice a bot makes comes from a seeded random stream, so a run can be replayed from its seed. The detail that matters: each bot's stream is derived from the run's seed and the bot's name, not from how many numbers were drawn before it.

const run = seeded("rush-scenario/42");
const c7 = run.fork("customer-7");  // same sequence whether created first or fortieth

Without this, adding one bot to a scenario reshuffles every other bot's behaviour, and "it only fails with seed 42" stops meaning anything. Given the same seed and the same answers from the API, a bot makes the same decisions. That is what lets a run's log become a test case.

Rule four: a min-heap decides who moves next

The scheduler is a min-heap of wake-ups ordered by time, with ties broken by insertion order. It pops the earliest bot, runs one turn, and pushes the bot back at whatever time the turn returned. The clock is injected: in a real run it is the wall clock (with think times compressed), and in unit tests it is a fake clock I advance by hand, so an hour of queue runs in milliseconds.

Two scheduler rules keep the load honest. A bot never has two turns in flight. And a turn that ended in a refusal holds the bot until its next scheduled wake, so a "no" from the server can never become a hot loop.

unsure? re-read Socket eventwake only, no state Schedulermin-heap of wakes Readcurrent state via API Decidestate machine + seeded RNG Actone write via API Reschedulepush next wake time

  1. Pop. The scheduler takes the bot with the earliest wake time off the heap and gives it one turn. Only one turn per bot is ever in flight.
  2. Read. The bot asks the API what is true right now. Whatever it remembered from last time is a hint at best.
  3. Decide. The persona's state machine picks a next move, weighted by its traits, using its own seeded random stream. Same seed and same answers give the same choice.
  4. Act. The bot makes one write through the public API, the same call a real user's app would make.
  5. Reschedule. The turn returns how long until the bot wants to act again, and the bot goes back into the heap at that time. After a refusal it waits for that wake, so a "no" never loops.
  6. Wake. A socket event for this bot only pulls its wake time earlier. It carries no state into the bot; the next turn still starts with a read.
  7. Unsure. If a write times out or the connection drops, the bot does not retry it blind. It reads again to learn whether the write happened.
One bot turn. Notice that nothing reaches the bot's state except a read from the API.

Rule five: socket events wake bots, they never change them

It is tempting to let a "you're up next" event flip the customer bot straight into a "called" state. Don't. Events arrive late, out of order, twice, or not at all after a reconnect. If they mutate bot state, the bot's view drifts from the server's and you end up debugging the simulator instead of the product.

Instead an event only moves the bot's next wake earlier, coalesced so a burst of ten events is one re-read, not ten. The turn that follows reads the API like any other turn. Real clients should work this way too, which is part of the point: if the product is only correct when every event arrives, the bots will find out.

Rule six: never blindly retry a write

"Call the next customer" is not idempotent. If the request times out, it may or may not have happened. Retrying it could skip a person. So the bots never retry a write whose outcome is unknown. They read and find out:

try {
  await api.callNext();
} catch (err) {
  if (!isUncertain(err)) throw err;   // a clear "no" is handled elsewhere
  bot.state = stateFrom(await api.myDesk());  // did it happen? ask, don't guess
}

A request that never reached the server, like a sign-in that failed with a connection error, is safe to retry a couple of times. A write that might have landed is not.

Rule seven: a catalogue test for coverage

The product keeps growing. A new state transition ships, nobody adds it to a persona, and the simulator quietly stops covering the product. To prevent that, I keep a catalogue: every transition and route is either simulated by some persona or listed as not simulated, with a reason. A test enumerates the product's own transition table and fails on anything in neither list.

test("every transition is simulated or explained", () => {
  for (const edge of productTransitions()) {
    expect(SIMULATED.has(edge) || edge in NOT_SIMULATED).toBe(true);
  }
});

"Later" is not an acceptable reason unless it says what it is waiting for. The test does not force anyone to write a bot. It makes leaving something out a deliberate decision someone wrote down.

Bug hunt one: the run that went to sleep

A long rush scenario finished with a tiny fraction of customers served. The logs showed bots going quiet for minutes, then resuming as if nothing happened. I spent a while suspecting a deadlock in the scheduler before I lined the gaps up against the operating system's power log. They matched to the second. The laptop had idled to sleep a couple of minutes into the run, woken briefly, and slept again.

Two fixes. First, a run keeps the machine awake: on macOS the runner holds caffeinate -i -w <pid> for the length of the run, tied to its own process so a crashed runner cannot leave the machine awake forever. Second, a run that sleeps anyway (closing the lid still wins) notices and stops itself, because heartbeats were missed and the results mean nothing. Detection is cheap. A monotonic clock usually stops counting while the machine is suspended, and the wall clock does not:

const wall0 = Date.now();
const mono0 = performance.now();

function sleptMs(): number {
  return (Date.now() - wall0) - (performance.now() - mono0);
}

if (sleptMs() >= 60_000) stopRun("sleep");

A threshold of a minute ignores small clock corrections. Check the behaviour on your own platform before relying on it.

Bug hunt two: hundreds of the same 404

An operator bot lost its connection for a couple of minutes. While it was gone, a server-side sweep did exactly what it should: it took the offline desk off shift and released it. When the bot came back, every "call next" got a 404, and the bot tried to resume its shift and call again, hundreds of times, about once a second, until the run ended. Each failure was forgiven as a single bad turn, so nothing escalated.

The bot's state machine assumed it still owned the desk. A 404 for something you hold is not an error to retry. It means the world changed. The fix was to make "no desk" a real state: on a 404 the bot re-reads, finds it has no desk, and goes back to claiming one, as a person would. A few refused restarts in a row also count as losing the desk, so this kind of loop cannot come back in another form.

Trade-offs

This is not cheap. Going through the real API means auth, rate limits and realistic pacing, so runs take real time and you need a quiet environment to run them in. Personas are rule-based, so they only explore what you thought to model, and the catalogue test helps but does not guarantee interesting behaviour. And the simulator is software: in my case both of the memorable bugs were in it, not in the product.

Takeaway

Make your bots behave like careful clients: read before acting, let events only wake them, never guess at an uncertain write, and treat "not found" as news rather than an error. A simulator built that way finds bugs in the product, and when it finds bugs in itself, they are usually the same mistakes a real client would make.