Mailboxes
Este conteúdo não está disponível em sua língua ainda.
Each actor has exactly one mailbox — a FIFO queue of envelopes
waiting to be processed. When you call ref.tell(message), the
framework wraps message in an envelope (with sender, log-context, and
optional trace context) and enqueues it on the recipient’s mailbox.
The dispatcher pulls the next envelope, hands it to the actor’s
onReceive, and waits for that to finish before pulling the next
one.
That gives every actor the “one message at a time” guarantee — and the mailbox is the thing that makes that physically true.
The default mailbox
Section titled “The default mailbox”If you don’t configure anything, the actor gets an unbounded FIFO mailbox. Nothing is ever discarded on the way in; the queue grows until the actor drains it, and the heap is the only ceiling.
Why unbounded? Because the alternative is worse in a way that is easy
to miss. Between v0.10 and v0.15 the default was bounded — 10 000
messages, drop-head — and the framework silently discarded the
oldest queued message whenever an actor fell behind. The trade was
supposed to be “lose some messages, gain a memory ceiling”, and it did
not hold up:
-
The ceiling was not real. Only the user queue was bounded. System messages — lifecycle, supervision, watch — were never capped, so a node could still exhaust its heap.
-
A mailbox cannot tell what it is discarding.
drop-headsuits telemetry, where the freshest reading is the only one that matters. It does not suit a delivery confirmation or a WebSocketclose— and those went through the same queue. Each of those turned into a filed defect.Three messages are now out of every policy’s reach: the death-watch
Terminated, the command that spawns a WebSocket connection’s actor, and that connection’s ownclose. All three take a lane no bound can shed (see Death watch and A mailbox of your own below). The test they pass is that each is sent once with nothing left to re-send it from, and that losing one costs you not a message but a piece of state outside the mailbox that nothing else will correct — a watcher that thinks a dead actor is alive, an upgraded socket nobody attached to, a peer you decided to disconnect and did not. The rest is still application traffic, and only you know which of it is safe to lose.
So the loss is now something you ask for — per actor at the spawn site,
per path from configuration through an actor-ts.deployment entry, or
once for a whole deployment through
actor-ts.mailbox.default.capacity, which bounds every actor your
application wrote — sharded entities and cluster singletons included,
even though the framework spawns those — and leaves the framework’s own
actors alone.
That key ships as 0, meaning off, and turning it on is the same
decision as bounding one actor, taken for all of them at once: see
Mailbox sizing for what it does
and does not reach.
The growth, meanwhile, is something you are told about: an actor whose queue reaches 10 000
messages logs a warning, and again at each doubling. With metrics
enabled, actor_mailbox_size reports the depth per actor above that
mark, and actor_mailbox_depth reports the whole distribution below it —
so a burst that never reaches the warning threshold is still visible.
A queue with no ceiling has to stay cheap when it is deep, so both of a
mailbox’s queues are backed by a RingBuffer
rather than a plain array: taking the next message advances an index instead
of reindexing everything behind it, so the cost of delivering one message
does not grow with the backlog waiting behind it. This is invisible from
the outside — including to a Mailbox subclass of your own, which sees only
the methods.
When to bound a mailbox
Section titled “When to bound a mailbox”Reach for a bound when shedding load is better than absorbing it, and you can say which messages are safe to lose:
- A telemetry or sensor sink where only the newest reading matters.
drop-headkeeps the queue fresh. - An admission point in front of an expensive pipeline, where you
would rather refuse work than queue it.
drop-newkeeps what you already accepted,rejecttells the sender to back off. - Any actor exposed to a producer you do not control, where an unbounded queue is a denial-of-service surface. Read the third bullet with the first two: it says where a bound is worth considering, not that the traffic there is expendable. A WebSocket hub is the clearest case of both at once — see Bounding the hub’s mailbox for what a bound there does and does not cost.
import { ActorOptions } from 'actor-ts';
const sensorOptions = ActorOptions.create() .withMailboxCapacity(10_000) .withMailboxOverflow('drop-head');
system.spawn(SensorSink, 'sensors', sensorOptions);Setting a capacity is what creates the bound; withMailboxOverflow
decides which message is lost, and defaults to drop-head. Setting a
policy without a capacity is rejected rather than silently ignored — an
unbounded mailbox never overflows, so it would have nothing to do. That
rejection stands even where configuration supplies a bound —
actor-ts.mailbox.default.capacity or a deployment entry: the validator
runs at the spawn call and knows nothing about the system the actor will
be spawned into, so restate the capacity alongside the policy when you
mean to reshape a configured bound for one actor.
Both fields have two config layers under them: the
actor-ts.deployment
entry matching the actor’s path, with its mailbox-capacity and
mailbox-overflow, and under that actor-ts.mailbox.default.capacity
and .overflow. The spawn site always wins; the entry decides for the
paths it names, and the block for every other actor that said nothing.
The three policies and how to choose between them are covered under
BoundedMailbox below — including why reject fails
the sender rather than the slow actor.
Drops from a capacity you set are counted by
actor_mailbox_dropped_total, labelled with the actor’s class and the
policy that fired. Per class, not per actor: shedding is what a bounded
mailbox is for, so a per-actor label would mint a permanent metric
series for every actor behaving exactly as designed. To see which
instance is shedding, add an onDrop of your own — it runs alongside the
stock counter rather than replacing it, and it is handed the envelope that
was discarded, so it can say what was lost and not only that something
was.
To keep that envelope rather than inspect it in passing, build the mailbox
with deadLetterDrops: true and each dropped message becomes a
dead letter with its sender intact. It is
off by default, and only reachable from a mailbox you construct yourself:
the drop runs on the sender’s stack, so routing every shed envelope is
work charged to exactly the burst the bound was meant to absorb cheaply.
See mailbox sizing.
Bringing your own mailbox
Section titled “Bringing your own mailbox”withMailbox replaces the queue outright — for a PriorityMailbox, a
ControlAwareMailbox, a BoundedMailbox configured beyond what the two
options above express, or a subclass of your own:
import { ActorOptions, PriorityMailbox } from 'actor-ts';
const triageOptions = ActorOptions.create() .withMailbox(() => new PriorityMailbox({ priorityFor: (m) => m.urgency }));
system.spawn(Triage, 'triage', triageOptions);The mailbox is yours, but its drops are still counted: the cell registers
an observer on whatever you return, provided it implements
DropReportingMailbox — BoundedMailbox does, and a Mailbox subclass of
your own can by adding one method:
import { Mailbox, type Envelope, type MailboxDropObserver } from 'actor-ts';
class SheddingMailbox<T> extends Mailbox<T> { private readonly observers: Array<MailboxDropObserver<T>> = []; readonly deadLetterDrops = true;
observeDrops(observer: MailboxDropObserver<T>): void { this.observers.push(observer); }
override enqueue(envelope: Envelope<T>): void { if (this.shouldShed()) { for (const observer of this.observers) observer('drop-new', envelope); return; } super.enqueue(envelope); }}A report carries the envelope as well as the reason, and deadLetterDrops
says whether the cell should turn each one into a
dead letter. Hand over the envelope you
actually discarded — under a drop-head-shaped policy that is the one you
evicted, not the one that arrived, or every letter will name a message that
is still queued. Both are optional: omit the field and the drop is counted
and nothing more, which is what BoundedMailbox does unless you ask
otherwise.
Registration is additive, so a BoundedMailboxOptions.onDrop of your own
keeps firing alongside the stock counter. What you cannot do is combine
withMailbox with withMailboxCapacity — that is a configuration error
rather than a silent precedence rule.
One obligation: enqueueSignal
Section titled “One obligation: enqueueSignal”A queue that sheds has a short list of things it must not shed: the four
envelopes the framework sends exactly once, with nothing left to send them
again from. A death-watch Terminated — see
Death watch — comes straight from the dying
actor for a local death, and after one hop on the system queue for a death
another node reported; a WebSocket hub gets the command that spawns a
connection’s actor; a connection’s actor gets its own close; and an
actor subscribed to a DistributedData key
gets the DistributedDataChanged that tells it the key’s latest value.
All of them arrive through enqueueSignal rather than enqueue, and the
contract is queue it whatever your bound says:
class SheddingMailbox<T> extends Mailbox<T> { // ...as above...
/** Past the bound, deliberately: this one cannot be re-sent. */ override enqueueSignal(envelope: Envelope<T>): void { super.enqueue(envelope); }}The base implementation delegates to your enqueue, which is correct for
a queue that discards nothing and wrong for one that does — so override
it whenever you override enqueue to shed. BoundedMailbox,
PriorityMailbox and ControlAwareMailbox already do. Delegating rather
than writing straight to the base queue is deliberate: a subclass may keep
its messages somewhere else entirely, and an envelope hidden in a store
your dequeueUser never reads is worse than one you dropped.
The envelope also carries undroppable: true, which removeOldest reads
— so a drop-head-shaped bound built on that seam steps over it for
free, and does not have to know why. If your enqueue throws instead,
the framework turns the refusal into a
dead letter and the dying actor’s teardown
continues; what it cannot do is invent a second copy of the
notification. A refused DistributedDataChanged is logged by the
replicator instead, and the next change to the key tries again.
The DistributedDataChanged is the newest of the four, and it is on the
list for the reason the others are rather than for its subject. The
replicator keeps at most one notification per subscriber and key in
flight: while one waits in your queue, later changes overwrite its value
in place, and the next one is posted only once your actor has been handed
it. Shed it, and it is never handed over — the replicator goes on
waiting, every later change lands in a message nobody reads, and the actor
is not told about that key again. What it costs your bound is at most one
envelope per subscribed key, and it keeps its place at the tail while its
value is overwritten.
Undroppable is not queue-jumping. The door decides that a signal
survives your bound, never where it lands: queue it where you would queue
any other message, which on a FIFO queue is the tail. Two of the four
depend on that — death watch promises that everything already told to the
watcher is handled before the Terminated, and a reply queued before a
WebSocket close() is written before the socket shuts. A queue that
orders messages by its own rule orders signals by the same rule:
PriorityMailbox ranks a Terminated with your priorityFor. And a
queue that should let some messages overtake the rest says so by
classifying them, the way ControlAwareMailbox
does — never by moving whatever came through this door to the front.
System messages always come first
Section titled “System messages always come first”Inside every mailbox, two queues live side-by-side: user messages
(your tells) and system messages (lifecycle signals — create,
terminate, failure, watch, …). System messages have absolute
precedence: even if 10 000 user messages are queued, the next
stop signal or supervisor failure is processed before any of
them.
This matters because:
- Calling
ref.stop()does not jump the queue — under the hood it’s a user message (PoisonPill), so the actor first drains the user messages already queued ahead of it, then stops (a graceful drain-then-stop). Only framework-emitted system messages get the absolute precedence above. - A failing actor’s supervisor decision (Restart / Resume / Stop) takes effect immediately, not after the queue clears.
- A death-watch
Terminatedis a user message too, for the same reasonPoisonPillis: it must arrive after everything already told to the watcher, so a handler that reacts to a death sees the work that preceded it. Undroppable is not the same as queue-jumping — it keeps its place in line and merely cannot be discarded from it. That holds for every signal the framework sends that way, not for this one alone: a message overtakes the user queue only on a mailbox that classifies messages, likeControlAwareMailbox, and only when its predicate says so — yours, or on a WebSocket hub the framework’s.
A mailbox capacity bounds the user queue only. The system queue is
never capped — not by BoundedMailbox, not by a mailbox of your own —
because supervision and lifecycle signals must never be dropped. Its
depth is bounded by what produces them instead: one create per actor
and one terminate per stop, one childTerminated per child that
finishes stopping, one failure per supervision decision plus the
suspend / resume / recreate that decision fans out over the
failing subtree, one receiveTimeout per armed timer that expires, and
one watchNotify per Terminated that arrives from another node — a
remote actor this node’s own actors watched, or a node they held
watches into that left the cluster. Every one of those was paid for by
an actor that had to exist first, or by a watch one of them registered.
A local death notification is not on that list. A watched actor’s
Terminated goes onto its watcher’s user queue — past the bound, as
above, but still behind everything already told to that watcher — so
watching a thousand local actors adds nothing to the system queue at
all. A Terminated reported by another node takes one system-queue
hop to become that same user-queue signal; a peer can send at most one
per watch this node opened, and an unsolicited one matches nothing.
You don’t normally see this distinction — system messages are emitted by the framework, not by your code. But understanding it explains why “supervision reacts instantly.”
BoundedMailbox
Section titled “BoundedMailbox”import { ActorOptions, Actor, ActorSystem, BoundedMailbox } from 'actor-ts';
class SlowConsumer extends Actor<{ kind: 'work'; n: number }> { override async onReceive(message: { kind: 'work'; n: number }): Promise<void> { await new Promise(r => setTimeout(r, 100)); // simulate slow work this.log.info(`processed ${message.n}`); }}
const system = ActorSystem.create('demo');
const consumerOptions = ActorOptions.create() .withMailbox(() => new BoundedMailbox({ capacity: 1_000, overflow: 'drop-head' }));
const consumer = system.spawn(SlowConsumer, 'consumer', consumerOptions);The mailbox here holds up to 1 000 user messages. When a 1 001st message arrives, the overflow policy decides what happens.
Three policies:
| Policy | What happens on overflow |
|---|---|
'drop-head' | Dequeue the oldest message in the queue, discard it, enqueue the new one. Newest messages always make it in. |
'drop-new' | Discard the incoming message. The old queue is preserved unchanged. |
'reject' | Throw MailboxFullError at the tell site. Caller surfaces the backpressure. |
Which one you get when you name none depends on which door you came
through, and the difference is deliberate: constructing a
BoundedMailbox yourself defaults to reject, because you built a
bound and nothing else can be assumed about what is safe to lose.
withMailboxOverflow defaults to drop-head, the policy that suits
the workloads people actually reach for a bound to protect. Name the
policy either way and the question does not arise.
The options are validated at construction: a missing or non-positive
capacity and an unknown overflow policy throw OptionsError.
capacity bounds the messages the mailbox is allowed to discard, which
in a mailbox holding nothing but undelivered death notifications means the
queue sits above it rather than losing one. The overshoot is bounded by
how many actors this one watches — and by how many DistributedData keys
it subscribes to, one notification each — and it is the price of the
exemption Death watch describes: size a
capacity for your traffic, not to the byte.
Picking between them is a backpressure-vs-loss trade-off:
drop-head= “freshest wins.” Right for telemetry, sensor data, status pings — where stale messages are worthless and the latest snapshot is the only thing that matters.drop-new= “first wins.” Right for command-streams where re-ordering is unacceptable and dropping a late arrival is OK.reject= “let the sender deal with it.” Right when the sender has a meaningful backoff response (retry, route to a different actor, return 503 from an HTTP handler).
droppedCount on the mailbox instance tracks how many messages
have been discarded — useful to wire into a metrics gauge so you
notice when the bound is hit.
PriorityMailbox
Section titled “PriorityMailbox”import { ActorOptions, Actor, ActorSystem, PriorityMailbox } from 'actor-ts';
type Message = | { readonly kind: 'urgent'; readonly text: string } | { readonly kind: 'normal'; readonly text: string } | { readonly kind: 'bulk'; readonly text: string };
class Worker extends Actor<Message> { override onReceive(message: Message): void { this.log.info(`[${message.kind}] ${message.text}`); }}
const workerOptions = ActorOptions.create<Message>() .withMailbox(() => new PriorityMailbox<Message>({ priorityFor: (message) => message.kind === 'urgent' ? 0 : message.kind === 'normal' ? 5 : 10, }));
const worker = system.spawn(Worker, 'worker', workerOptions);
worker.tell({ kind: 'bulk', text: 'batch import row 1' });worker.tell({ kind: 'normal', text: 'user login' });worker.tell({ kind: 'urgent', text: 'page-out: disk full' });// → processed order: urgent → normal → bulkThe priorityFor callback runs at enqueue time, computing a
numeric priority per message. Lower numbers go first (priority
0 is highest), and ties break by FIFO insertion order — so two
'normal' messages stay in send-order relative to each other.
Common shapes for priorityFor:
- Per-
kindconstant table — like the example above. Easy to read, easy to evolve. - Field-derived —
priorityFor: (m) => m.deadlineMsmakes earliest-deadline messages run first. Works because both axes are “lower = sooner.” - Caller-tagged — sender includes
priority: numberin the message andpriorityForjust reads it. Sometimes the right call; usually a smell that the recipient should derive priority from message content instead.
When priorityFor cannot answer
Section titled “When priorityFor cannot answer”Your callback does not have to be total. If it throws, or if it
answers with something that is not a usable number — undefined, NaN,
a value of another type — the message is queued at the lowest
priority and nothing else happens. It is not dropped and the failure
does not surface at the tell site.
Both halves matter:
- Lowest, not highest. A priority that could not be determined must not outrank one that was stated. Ties still break by FIFO, so unrankable messages stay in send-order relative to each other.
- Contained, not thrown.
priorityForruns synchronously inside the sender’stell. A sender is a bystander to the receiver’s mailbox configuration: it has nothing to do about a brokenpriorityForand no way to tell that from a failure of its own. An escaping throw landed in the sender’sonReceiveand got the sender restarted — the same confusion therejectcaution above describes, for a bug that has nothing to do with the sender at all.
±Infinity is a ranking, not a failure: -Infinity means “ahead of
everything”, +Infinity means “behind everything”, and both are ordered
as written. Only NaN and non-numbers count as undeterminable.
To see a contained failure rather than only its consequences, pass
onPriorityError. Nothing else in the system reports one — the message
still arrives, just last:
import { PriorityMailbox, PriorityMailboxOptions } from 'actor-ts';
const triageOptions = PriorityMailboxOptions.create<Message>() .withPriorityFor((message) => message.kind === 'urgent' ? 0 : 10) .withOnPriorityError((cause, message) => { log.warn(`priorityFor could not rank ${JSON.stringify(message)}: ${String(cause)}`); });
const mailbox = new PriorityMailbox<Message>(triageOptions);cause is whatever priorityFor threw, or a TypeError describing the
value it returned. Record and return from the hook: it runs on the
sender’s stack too, so a throw from inside it puts the escape back — and
costs the message its place in the queue.
The current implementation uses a sorted-insertion array — O(log n) locate + O(n) splice on each enqueue. Fine for mailboxes that stay in the low thousands; if you have a sustained 10 000-message backlog where priority insertion shows up in profiles, the mailbox is open to a heap-backed swap (see the source).
Bounding a priority mailbox
Section titled “Bounding a priority mailbox”A priority mailbox is unbounded unless you give it a capacity, exactly
like every other mailbox. The bound lives on the mailbox’s own options
rather than on ActorOptions, because withMailbox and
withMailboxCapacity cannot be combined — a supplied mailbox brings its
own bound:
import { ActorOptions, PriorityMailbox, PriorityMailboxOptions } from 'actor-ts';
const triageOptions = PriorityMailboxOptions.create<Message>() .withPriorityFor((message) => message.kind === 'urgent' ? 0 : 10) .withCapacity(10_000) .withOverflow('drop-lowest-priority');
const workerOptions = ActorOptions.create<Message>() .withMailbox(() => new PriorityMailbox<Message>(triageOptions));The policies are 'drop-lowest-priority', 'drop-new' and 'reject', and
reject is what you get when you name a capacity without one — naming a
capacity says how much you will hold, not what you are willing to lose.
| Policy | What happens on overflow |
|---|---|
'drop-lowest-priority' | Discard the message furthest from delivery — the lowest-priority one, and among equals the one that arrived last. The arriving message competes on the same terms, so a message ranked below the whole backlog is the one that goes. |
'drop-new' | Discard the incoming message, whatever priority it was given. |
'reject' | Throw MailboxFullError at the tell site. |
drop-head is deliberately not offered here. On a FIFO queue it means
“discard the stalest”, which works because arrival order is the only order
there is. On a priority queue the head is the message your priorityFor
called most important — dropping it would defeat the reason you chose this
mailbox. Drops are still reported as drop-head on
actor_mailbox_dropped_total (that label has a closed two-value
vocabulary), except when the discarded message was the arriving one, which
reports drop-new.
The options are validated at construction: a missing or non-callable
priorityFor, a non-positive capacity, an unknown policy, or a policy
without a capacity all throw OptionsError. What the callback returns
is a runtime question and is handled at the enqueue instead — see
When priorityFor cannot answer. On a
bounded mailbox the two meet: an unrankable message is the least important
thing in the queue, so under drop-lowest-priority it is the arrival that
gets shed, reported as drop-new.
ControlAwareMailbox
Section titled “ControlAwareMailbox”import { Actor, ActorOptions, ActorSystem, ControlAwareMailbox, ControlAwareMailboxOptions } from 'actor-ts';
type PauseCommand = { readonly kind: 'pause' };type ResumeCommand = { readonly kind: 'resume' };type ReadingCommand = { readonly kind: 'reading'; readonly value: number };type IngestCommand = PauseCommand | ResumeCommand | ReadingCommand;
class Ingest extends Actor<IngestCommand> { override onReceive(command: IngestCommand): void { this.log.info(`handled ${command.kind}`); }}
// Name the control kinds rather than excluding the rest — see the cautions below.const isControl = (command: IngestCommand): boolean => command.kind === 'pause' || command.kind === 'resume';
const ingestMailboxOptions = ControlAwareMailboxOptions.create<IngestCommand>() .withIsControl(isControl) .withCapacity(10_000) .withOverflow('drop-head');
const newIngestMailbox = () => new ControlAwareMailbox<IngestCommand>(ingestMailboxOptions);const ingestOptions = ActorOptions.create<IngestCommand>().withMailbox(newIngestMailbox);
const system = ActorSystem.create('demo');const ingest = system.spawn(Ingest, 'ingest', ingestOptions);
ingest.tell({ kind: 'reading', value: 1 });ingest.tell({ kind: 'reading', value: 2 });ingest.tell({ kind: 'pause' });// → handled order: pause → reading → readingA ControlAwareMailbox keeps two FIFO queues and hands the actor every
control message before any ordinary one, arrival order kept inside
each. The predicate you pass as isControl decides which is which, once
per message, as it arrives. Nothing else changes: system messages still
come first, and the framework classifies messages as control on its own
for one actor only — the WebSocket hub, below.
Reach for it when a few kinds of message must not wait behind a backlog of
the rest — a pause or a reconfiguration in front of a flood of readings, an
administrative command in front of a stream of data. Where you want a
whole ordering by importance rather than two classes, a PriorityMailbox
is the tool; where everything has to stay in the order it was sent, use
neither.
The WebSocket hub has one by default
Section titled “The WebSocket hub has one by default”A WebsocketServerActor
gets a ControlAwareMailbox without being asked, unless it is spawned with
a mailbox of its own. Its control messages are the command that hands it
an upgraded socket and the onClientConnected signal the new connection
reports; frames, disconnects and your own messages to the hub stay
ordinary. A new connection is therefore set up ahead of every other
connection’s backlog and is never shed by a bound, while the order per
connection — connected, messages, disconnected — stays as it was. A
capacity the hub would otherwise have had, from withMailboxCapacity(), an
actor-ts.deployment entry for its path or
actor-ts.mailbox.default.capacity, becomes the capacity of the ordinary
class. withMailbox(...) replaces the queue, and the control lane with
it.
Bounding a control-aware mailbox
Section titled “Bounding a control-aware mailbox”A capacity bounds the ordinary class only, and the three
BoundedMailbox policies — 'drop-head', 'drop-new', 'reject' — act
on it alone. A control message is never shed, never refused, never
counted as a drop and never makes reject throw: the flood a bound sheds
is the traffic the control message is there to overtake. So the capacity
is a ceiling on the ordinary class, and the control class is bounded by
whatever sends it — which is one more reason to keep the predicate to the
few kinds that need to overtake. Named without a policy, a capacity means
reject, as on every mailbox you construct yourself.
unstashAll() puts each message back at the head of its own class, and
the ordinary half meets the bound the way a BoundedMailbox replay does.
Drops reach actor_mailbox_dropped_total and your onDrop, and
deadLetterDrops: true turns each one into a
dead letter.
The options are validated at construction: a missing or non-callable
isControl, a non-positive capacity, an unknown policy, and a policy or
deadLetterDrops without a capacity all throw OptionsError.
When isControl cannot answer
Section titled “When isControl cannot answer”isControl runs inside the sender’s tell, so it is contained the
same way priorityFor is: if it throws, or answers anything but true,
the message is ordinary and the tell goes through. Ordinary is not only
the safe answer but the right one — it is the class the message would have
had on any other mailbox.
Contained is not silent. A predicate that throws on every message — a
method handed over without its instance is the usual one — turns the
mailbox into a plain FIFO queue while every message still arrives, so the
mailbox logs the first throw at warn. Once per mailbox, because the
predicate runs on every tell; and by class only — the class of the
message it threw on and of what it threw, never the message or the error’s
text, since an exhaustive matcher’s error quotes the value it could not
match. To see each throw, or to send it to your own logger, pass
onControlError:
const ingestMailboxOptions = ControlAwareMailboxOptions.create<IngestCommand>() .withIsControl(isControl) .withOnControlError((cause) => { log.warn(`isControl threw: ${String(cause)}`); });cause is what the predicate threw. A hook you pass replaces the log
line, and the rule onPriorityError has holds here too: record and
return — it runs on the sender’s stack. An answer that is not true is
not a failure and never reaches the hook; it makes the message ordinary,
as above.
Per-actor mailbox via ActorOptions
Section titled “Per-actor mailbox via ActorOptions”Three knobs on ActorOptions:
import { ActorOptions, PriorityMailbox } from 'actor-ts';
// Bound the default FIFO, and say what a full one discards.const cappedOptions = ActorOptions.create() .withMailboxCapacity(500) .withMailboxOverflow('drop-new');
// Full custom factory — pick the type and configure it.const customOptions = ActorOptions.create() .withMailbox(() => new PriorityMailbox({ priorityFor: (m) => m.urgency }));withMailboxCapacity(n) turns the default FIFO into a bounded one;
withMailboxOverflow picks the policy, defaulting to drop-head. The
policy on its own is rejected — an unbounded mailbox never overflows, so
it would be a no-op that reads like configuration.
withMailbox(factory) is the general form — you return a brand-new
mailbox instance from the factory. The factory is called once per
actor instance (including on restart), so each restarted actor
gets a fresh empty mailbox-data-structure. It replaces the queue
rather than configuring it, so combining it with withMailboxCapacity
is a configuration error rather than a silent precedence rule, and the
framework wires no drop telemetry into whatever you return.
The default is unbounded: a bound is chosen per actor with these knobs,
or once for a whole deployment with actor-ts.mailbox.default.capacity,
which the spawn site’s own setting always overrides — see
Mailbox sizing for the actors it
reaches.
For an actor whose spawn site you cannot edit, the same two knobs exist
in configuration, per path: an
actor-ts.deployment
entry sets mailbox-capacity and mailbox-overflow (and throughput)
for the actors its key matches — "/user/ingest", the routees of
"/user/pool/routee-*", the connections of "/user/chat/ws-*". It sits
under the knobs above and over the global block: withMailboxCapacity
and withMailbox still win, an entry’s capacity wins over
actor-ts.mailbox.default.capacity, and its 0 leaves the matched actors
unbounded however the global block is set.
Mailboxes + stash
Section titled “Mailboxes + stash”When an actor calls this.context.stash() inside onReceive, the
current message is parked. When the actor later calls
unstashAll(), the parked messages are re-prepended to the front
of the mailbox.
This works the same way for every mailbox type — the framework
calls mailbox.prependUser(envs), and the mailbox decides how to
reinsert. Notably for PriorityMailbox, unstashed messages are
re-prioritized: a stashed bulk message rejoins the bulk tier,
even if you stashed it while urgent messages were arriving. Stash
order is preserved within a priority tier. A ControlAwareMailbox
puts each message back at the head of its own class, so a stashed
control message is still handed over before the ordinary ones.
A bound applies to the replay. Whichever bounded mailbox you
chose, unstashAll() is subject to the capacity and the overflow
policy you set — a replay is traffic re-entering the queue, not a
back door around it. What differs is only where the room comes
from: PriorityMailbox re-ranks, and BoundedMailbox puts the
replay at the head and sheds at the tail, so a full queue loses its
newest messages rather than the ones you deliberately parked; a
ControlAwareMailbox does the same over its ordinary class. Under
reject nothing is lost at all — unstashAll() throws
MailboxFullError, the whole batch stays stashed, and the failure
reaches your actor’s supervisor like any other. Size the capacity
for the backlog plus whatever you expect to stash, or accept the
drops as the price of the bound.
One exception, and it is the same one as everywhere else. An
envelope marked undroppable — a death-watch Terminated, a WebSocket
accept or close command, a DistributedData change notification — is
admitted past the bound on the way back in too. The marker travels on the envelope rather than being remembered
by the queue, precisely so it survives a context.stash() /
unstashAll() round trip: a bound gets one chance to shed a
notification, not a second one because the actor parked it first.
That is a claim about the bound, not about what the actor will
see. A Terminated parked under a plain watch is admitted here
and then refused by the dispatch, because the registration the death
consumed is the thing that would have admitted it — so it ends as a
dead letter rather than a second
delivery. Which is not the bound’s doing, and is exactly why the two
are worth keeping apart: a notification the bound shed never reaches
the dispatch at all, so it leaves no dead letter behind. See
Death watch for the registration that
does survive a stash — watchWith, whose domain message the death
watch has no further opinion about. The WebSocket accept and close
commands carry no such bookkeeping and are redelivered normally, and so
is a DistributedData change notification — the replicator stopped
overwriting it the moment the actor was first handed it, so it replays
with the value it had then.
See Become and stash for the full behavior-switching story.
When the mailbox choice matters
Section titled “When the mailbox choice matters”For most actors, the default unbounded FIFO is right. Reach for an alternative in four situations:
- Producer/consumer mismatch. The producer can emit faster than the consumer can drain. Bound the consumer’s mailbox; pick an overflow policy that matches the workload (drop-head for telemetry, reject for HTTP-driven backpressure).
- Latency budget per kind. Some messages must be handled in
tens of milliseconds (user-facing requests), others can wait
minutes (background reconciliation). Priority mailbox; the
urgent kind gets
0, the background kind gets100. - Memory bound. An actor with no application-level priority
distinction whose queue will grow without limit if it falls behind
— an audit-log subscriber during a spike, or anything fed by a
producer you do not control. Bound it at a number that matches your
memory budget;
drop-headif the latest events are most valuable,drop-newif the ones you already accepted are. Watchactor_mailbox_wait_secondsto find out whether you need this before you need it — it climbs as soon as an actor stops keeping up, whereactor_mailbox_sizeonly reports once a queue passes 10 000 messages.actor_mailbox_depth’s p99 is what to pick the number itself from: a capacity is a bet on the worst-case burst, and that histogram is the measurement of it. - A command stuck behind a backlog. A few kinds of message — a
pause, a reconfiguration, an administrative request — must not wait
behind a flood of everything else, and the rest has no ranking worth
paying a priority mailbox for.
ControlAwareMailbox; name those kinds in its predicate.
Where to next
Section titled “Where to next”- Dispatchers — the scheduler that pulls from the mailbox. Mailbox = the queue; dispatcher = when to drain it.
- Become and stash —
parking messages for later, restoring them via
unstashAll. - Actor —
onReceiveis what the mailbox delivers messages to. - Coordinated shutdown — what happens to pending mailbox messages during graceful shutdown.
The BoundedMailbox,
PriorityMailbox and
ControlAwareMailbox API
references cover the full settings shape.
