Skip to content

About

Allocates conversations across a pool of capacity-limited, ban-fragile messaging lines. Rendezvous hashing for thread stability, absence-based ban detection, warm-up ramps.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

Switchboard

Allocates conversations across a pool of capacity-limited, ban-fragile messaging lines.

Zero runtime dependencies · 93 tests · benchmark · spec · design


Why this exists

Platforms that give AI agents iMessage capability don't buy messages. They buy lines — each one a physical Mac mini running a dedicated Apple ID, at a flat monthly cost. Published rates run from $39/mo for a shared line to $195–289 for a dedicated outbound line, and reportedly past $1,000/mo at enterprise tiers. Self-operating costs $599–1,399 in hardware per line plus ongoing maintenance.

On top of that fixed cost sits a hard ceiling. Operators in the space report that roughly 100 messages/day per Apple ID is where ban risk starts climbing steeply, and that sustained 200+/day attracts enforcement within weeks. Hence the standing rule of thumb: to send 1,000 messages/day you need 10+ Apple IDs.

Two things follow, and together they are the entire problem:

  • An idle line is a total loss. You pay the same whether it sends zero messages or three thousand. A fleet at 40% utilisation wastes 60% of its cost of goods.
  • An over-used line is worse than a loss. A ban forfeits the line, the Apple ID, the phone number, the multi-day warm-up investment — and every conversation threaded through that number. That last part is a customer-visible outage, not an internal cost.

So gross margin on the channel is decided almost entirely by how well demand is packed into it. That's a scheduling problem with an unusual constraint set, and it's what this library solves.

On the numbers. These figures come from third-party operator reports and published price lists, not vendor SLAs. The ~100/day threshold in particular is directionally reliable and numerically uncertain. Every threshold in this system is therefore configuration, never a constant.

What makes it a hard scheduling problem

Existing schedulers assume things that aren't true here.

Assumption Why it fails for lines
Resources degrade under load, then recover A line is destroyed permanently by overuse
Work is fungible; re-homing is free A line carries a phone number a human recognises. Moving a conversation means a stranger's number appears mid-thread
A new resource is immediately usable at full rate A line is unusable at full rate until warmed over several days
Failure is reported A banned line accepts sends and goes quiet. There is no error

Kubernetes has quotas and taints, but nodes aren't annihilated for accepting too much work and pods don't have caller ID. Envoy's ring-hash balancers solve stickiness beautifully — for stateless backends where re-homing costs nothing. Neither models the resource this actually is.

Architecture

flowchart LR
    C["send(tenant, contact, body)"] --> E["Engine"]
    E --> AS["assign<br/>weighted rendezvous hashing"]
    E --> AD["admit<br/>quota + fair share + policy"]
    E --> DT["detect<br/>absence-based health"]
    E --> RH["rehome<br/>churn accounting"]
    E --> CO["cost<br/>largest-remainder allocation"]
    AS --> F[("Fleet state")]
    AD --> F
    DT --> F
    RH --> F
    E --> AP["ChannelAdapter (port)"]
    AP --> SIM["Simulated"]
    AP -.-> LIVE["Live (not built)"]
Loading

Every mechanism is a pure module, independently tested. The engine composes them and owns state. All I/O crosses one port. Nothing reads a clock or a random source — both are injected — which is what makes benchmark runs byte-reproducible.

Line lifecycle

stateDiagram-v2
    [*] --> warming
    warming --> healthy: ramp complete
    healthy --> cooling: daily quota spent
    cooling --> healthy: new day
    healthy --> quarantined: confirmations stopped
    warming --> quarantined: confirmations stopped
    quarantined --> warming: returned to service
    quarantined --> retired: removed
    healthy --> retired: removed
Loading

cooling (at quota, healthy) is deliberately a separate state from quarantined (failing). The first is the system working correctly; the second is it losing an asset. A dashboard that conflates them tells you nothing.

Results

Four allocators, one identical world — same traffic, fleet, quota, ban model, seed, and the same line deliberately removed on day 15. Only the allocation decision varies. Full setup and assumptions in BENCHMARK.md.

Steady state — warmed fleet, ~65% load, 30 days:

Allocator Delivered Bans Line switches …from line loss Avoidable churn
round-robin 39,000 0 33,508 98 33,410
least-loaded 39,000 0 33,481 98 33,383
sticky-mod-n 39,000 0 2,083 112 1,971
switchboard 39,000 0 125 125 0

Cold start — same traffic, fleet provisioned on day 0 so every line begins its ramp at 20/day:

Allocator Delivered Bans Lines left Overshoot sends
round-robin 39,000 0 19/20 0
least-loaded 39,000 0 19/20 0
sticky-mod-n 1,300 20 0/20 900
switchboard 39,000 0 19/20 0

What this shows, stated fairly

Throughput ties. On a warm fleet, every allocator delivers the same volume with zero bans. Switchboard is not faster and does not claim to be.

Continuity is where they separate. Round-robin and least-loaded pack volume perfectly and have no concept of a conversation, so nearly every message leaves from a different number — 33,000+ switches a human would experience as messages from strangers. Switchboard's 125 switches are exactly the 125 caused by the line that was removed. Zero avoidable churn, which is the property the design exists to produce.

Capacity-blindness is survivable warm and fatal cold. sticky-mod-n — hash the conversation, mod the fleet size, the obvious sticky implementation — holds up on a warm fleet with 16× worse churn. On a cold fleet it overshoots the ramp and loses all 20 lines, delivering 1,300 messages instead of 39,000.

The claim under test was never "faster." It's that each obvious approach sacrifices something, and only one holds capacity-awareness, conversation affinity, and bounded churn at once.

The three decisions that matter

Weighted rendezvous hashing, not consistent hashing or least-loaded. Each line's score depends only on itself and the conversation key, so removing a line moves only the conversations that were on it — two surviving lines never trade conversations. hash mod N fails exactly this: changing N reshuffles nearly everything. Weighting by remaining headroom biases new conversations toward capacity without disturbing existing ones.

Absence-based failure detection with three guards. A banned line produces no error, so health is inferred from confirmations that stop arriving. That's fragile in three specific ways, each closed deliberately: a minimum sample stops a low-traffic line being quarantined on two data points; a distinct-recipient requirement means one unreachable phone number can never quarantine a healthy line at any volume; and a fleet floor breaks the cascade where quarantines shrink the fleet, raising load on survivors, triggering more quarantines.

spill and rehome are different operations. When a conversation's line is out of budget, a spill sends from elsewhere once and leaves the assignment intact; a rehome changes it permanently. Conflating them is how a system quietly starts switching the number a human sees mid-thread. The default is defer — a message arriving late from the right number generally beats one arriving now from a stranger.

Usage

import { createSwitchboard, ManualClock, RecordingAdapter } from 'switchboard'

const sb = createSwitchboard({
  clock: new ManualClock(0),
  adapter: new RecordingAdapter(),
  config: {
    quota:  { safeDaily: 100, rampDays: 5, rampStart: 20 },
    health: {
      windowSize: 50,
      minSampleSends: 10,
      minDistinctRecipients: 5,
      minConfirmationRate: 0.5,
      minFleetSize: 3,
    },
    policy: { onQuotaExhausted: 'defer', tenantFairShare: 0.25 },
  },
})

sb.addLine({ id: 'line-01', monthlyCostCents: 19_500 })

const outcome = sb.send({ tenantId: 'acme', contact: '+15551234567', body: 'hello' })

if (outcome.status === 'sent') {
  // Confirmations are the health signal. Their absence is what detects a ban.
  sb.confirm(outcome.messageId)
}

sb.tick()                 // day roll, ramps, health evaluation
sb.metrics()              // utilisation, bans, churn, deferrals
sb.attributeCost(30)      // per-tenant share of fixed pool cost

SendOutcome is a discriminated union with no nullish success case, so a caller cannot reach lineId without handling the empty-fleet and all-quarantined branches. Those edge cases are type errors rather than runtime nulls.

What isn't built

Declared non-goals, not oversights — each is in requirements.md §4 with a reason:

  • No live adapter. The ChannelAdapter port is designed to be implementable from its type signature alone; only a simulated implementation ships.
  • No persistence. In-memory, single process.
  • No distributed quota accounting. Assignment is coordination-free by construction — any replica with the same fleet state derives the same answer — so the genuine scaling seam is the send counter, which would need an atomic store. That's the one distributed-systems problem this design defers, and it's named rather than hidden.
  • No channel fallback. This allocates within one channel's line pool. Falling back across iMessage/RCS/SMS is a different problem.
  • Proportional cost attribution only. Adequate and explicable; the interface leaves room for better when drivers are collinear.

Running it

npm install
npm run check         # typecheck + 93 tests
npm run bench         # regenerate the benchmark to stdout
npm run bench:write   # regenerate BENCHMARK.md

How it was built

Spec-driven, in five phases, with the artifacts committed as they were written:

  1. docs/requirements.md — 9 testable requirements, 6 non-goals, 11 edge cases
  2. docs/design.md — build-vs-adopt analysis, six decisions with alternatives, stress test
  3. docs/tasks.md — 16 tasks, each naming the requirement it satisfies
  4. Implementation, one task at a time
  5. Validation against the spec

The build-vs-adopt analysis concluded that every algorithm here is decades old and should be adopted rather than invented — rendezvous hashing, token buckets, rolling-window failure detection, largest-remainder allocation. What's built is the composition, because no existing scheduler models a resource that is permanently destroyed by overuse and carries a human-visible identity.

The benchmark is committed as produced. Success criterion 2 commits to publishing the numbers whether or not they flatter the design — and the first run of it was wrong in a way worth recording: the fleet was undersized, so every allocator saturated and utilisation was meaningless at 99.8% across the board, while sticky-mod-n destroyed itself on day one and never survived to demonstrate the churn failure that motivates the whole design. Fixing the experiment rather than the numbers is what produced the two scenarios above.

Licence

MIT

About

Allocates conversations across a pool of capacity-limited, ban-fragile messaging lines. Rendezvous hashing for thread stability, absence-based ban detection, warm-up ramps.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages