Skip to content

Commit edc37a0

Browse files
committed
wip(core): DispatchLoop wakes at the next due time and skips the ramp for a sole writer (#29919)
1 parent b7075d9 commit edc37a0

13 files changed

Lines changed: 437 additions & 37 deletions

File tree

‎packages/core/src/dispatch-loop.ts‎

Lines changed: 148 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,27 @@
3737
* for — a deferred row coming due, a row another process wrote, a crashed
3838
* node's claim passing its timeout: it is noticed within one backed-off
3939
* interval, never more than `maxIdleIntervalMs` after it became claimable.
40+
*
41+
* ## Waking at the next due time (#29919)
42+
*
43+
* Two of those three are not unknowable: a deferred row and a claim carry the
44+
* instant they become claimable. A loop given {@link DispatchLoopOptions.nextDueAt}
45+
* asks for the earliest such instant once, after the first empty tick of an
46+
* idle streak (after `start()`, after a tick that claimed work, after a wake,
47+
* and after the due time it was sleeping towards arrives), and never sleeps
48+
* past it: a deferred row goes out within one tick of coming due, whatever the
49+
* ceiling. The answer is remembered, not re-read on every ceiling tick, so an
50+
* idle loop's steady-state cost is unchanged; a deferred row written in this
51+
* process later in the streak reaches the loop through
52+
* {@link DispatchLoop.wakeAt} instead, at no read at all.
53+
*
54+
* Only the third case — a row another process wrote — is left to the backoff.
55+
* A host on which no other process writes the store (a hosted tenant kernel:
56+
* one kernel per tenant database) says so with
57+
* {@link DispatchLoopOptions.soleWriter}, and an empty tick then sleeps
58+
* straight to the next due time or the ceiling instead of re-running the
59+
* `intervalMs` ramp. Before #29919 every boot re-ran that ramp against empty
60+
* stores: five ticks in the first minute per loop, every one of them idle.
4061
*/
4162

4263
/** Default ceiling of the idle backoff, in ms — see {@link DispatchLoopOptions.maxIdleIntervalMs}. */
@@ -50,6 +71,30 @@ export interface DispatchLoopOptions {
5071
* A value at or below `intervalMs` disables the backoff.
5172
*/
5273
maxIdleIntervalMs?: number;
74+
/**
75+
* [#29919] The earliest instant (epoch ms, on `Date.now()`'s clock) at
76+
* which work this loop's tick would claim becomes claimable — a deferred
77+
* row's due time, a claim's expiry — or `null` when nothing is deferred.
78+
* Read once per idle streak, after its first empty tick; the loop then never
79+
* sleeps past the answer. An answer at or before the start of the tick that
80+
* just found nothing is not chased (that work was visible and not claimable
81+
* by this loop — another node's partition, say), so it cannot make the loop
82+
* spin. A rejection is reported through `onTickError` and the loop sleeps as
83+
* if it had no answer.
84+
*
85+
* Absent, the loop sleeps by the backoff alone, as it always has.
86+
*/
87+
nextDueAt?: () => Promise<number | null | undefined>;
88+
/**
89+
* [#29919] No other process writes the store this loop drains: every row it
90+
* can claim is written here, by a producer that calls
91+
* {@link DispatchLoop.wake} (or {@link DispatchLoop.wakeAt} for a deferred
92+
* row). The idle backoff's ramp only ever bought latency on rows another
93+
* process wrote, so with this set an empty tick sleeps straight to the
94+
* ceiling, or to the next due time when {@link nextDueAt} is given. Default
95+
* `false`: the ramp from `intervalMs` is kept.
96+
*/
97+
soleWriter?: boolean;
5398
/** One full pass over the outbox. Resolves to the number of rows it claimed. */
5499
runTick: () => Promise<number>;
55100
/** A tick rejected. The loop has already counted it as idle; report it. */
@@ -61,7 +106,17 @@ export class DispatchLoop {
61106
private readonly maxIdleIntervalMs: number;
62107
private readonly runTick: () => Promise<number>;
63108
private readonly onTickError: (err: unknown) => void;
109+
private readonly nextDueAt: (() => Promise<number | null | undefined>) | undefined;
110+
private readonly soleWriter: boolean;
64111
private timer: ReturnType<typeof setTimeout> | undefined;
112+
/** When the pending timer fires (epoch ms); meaningful only while `timer` is set. */
113+
private timerFiresAt = 0;
114+
/** [#29919] Earliest known instant work becomes claimable, from the last read and every hint since. */
115+
private knownDueAt: number | null = null;
116+
/** [#29919] The next empty tick reads {@link DispatchLoopOptions.nextDueAt}. */
117+
private dueReadOwed = false;
118+
/** [#29919] Hints ({@link DispatchLoop.wakeAt}) since the running tick began — a read in flight cannot see them. */
119+
private hintedDueAt: number | null = null;
65120
private running = false;
66121
private inflightTick: Promise<void> | undefined;
67122
/** Consecutive loop ticks that claimed nothing — the idle backoff's exponent. */
@@ -78,13 +133,17 @@ export class DispatchLoop {
78133
);
79134
this.runTick = options.runTick;
80135
this.onTickError = options.onTickError;
136+
this.nextDueAt = options.nextDueAt;
137+
this.soleWriter = options.soleWriter ?? false;
81138
}
82139

83140
/** Begin the loop; the first tick runs immediately. Idempotent. */
84141
start(): void {
85142
if (this.running) return;
86143
this.running = true;
87144
this.idleTicks = 0;
145+
this.knownDueAt = null;
146+
this.dueReadOwed = true;
88147
this.loopTick();
89148
}
90149

@@ -106,9 +165,33 @@ export class DispatchLoop {
106165
wake(): void {
107166
if (!this.running) return;
108167
this.idleTicks = 0;
168+
this.dueReadOwed = true;
109169
this.loopTick();
110170
}
111171

172+
/**
173+
* [#29919] Work becomes claimable at `dueAtMs` (epoch ms, on `Date.now()`'s
174+
* clock) — a deferred row this process just wrote: make sure a tick runs
175+
* then. Costs no read and no tick now, and leaves the idle backoff where it
176+
* is; a timer already due sooner is kept. An instant already past ticks at
177+
* once. No-op while stopped, or for a non-finite instant.
178+
*/
179+
wakeAt(dueAtMs: number): void {
180+
if (!this.running || !Number.isFinite(dueAtMs)) return;
181+
this.knownDueAt = earliest(this.knownDueAt, dueAtMs);
182+
this.hintedDueAt = earliest(this.hintedDueAt, dueAtMs);
183+
// The running tick schedules its successor from `knownDueAt` when it settles.
184+
if (this.inflightTick) return;
185+
if (this.timer !== undefined && this.timerFiresAt <= dueAtMs) return;
186+
const delayMs = dueAtMs - Date.now();
187+
if (delayMs <= 0) {
188+
this.dueReadOwed = true;
189+
this.loopTick();
190+
return;
191+
}
192+
this.schedule(delayMs, true);
193+
}
194+
112195
/**
113196
* One tick of the loop, then the timer for the next. Never two at once: a
114197
* call that finds a tick in flight becomes a follow-up request instead.
@@ -121,13 +204,22 @@ export class DispatchLoop {
121204
return;
122205
}
123206
const startedAt = Date.now();
207+
this.hintedDueAt = null;
124208
this.inflightTick = this.runTick()
125-
.then((claimed) => {
126-
this.idleTicks = claimed > 0 ? 0 : this.idleTicks + 1;
209+
.then(async (claimed) => {
210+
if (claimed > 0) {
211+
this.idleTicks = 0;
212+
// The work just done may have deferred more (a retry, a backoff).
213+
this.dueReadOwed = true;
214+
return;
215+
}
216+
this.idleTicks += 1;
217+
if (this.nextDueAt && this.dueReadOwed) await this.readNextDueAt();
127218
})
128219
.catch((err) => {
129220
// A failing store is not work: back off rather than hammer it.
130221
this.idleTicks += 1;
222+
this.dueReadOwed = true;
131223
this.onTickError(err);
132224
})
133225
.finally(() => {
@@ -139,25 +231,67 @@ export class DispatchLoop {
139231
this.loopTick();
140232
return;
141233
}
142-
this.schedule(Math.max(0, this.nextIntervalMs() - (Date.now() - startedAt)));
234+
const { delayMs, forDue } = this.nextDelay(startedAt);
235+
this.schedule(Math.max(0, delayMs - (Date.now() - startedAt)), forDue);
143236
});
144237
}
145238

239+
/** [#29919] One read of the next due time, folded with the hints that arrived while it ran. */
240+
private async readNextDueAt(): Promise<void> {
241+
this.dueReadOwed = false;
242+
try {
243+
const due = await this.nextDueAt!();
244+
this.knownDueAt = earliest(
245+
typeof due === 'number' && Number.isFinite(due) ? due : null,
246+
this.hintedDueAt,
247+
);
248+
} catch (err) {
249+
// No answer: sleep by the backoff alone, and ask again next idle tick.
250+
this.dueReadOwed = true;
251+
this.onTickError(err);
252+
}
253+
}
254+
146255
/**
147-
* Delay before the next loop tick, measured from the START of the last one:
148-
* `intervalMs` while ticks claim work, doubled for every consecutive empty
149-
* tick after that, capped at `maxIdleIntervalMs`.
256+
* Delay before the next loop tick, measured from the START of the last one
257+
* (`startedAt`), and whether it is a due time's: the backoff's delay
258+
* ({@link nextIntervalMs}), cut short by the earliest known due time.
259+
*/
260+
private nextDelay(startedAt: number): { delayMs: number; forDue: boolean } {
261+
const backoffMs = this.nextIntervalMs();
262+
if (this.idleTicks === 0 || this.knownDueAt === null) return { delayMs: backoffMs, forDue: false };
263+
if (this.knownDueAt <= startedAt) {
264+
// Claimable before this tick began, and the tick claimed nothing: the
265+
// work is not this loop's to take right now (another node holds its
266+
// partition, say). Chasing it would spin; the backoff covers it.
267+
this.knownDueAt = null;
268+
return { delayMs: backoffMs, forDue: false };
269+
}
270+
const untilDueMs = this.knownDueAt - startedAt;
271+
return untilDueMs < backoffMs ? { delayMs: untilDueMs, forDue: true } : { delayMs: backoffMs, forDue: false };
272+
}
273+
274+
/**
275+
* The backoff's delay before the next loop tick, measured from the START of
276+
* the last one: `intervalMs` while ticks claim work, doubled for every
277+
* consecutive empty tick after that, capped at `maxIdleIntervalMs` — or the
278+
* cap at once after an empty tick when the loop is the store's sole writer.
150279
*/
151280
private nextIntervalMs(): number {
152281
if (this.idleTicks === 0) return this.intervalMs;
282+
if (this.soleWriter) return this.maxIdleIntervalMs;
153283
// Exponent clamped so the product stays finite long after the cap wins.
154284
return Math.min(this.maxIdleIntervalMs, this.intervalMs * 2 ** Math.min(this.idleTicks, 30));
155285
}
156286

157-
private schedule(delayMs: number): void {
287+
private schedule(delayMs: number, forDue: boolean): void {
158288
this.clearTimer();
289+
this.timerFiresAt = Date.now() + delayMs;
159290
this.timer = setTimeout(() => {
160291
this.timer = undefined;
292+
// The due time arrived: the tick takes that work, and the next idle
293+
// tick asks for the one after it.
294+
if (forDue) this.dueReadOwed = true;
161295
this.loopTick();
162296
}, delayMs);
163297
// Don't keep the event loop alive solely for the dispatcher.
@@ -170,3 +304,10 @@ export class DispatchLoop {
170304
this.timer = undefined;
171305
}
172306
}
307+
308+
/** The earlier of two optional instants. */
309+
function earliest(a: number | null, b: number | null): number | null {
310+
if (a === null) return b;
311+
if (b === null) return a;
312+
return Math.min(a, b);
313+
}

‎packages/services/service-messaging/src/dispatcher.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,24 @@ export interface NotificationDispatcherOptions {
7171
* {@link NotificationDispatcher.wake} call, snaps it back to `intervalMs`.
7272
* A value at or below `intervalMs` disables the backoff.
7373
*
74-
* While idle this bounds how late the loop notices work nobody woke it for:
75-
* a deferred row coming due (retry schedule, quiet hours, a digest window),
76-
* a row enqueued by a process this dispatcher does not serve, and a crashed
77-
* node's `in_flight` rows — reaped at most `claimTtlMs` + this after their
78-
* claim, where the fixed interval gave `claimTtlMs` + `intervalMs`.
74+
* While idle this bounds how late the loop notices a row enqueued by a
75+
* process this dispatcher does not serve. A deferred row coming due (retry
76+
* schedule, quiet hours, a digest window) and a crashed node's `in_flight`
77+
* rows passing `claimTtlMs` are not left to it: with an outbox that answers
78+
* {@link INotificationOutbox.nextDueAt} the loop sleeps no later than the
79+
* earliest of them (#29919), so each is taken within one tick of coming
80+
* due. An outbox without it leaves both to this bound too.
7981
*/
8082
maxIdleIntervalMs?: number;
83+
/**
84+
* [#29919] No other process writes this dispatcher's outbox — every row is
85+
* enqueued in this process, which wakes the dispatcher (a hosted tenant
86+
* kernel: one kernel per tenant database). An idle tick then sleeps straight
87+
* to the next due time or the ceiling instead of re-running the backoff's
88+
* ramp from `intervalMs`, which only ever bought latency on rows another
89+
* process wrote. Default `false`.
90+
*/
91+
soleWriter?: boolean;
8192
lockTtlMs?: number;
8293
claimTtlMs?: number;
8394
rng?: () => number;
@@ -127,7 +138,7 @@ export interface NotificationDispatcherOptions {
127138
*/
128139
export class NotificationDispatcher {
129140
private readonly opts: Required<
130-
Omit<NotificationDispatcherOptions, 'rng' | 'logger' | 'onAttempt' | 'cluster' | 'now' | 'maxIdleIntervalMs' | 'textRenderer'>
141+
Omit<NotificationDispatcherOptions, 'rng' | 'logger' | 'onAttempt' | 'cluster' | 'now' | 'maxIdleIntervalMs' | 'soleWriter' | 'textRenderer'>
131142
> &
132143
Pick<NotificationDispatcherOptions, 'rng' | 'logger' | 'onAttempt' | 'now' | 'textRenderer'> & { cluster: DispatchCluster };
133144
/** [#17610, #17623] The timer loop — idle backoff, wake, stop — shared with `HttpDispatcher`. */
@@ -153,9 +164,21 @@ export class NotificationDispatcher {
153164
onAttempt: options.onAttempt,
154165
textRenderer: options.textRenderer,
155166
};
167+
const { outbox } = options;
156168
this.loop = new DispatchLoop({
157169
intervalMs,
158170
maxIdleIntervalMs: options.maxIdleIntervalMs,
171+
soleWriter: options.soleWriter,
172+
// [#29919] Read once per idle streak; an outbox without the read
173+
// leaves the loop on its backoff alone. An injected clock's answer
174+
// is re-based onto the loop's (`Date.now()`).
175+
nextDueAt: outbox.nextDueAt
176+
? async () => {
177+
const now = this.opts.now?.();
178+
const due = await outbox.nextDueAt!({ claimTtlMs: this.opts.claimTtlMs, now });
179+
return due === null || now === undefined ? due : Date.now() + (due - now);
180+
}
181+
: undefined,
159182
runTick: () => this.runTick(),
160183
onTickError: (err) => {
161184
this.opts.logger?.warn?.('notification-dispatcher: tick failed', {

‎packages/services/service-messaging/src/http-dispatcher.ts‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,17 +78,23 @@ export interface HttpDispatcherOptions {
7878
* tick that claims anything, or a {@link HttpDispatcher.wake} call, snaps it
7979
* back to `intervalMs`. A value at or below `intervalMs` disables the backoff.
8080
*
81-
* While idle this bounds how late the loop notices work nobody woke it for:
82-
* - a retry coming due — attempted less than `min(its delay + intervalMs,
83-
* maxIdleIntervalMs)` after it is due (plus the time ticks themselves
84-
* take), because the backoff restarts from `intervalMs` at the attempt
85-
* that scheduled the retry;
86-
* - a row enqueued by a process this dispatcher does not serve;
87-
* - a crashed node's `in_flight` rows — reaped at most `claimTtlMs` + this
88-
* after their claim, where the fixed interval gave `claimTtlMs` +
89-
* `intervalMs`.
81+
* While idle this bounds how late the loop notices a row enqueued by a
82+
* process this dispatcher does not serve. A retry coming due and a crashed
83+
* node's `in_flight` rows passing `claimTtlMs` are not left to it: with an
84+
* outbox that answers {@link IHttpOutbox.nextDueAt} the loop sleeps no
85+
* later than the earliest of them (#29919), so each is taken within one
86+
* tick of coming due. An outbox without it leaves both to this bound too.
9087
*/
9188
maxIdleIntervalMs?: number;
89+
/**
90+
* [#29919] No other process writes this dispatcher's outbox — every row is
91+
* enqueued in this process, which wakes the dispatcher (a hosted tenant
92+
* kernel: one kernel per tenant database). An idle tick then sleeps straight
93+
* to the next due time or the ceiling instead of re-running the backoff's
94+
* ramp from `intervalMs`, which only ever bought latency on rows another
95+
* process wrote. Default `false`.
96+
*/
97+
soleWriter?: boolean;
9298
/** Per-partition lock TTL. Default = 5 × intervalMs. */
9399
lockTtlMs?: number;
94100
/** Visibility timeout for claimed rows. Default = 2 × lockTtlMs. */
@@ -107,7 +113,7 @@ export interface HttpDispatcherOptions {
107113

108114
export class HttpDispatcher {
109115
private readonly opts: Required<
110-
Omit<HttpDispatcherOptions, 'fetchImpl' | 'rng' | 'logger' | 'onAttempt' | 'cluster' | 'now' | 'maxIdleIntervalMs'>
116+
Omit<HttpDispatcherOptions, 'fetchImpl' | 'rng' | 'logger' | 'onAttempt' | 'cluster' | 'now' | 'maxIdleIntervalMs' | 'soleWriter'>
111117
> &
112118
Pick<HttpDispatcherOptions, 'fetchImpl' | 'rng' | 'logger' | 'onAttempt' | 'now'> & {
113119
cluster: DispatchCluster;
@@ -133,9 +139,21 @@ export class HttpDispatcher {
133139
logger: options.logger,
134140
onAttempt: options.onAttempt,
135141
};
142+
const { outbox } = options;
136143
this.loop = new DispatchLoop({
137144
intervalMs,
138145
maxIdleIntervalMs: options.maxIdleIntervalMs,
146+
soleWriter: options.soleWriter,
147+
// [#29919] Read once per idle streak; an outbox without the read
148+
// leaves the loop on its backoff alone. An injected clock's answer
149+
// is re-based onto the loop's (`Date.now()`).
150+
nextDueAt: outbox.nextDueAt
151+
? async () => {
152+
const now = this.opts.now?.();
153+
const due = await outbox.nextDueAt!({ claimTtlMs: this.opts.claimTtlMs, now });
154+
return due === null || now === undefined ? due : Date.now() + (due - now);
155+
}
156+
: undefined,
139157
runTick: () => this.runTick(),
140158
onTickError: (err) => {
141159
this.opts.logger?.warn?.('http-dispatcher: tick failed', {

‎packages/services/service-messaging/src/http-outbox.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,14 @@ export interface HttpDueWorkOptions {
348348
now?: number;
349349
}
350350

351+
/** [#29919] Options for {@link IHttpOutbox.nextDueAt}. */
352+
export interface HttpNextDueOptions {
353+
/** Visibility timeout — an `in_flight` row becomes reapable once claimed longer ago than this. */
354+
claimTtlMs: number;
355+
/** "Now" reference, ms since epoch. Defaults to Date.now(). */
356+
now?: number;
357+
}
358+
351359
export interface HttpAckSuccess {
352360
success: true;
353361
httpStatus: number;
@@ -656,6 +664,21 @@ export interface IHttpOutbox {
656664
*/
657665
hasDueWork?(opts: HttpDueWorkOptions): Promise<boolean>;
658666

667+
/**
668+
* [#29919] The earliest instant (ms since epoch) at which a row becomes
669+
* claimable without anyone writing to the outbox — a `pending` row's
670+
* `nextRetryAt` still after `now`, or the instant an `in_flight` row's claim
671+
* passes `claimTtlMs` (already past if no reap has run since) — or `null`
672+
* when there is none. The dispatcher's loop sleeps no later than
673+
* this after an idle tick.
674+
*
675+
* A read and nothing more, stale the moment it returns like
676+
* {@link hasDueWork}: a row written afterwards reaches the loop by the
677+
* writer's `wake()`. Optional: without it the dispatcher sleeps by its idle
678+
* backoff alone. Both built-in stores implement it.
679+
*/
680+
nextDueAt?(opts: HttpNextDueOptions): Promise<number | null>;
681+
659682
/**
660683
* Atomically claim up to `limit` rows whose `nextRetryAt <= now` (or null)
661684
* and matching the partition predicate. Claimed rows MUST be marked

0 commit comments

Comments
 (0)