The pilot the whole stack migration was judged on — I built it solo, and every pattern I set became the template later services copied.
The design, in code
Representative snippet of the production design — rewritten for publication; not company source.
routing-score.ts
// One number encodes the whole routing policy — banded so each term
// owns an order of magnitude and can never outvote the one above it.
const score =
statusLevel * 1e18 + // status ▸ away sinks below every online agent
chatCount * 1e15 + // load ▸ fewer active chats ranks first
timestampMs; // waited-longest ▸ idle-since breaks the tie
// Every state change is one atomic increment — no read-modify-write race.
await redis.zincrby(QUEUE, +1e18, agentId); // agent steps away
await redis.zincrby(QUEUE, -1e18, agentId); // agent comes back online
// Assignment is O(1): the best agent is simply the head of the set.
const [next] = await redis.zrange(QUEUE, 0, 0);
agent-invite.ts
// Two messages in the same room, same millisecond, both want a human —
// without a fence, two agents get invited into one chat. First caller wins.
async function inviteAgent(roomId: string) {
const locked = await redis.set(
`agentRoomLock:${roomId}`, '1', { nx: true, px: 10_000 });
if (!locked) return; // someone else already took the room — walk away
const agent = await assignFromQueue(roomId);
await notify(agent, roomId); // TTL aligned to op: a crash can't lock forever
}
ai-race-guard.ts
// AI answering first means AI failing first. The model is a flaky
// dependency: race it against a timer, and on stall or error fall
// straight through to a human — the user never gets a spinner.
try {
const reply = await Promise.race([
askModel(message),
rejectAfter(10_000), // ten seconds, then it's a person's job
]);
return send(reply);
} catch {
return forceToAgent(message); // timeout OR error → human takeover
}