Skip to content

[feature][broker] Route delayed messages to a delay storage at write time - #46

Open
nodece wants to merge 3 commits into
masterfrom
delay-routing
Open

nodece wants to merge 3 commits into
masterfrom
delay-routing

Conversation

@nodece

@nodece nodece commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Summary

Delayed messages today sit in the data ledger at their arrival position, and every
subscription's cursor tracks them as holes (individually acked positions blocking
markDelete) until they are due. This PR adds an experimental write-time routing mode
(delayedDeliveryWriteRoutingEnabled, default off) that eliminates holes entirely:
a message with deliverAtTime in the future never enters the data ledger — it goes to
the topic's delay storage and is rewritten to the data-ledger tail when due, so the
consumer always reads sequentially.

  • PersistentTopic.publishMessage checks deliverAtTime after the existing
    max-delay check (which already parses the metadata — no extra cost on the hot path
    when the flag is off). The producer receives the delay-storage BK position as its
    messageId.
  • TopicDelayRouter keeps one BK ledger per 60-second delivery window, shared by all
    subscriptions of the topic: sequential writes at route time, sequential drain at due
    time — no per-subscription copy (vs. the journal experiment in [feature][broker] Journaling bucket tracker: per-topic body-copy experiment scaffold #45), no random reads
    on the data ledgers, and no cursor holes at all.
  • The drain is driven by an exact-due timer modeled on
    AbstractDelayedDeliveryTracker.updateTimer(): the exact minimum deliverAt arms a
    one-shot timeout, an earlier append re-arms it, and every completed round recomputes
    the target from what it saw (held-back record / future windows / batch truncation),
    with a version guard so a racing append can only move the firing earlier, never
    later. Firing rate is floored at one tickTimeMillis per round. A hashed timing
    wheel (Varghese & Lauck, SOSP'87) earns its complexity at many concurrent timeouts;
    one precise one-shot per topic is simpler and more accurate.
  • Window ledgers are deleted after they expire and drain (and on close()/clear()).

Known trade-offs (documented in the code)

  • Arrival-order drain within a window: a not-due record at the head holds back a
    later already-due record; lateness is bounded by the window width (60 s). Skipping
    past the head would need the per-entry rewrite index this design exists to avoid.
  • Not durable across restarts (Phase 1): the delay-storage ledger ids and drain
    offsets are not recorded in topic metadata yet; a restart loses the routed entries.
    Production use needs that recovery layer.
  • Producer-visible messageIds point into the delay storage, not the data ledger —
    interoperability caveats apply (e.g. dedup, seek by messageId).

Test plan

  • New TopicDelayRouterTest (8 cases, in-memory BK double): producer-visible
    position, due rewrite, no rewrite before due, held-back record re-arming the
    timer at its own deliverAt, earlier-append re-arm, arrival-order hold-back,
    window math, close cancels the timer + deletes the storage. Run 3× green.
  • Regression: org.apache.pulsar.broker.delayed.*,
    DelayedDeliveryTest, BucketDelayedDeliveryTest green; spotless clean.
  • Cluster A/B against the bucket tracker on cloud disks (sequential-vs-random gap).

void-ptr974 and others added 3 commits November 27, 2026 18:22
…time

Delayed messages currently sit in the data ledger at their arrival
position, and the consumer's cursor tracks them as holes until they are
due. This adds a write-time routing mode (delayedDeliveryWriteRoutingEnabled,
default false) that eliminates holes entirely:

- PersistentTopic.publishMessage checks deliverAtTime after the existing
  max-delay check (which already parses the metadata — no extra cost). A
  message with deliverAtTime in the future goes to the topic's delay
  storage, not the data ledger; the producer gets the delay-storage BK
  position as its messageId.
- TopicDelayRouter manages a time-windowed delay storage per topic
  (60-second windows, one BK ledger per window, shared by all
  subscriptions): sequential writes at route time, sequential drain at
  due time.
- A scheduled task drains the due entries and rewrites each one to the
  topic's data ledger tail via the normal publishMessage path — the
  deliverAtTime is in the past by then, so the routing check writes it
  normally. The consumer reads the rewritten entry at the tail
  sequentially: no holes, no skip condition, no delayed-delivery
  tracker needed for the data ledger.
- Fully drained and expired windows have their ledgers deleted.

The consumer's messageId is the data-ledger position of the rewritten
entry; the producer's messageId is the delay-storage position. They are
different — this is a known trade-off of the routing approach.

Not durable across restarts: the delay-storage ledgers and drain
offsets are not recorded in cursor properties. A restart loses the
pending delayed messages (they were acknowledged by the producer but not
yet in the data ledger). This is an experiment; production would record
the delay-storage ledger ids in the topic's metadata for recovery.

Assisted-by: Claude Code
The drain was a fixed-rate poll: rescheduled at every tick, awake
whether or not anything was due, and blind to a due time until the
next tick boundary. Replace it with the tracker-timer pattern of
AbstractDelayedDeliveryTracker.updateTimer():

- nextDeliverAt tracks the exact minimum deliverAt. It is lowered at
  append time (before the BK write completes, so delivery never waits
  on the ack) and recomputed at the end of every drain round from what
  the round saw: the held-back record's deliverAt (exact), the future
  window starts (lower bounds), and cutoff+1 when the batch was
  truncated with everything read already due.
- The recompute is version-guarded: an append that became visible
  during a round can only move the firing earlier (the cutoff+1
  clamp), never later — a racing append's deliverAt is always past the
  round's cutoff, since routing only appends future deliveries.
- The firing rate is floored at one tickTimeMillis per round (upstream's
  lastTickRun floor), an append that moves the target earlier re-arms
  the timer, and a stale timeout that raced its cancellation cannot
  clear the newer timer's state (generation counter, as in apache#25996).
- runDrain guards against a synchronous failure leaving the in-flight
  flag stuck, which would stall every later round.

A hashed timing wheel (Varghese & Lauck, SOSP'87) earns its complexity
at many concurrent timeouts; the router holds one per topic, where a
precise one-shot schedule is both simpler and more accurate than a
wheel rounded to its tick duration.

Also documents a trade-off the new tests surfaced: within a window the
drain follows arrival order, so a not-due record at the head delays a
later already-due record, bounded by the window width. Skipping past
the head would need a per-entry rewrite index and re-reads of the held
prefix every round — the very index this write-routing design exists
to avoid.

TopicDelayRouterTest exercises the router against an in-memory BK
double: the producer-visible position, the due rewrite, no rewrite
before due, the held-back record re-arming the timer at its own
deliverAt, the earlier-append re-arm, the arrival-order hold-back,
the window math, and the close semantics.

Assisted-by: Claude Code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants