[bug]: wtclient calls FetchChannelByID per backup task, which scans all channel buckets (incl. tombstoned closes) — CPU and RPC latency grow with every close on postgres

Open
#11,476 4 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
12/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
go, grpc, postgresql
Domain
backend, database

Research direction

Start with the call chain in the payload: buildBreachRetribution in server.go (around L1840) calls ChannelStateDB.FetchChannelByID in channeldb/db.go (around L757), which uses channelScanner to walk every node and chain bucket. Also look at the GetInfo path through FetchAllOpenChannels and FetchPendingChannels. Done means the per-task lookup avoids a full bucket scan and tombstoned channels are skipped cheaply, with the wtclient tests still passing; the design choice between an in-memory map and an outpoint index needs maintainer input first.

Written by the indexing model from the issue text.

Description

Summary

On a postgres node (kvdb-on-SQL for channel state), the watchtower client is the single largest CPU consumer in lnd,
and the cost grows with every channel we close. Each backup task goes through buildBreachRetribution →
ChannelStateDB.FetchChannelByID → channelScanner, which walks every node bucket and every key of every chain bucket
to find one channel. Since #10780 (backported in #10786) closed channels are tombstoned on SQL backends, so their
buckets stay and are walked too.

GetInfo uses the same kind of full scan (FetchAllOpenChannels / FetchPendingChannels), so RPC latency rises with it.

Environment

  • lnd v0.21.6-beta (official release binary), Linux amd64
  • db.backend=postgres, db.use-native-sql=true (channel state still in channeldb_kv: ~61M rows), Postgres 18 on the
    same host
  • bitcoind backend (pruned), wtclient.active=true (one tower)
  • ~79 open channels; ~45 channels closed since the node moved to 0.21 (all tombstoned per #10780)

What we measured

30 s CPU profile (/debug/pprof/profile?seconds=30, 28.2 s of samples):

  • Almost all CPU is DB round trips: Syscall6 46% flat (postgres socket), scheduler (findRunnable/netpoll) ~40%
    cum, pgx (*Conn).Query 33% cum, (*PgConn).Prepare 9.5% cum, deallocateInvalidatedCachedStatements 5.6% cum.
  • By caller (cum):
    • 26.3% wtclient.(*client).backupDispatcher → processTask → sessionQueue.AcceptTask →
      backupTask.bindSession → newServer.func30 (buildBreachRetribution, server.go ~L1840) →
      channeldb.(*ChannelStateDB).FetchChannelByID → channelScanner
    • 15.1% rpcServer.GetInfo → FetchAllOpenChannels (8.2%) / FetchPendingChannels (9.2%) → fetchChannels

Goroutine dumps taken while a GetInfo was in flight: in all 6 samples it was in
kvdb/sqlbase.(*readWriteBucket).ForEach / NestedReadBucket → database/sql … pgx … Read, i.e. one query per key.
1–3 GetInfo calls were in flight in every sample (normal client polling: LNDg, litd sub-servers, monitors).

Latency trend: GetInfo average from a 10-minute health check: ~1.9 s two weeks ago → ~3.0–3.7 s now, with
host CPU iowait ~0, no steal, no memory pressure, dead tuples low, DB size flat. The rise tracks a close-heavy
period (16 closes in the last two weeks). Practical effect: on a litd restart, loop's static-address deposit manager
missed its fixed 10 s readiness deadline (static address deposit manager not ready: context deadline exceeded);
a second start made it in 7 s. lncli wtclient towers (one tower) also took from a few seconds to
over a minute in back-to-back calls.

Why it scales badly

  • FetchChannelByID (channeldb/db.go ~L757) can only match by ChannelID, so its selector ForEaches every key of a
    chain bucket and decodes each outpoint; channelScanner repeats that for every node bucket. On kvdb-on-SQL each key
    and nested-bucket step is a separate query.
  • The tombstone check (isOutpointClosed) runs after the walk reaches the channel, so tombstoned channels still
    cost their queries. Their number only grows.
  • The wtclient does this once per backup task, i.e. roughly once per channel state update.

Possible fixes (suggestions)

  1. Let the wtclient resolve ChannelID → outpoint once (in-memory map populated when the channel is registered with
    the client, or pass the outpoint through the task) and fetch with a direct key lookup, instead of a scan per task.
  2. Make channelScanner skip tombstoned node/chain buckets cheaply (e.g. via the outpoint index), or provide a way
    to purge tombstoned channels in the background so the walk does not grow forever on SQL backends.
  3. GetInfo counts could come from in-memory state (the switch / peer manager already know the active set) instead of
    deserializing every channel.

Related: #10780 / #10786 (tombstoning), #7623 (wtclient queues backup IDs only), #10994 (wtclient catch-up on the same
node). Happy to run a test build or collect more profiles.

Dominant language
Go
Stars
8.2k
Forks
2.3k
Avg merge
1d 11h
Merged PRs (30d)
103

Getting set up

  • Ships a Dockerfile or Docker Compose file
  • Has a pull request template
  • No contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from lightningnetwork/lnd

All issues in lightningnetwork/lnd

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.