← Back to Pull requests

onionmessage+peer: rate-limit incoming onion messages per-peer and globally #10713

Closed
unknown closed this pull request without merging on Apr 15, 2026 23:27 UTC
View on GitHub
unknown unknown commented on Apr 07, 2026 02:32 UTC
Author

In this PR, we add two token-bucket rate limiters on the incoming onion
message path: one per-peer, one process-global. Both sit in front of the
existing actor mailbox so that over-limit traffic is dropped at ingress
before we spend any Sphinx unwrap CPU or replay-DB writes on it.

The current defense is the 50-slot per-peer actor mailbox with Random
Early Drop kicking in at depth 40. That's a _backpressure_ mechanism: it
bounds how much work can pile up waiting on the actor, and it keeps a
slow consumer from blowing up memory. What it doesn't bound is
throughput. A peer whose actor drains fast (which is the common case,
since the actor mostly just decodes, routes, and forwards) never goes
near the RED threshold no matter how much traffic it sends us. RED only
trips when the consumer is slow, not when the producer is hostile.

So the mailbox handles the "slow consumer" case and these new limiters
handle the "fast hostile producer" case. They're complementary, not
redundant: the mailbox protects against actor stalls, the limiters
protect against unpaid-traffic flooding.

Why bother

Onion messages are unpaid, source-routed, and forwarded on behalf of
whoever asks. Assuming spec-max packets (~32 KiB each) and a peer that
drains quickly, a single peer on the default ~50-slot mailbox can push
multiple Mbps of forwarded traffic through us without ever tripping
RED. Fan-in from many peers multiplies that into tens of Mbps. For a
routing node operator, 13 Mbps sustained is about 4.2 TB/month of
unpaid egress (at AWS prices, ~$380/month if saturated), and it's
30x the existing gossip budget. That's very much out of proportion for
a side channel on a payment router, and it's exactly the kind of
surface rate-limiting exists for.

Defaults

The knobs target roughly ~5 Mbps worst-case ingress at spec-max
message sizes:

  • Per-peer: 2 msg/s, burst 8 (~130 KB/s at spec-max)

  • Global: 20 msg/s, burst 50 (~650 KB/s, ~1.7 TB/month worst case)
  • 5 Mbps is one HD video stream, within an order of magnitude of our
    existing gossip budget, and easily above anything BOLT-12 or
    async-payment flows hit in practice. All four values are tunable via
    protocol.onion-msg-peer-rate, protocol.onion-msg-peer-burst,
    protocol.onion-msg-global-rate, and protocol.onion-msg-global-burst.
    To disable a limiter entirely, set both its rate and burst to zero;
    setting only one of the pair to zero is rejected at startup so a typo
    can't silently turn protection off.

    How it works

    The primitives live in onionmessage/ratelimit.go: a small
    RateLimiter interface, a noopLimiter for the disabled case, a
    countingLimiter wrapping x/time/rate.Limiter with an atomic drop
    counter, and a PeerRateLimiter registry that lazily creates a bucket
    per peer on first use and evicts on Forget. The usage pattern mirrors
    the existing gossiper rate-limiter in discovery/gossiper.go.

    At the brontide ingress, readHandler's *lnwire.OnionMessage case
    calls a small allowOnionMessage helper that consults the per-peer
    limiter first, then the global limiter. The ordering matters: if we
    checked global first, a peer whose own bucket was already empty would
    still burn a global token on every rejected attempt, letting a single
    hostile peer drain the shared budget and starve legitimate peers.
    Checking per-peer first means over-limit traffic from one peer is
    rejected before it can touch the global bucket, and the global bucket
    only ever accounts for traffic that was within its source peer's own
    allowance.

    On peer disconnect, Brontide.Disconnect calls Forget on the
    per-peer registry so its memory footprint stays bounded across the
    lifetime of the process. There's an acknowledged edge case where a
    peer that cycles disconnect+reconnect rapidly can amplify its effective
    per-peer rate (each reconnect yields a fresh full-burst bucket). The
    global limiter is the hard ceiling that catches this. We document the
    interaction in sample-lnd.conf so operators understand how the two
    limits relate.

    When a limiter first trips, logFirstOnionDrop emits a one-shot
    info-level line so operators get a visible "rate limiting engaged"
    signal without log flooding. Subsequent drops fall through to debug.

    Commits

    See each commit message for a detailed description w.r.t the
    incremental changes:

  • onionmessage: add token-bucket rate limiter primitives

  • lncfg+config: add tunable onion message rate limit options

  • peer: enforce onion message rate limits at ingress

  • server+docs: construct onion message rate limiters and document config
  • Out of scope (follow-ups)

    A few items came up in review that I've left for follow-up PRs:

  • Wiring Dropped() counters into Prometheus metrics. Counters exist;

  • exposing them is a separate plumbing change.
  • Upper bounds on rate/burst to catch "effectively disabled" settings

  • like burst=2147483647. Not a correctness issue, just hardening.
  • Clamping OnionBlob to the BOLT spec max of 32,834 bytes. Right now

  • lnwire.MaxMsgBody (~65 KiB) is the only ceiling, which doubles the
    worst-case bandwidth math. Would need a spec conversation first.

    Test plan

  • Unit tests for the limiter primitives, including table-driven

  • disabled-mode, burst exhaustion, per-peer isolation, and a
    concurrent Forget+Allow stress test under -race.
  • Unit tests for the ingress allowOnionMessage helper, including

  • nil-limiter, ordering (per-peer rejects first without touching
    global), peer isolation, and a concurrent stress test asserting
    every attempt is accounted for.
  • Unit tests for FirstDropClaim / FirstGlobalDropClaim and for

  • logFirstOnionDrop (one-shot, nil-peer, unknown-reason).
  • Table-driven tests for validateOnionMsgLimiter covering NaN,

  • ±Inf, negatives, mismatched rate/burst pairs, both-zero, and
    both-positive.
  • Run existing onion message itests to confirm defaults don't

  • interfere with happy-path traffic.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: gijswijs Review duration: 12774m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #10713"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%