services
Get a key

library / How to use Solana / WebSocket / HS0118

Multi-endpoint subscription dedup

One TypeScript file opens the same logs subscription on two WebSocket feeds. It delivers each transaction once, keyed by signature, and after a timed run reports the repeats it dropped and the transactions only one feed carried.

By Carbium · WebSocket · HS0118 · updated 2026-11-23

01

Why two feeds repeat

People run two WebSocket feeds for one reason: a single socket can stall or drop, and a second one covers the gap. The price is that every notification now arrives twice, from two different nodes, in whatever order the networks deliver them. Your handler has to turn that into one event per transaction.

Three rules do the work.

  • Pick a key that both feeds agree on. A transaction signature is the same on every node, so it identifies the event. A slot number does not: one slot carries many transactions, so a slot key merges distinct events, and a slot notified at processed can still end up skipped when its fork is dropped.
  • Deliver on first sight and remember the key for a while. The faster feed wins each event, and the later copy only adds its feed number to a record.
  • Keep the record long enough to catch the slower feed, then forget it. A map that never shrinks is a memory leak on a busy address.

Commitment matters here too. Both subscriptions must ask for the same level. At mixed levels the processed feed reports transactions that may never confirm, which then look like misses on the other feed, and its head start in time is commitment lag instead of feed lag. The file sends commitment: "confirmed" explicitly on both.

The same record finds missed updates. A signature that one feed reported and the other never did is a missed update on the quiet feed. Counting those per feed tells you which endpoint to trust less, and it tells you whether the second feed earns its cost.

02

The code

The file needs no install. Export CARBIUM_KEY, then run it with an address to watch and an optional number of seconds. It opens one logsSubscribe with a mentions filter on each feed and prints the first three transactions it delivers, then a summary.

main.ts
// HS0118 · Multi-endpoint subscription dedup// https://carbium.sh/library/howsolana/multi-endpoint-subscription-dedup// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITconst key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const address = process.argv[2];if (!address) {  console.error("Usage: node main.ts <address> [seconds]");  process.exit(1);}const seconds = Number(process.argv[3] ?? 15);const primary = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");primary.searchParams.set("api-key", key);// Extra endpoints carry their own credentials in the URL; the Carbium key goes only to the Carbium URL.const extra = (process.env.EXTRA_WS_URLS ?? "").split(",").filter(Boolean);const feeds = [primary.href, ...(extra.length ? extra : [primary.href])];type Seen = { at: number; slot: number; by: Set<number> };const seen = new Map<string, Seen>();const raw = feeds.map(() => 0);let shown = 0;feeds.forEach((href, i) => {  const ws = new WebSocket(href);  ws.addEventListener("open", () =>    ws.send(JSON.stringify({      jsonrpc: "2.0", id: 1, method: "logsSubscribe",      params: [{ mentions: [address] }, { commitment: "confirmed" }],    })),  );  ws.addEventListener("message", (ev) => {    const msg = JSON.parse(String(ev.data));    if (msg.error) return void console.error(`feed ${i} refused: ${msg.error.message}`);    if (msg.method !== "logsNotification") return;    const sig: string = msg.params.result.value.signature;    const slot: number = msg.params.result.context.slot;    raw[i]++;    const hit = seen.get(sig);    if (hit) {      hit.by.add(i); // a repeat: record the feed, deliver nothing      return;    }    seen.set(sig, { at: Date.now(), slot, by: new Set([i]) });    if (shown++ < 3) console.log(`delivered ${sig.slice(0, 12)} slot ${slot} first from feed ${i}`);  });  ws.addEventListener("error", () => console.error(`feed ${i} socket error`));  setTimeout(() => ws.close(), seconds * 1000);});setTimeout(() => {  const cutoff = Date.now() - 2000; // a signature this fresh may not have reached the other feed yet  const settled = [...seen.values()].filter((s) => s.at < cutoff);  feeds.forEach((_, i) => {    const only = settled.filter((s) => s.by.size === 1 && s.by.has(i)).length;    console.log(`feed ${i}: raw ${raw[i]}, only this feed ${only}`);  });  const total = raw.reduce((a, b) => a + b, 0);  console.log(`unique ${seen.size}, repeats dropped ${total - seen.size}`);  process.exit(0);}, seconds * 1000 + 500);

run: node main.ts <address> [seconds]

With no extra endpoint set, the file opens two sockets to the same Carbium endpoint, which is enough to see the dedup work. To add a second provider, put its full WebSocket URL, with whatever credential that provider asks for, in EXTRA_WS_URLS as a comma separated list. The Carbium key goes only to the Carbium URL.

Each feed handler does two things: it counts the raw message, and it looks the signature up in the map. A miss means this feed is first, so the file stores the arrival time and the slot and delivers the event. A hit adds the feed number to the record and delivers nothing.

03

Reading the output

The summary has one row per feed and two totals. raw is every message the feed sent. only is the number of settled signatures that this feed reported and the other feeds did not. unique is the number of events you delivered, and repeats dropped is the raw total minus that.

Settled means the signature was first seen at least two seconds before the run ended. A transaction that lands in the last moment may simply not have reached the second feed yet, so counting it as missed would be wrong. The cutoff removes that false alarm.

On a healthy pair of feeds, only is zero or close to it and the repeats equal the raw count of the second feed. A feed with a steady only of its own is the one that drops updates. A run on a quiet address says little, because ten transactions are too few to compare two feeds. Use a busy program such as the Token program, and let it run longer.

$The raw counts can differ by a few between feeds even when nothing is missing. Each feed ends at its own close time, so the last second of traffic is not identical.
04

Choosing the key and the window

ChoiceValue in the fileWhy
Dedup keytransaction signatureUnique to one transaction and the same on every node. A slot holds many transactions.
Commitmentconfirmed on both feedsMixed levels turn commitment lag into false misses.
Settle window2 secondsLong enough for a slower feed to catch up, short enough to judge the run.
Record lifetimewhole runFine for a timed check. A long process needs the pruning described below.
Delivery rulefirst arrival winsThe quicker feed sets your latency, and the other one only adds a vote.

In a process that runs for days, replace the whole-run record with a timed one. Store each signature with its arrival time and delete entries older than a minute on an interval. The window only has to exceed the largest lag you expect between feeds. A copy that arrives after the entry is gone would be delivered a second time, so size the window by the worst lag you have measured.

05

On Carbium

The WebSocket endpoint is wss://services.carbium.sh and the file puts the key in the URL as `?api-key=`. A socket can also carry it as the subprotocol api-key.<YOUR_KEY> in the handshake, which keeps it out of the URL and out of any log that records URLs.

Every socket and every subscription counts against the account. Your plan caps connections and subscriptions per account, Free carries 5 sockets, and all keys on one account share the same budget. Two feeds into Carbium use two of them, and each reconnect while the old socket lingers can use a third, so leave headroom.

Opening a logsSubscribe with a mention filter costs 25 credits, and the weight rises to 200 for all logs. After that the stream costs 20 credits per MiB sent. Duplicating a subscription duplicates its stream, so two feeds on a busy program roughly double the metered bytes. A refused subscription costs nothing.

logsSubscribe streams transaction logs, all or by mention. accountSubscribe is a poor fit for a plain SOL wallet, because it sends nothing for one. Use the logs mention filter for wallets, and read the balance with getBalance when an event arrives.

06

Where it ends

The file proves that two feeds agree during a short window. It does not repair a gap. A signature that neither feed delivered is invisible to this method, because the record only knows what arrived.

To close that gap, keep the newest signature you delivered and, whenever either socket reconnects, call getSignaturesForAddress on the watched address with until set to that signature. That call costs 50 cells, and on Carbium its pages come from an address index that keeps up to 30 days. An empty page past that is the index's age limit and does not mean the address has no older transactions.

The code has no reconnect loop. A dead socket stays dead until the run ends, so a production version needs the watchdog and backoff from WebSocket keepalive and reconnect, one per feed.

The dedup record lives in one process. Two worker processes each hold their own map and each deliver every event once, so a downstream that must see an event once needs a shared store keyed by signature. A mentions filter also takes a single address per subscription, so many addresses need many subscriptions on each feed.

07

When it goes wrong

what goes wrongwhat to do
The summary shows zero raw messages on every feed.The address had no transactions during the run, or the subscribe was refused. Read the refused line in the output, then try a busy program such as the Token program and a longer run.
Every transaction is delivered twice downstream.The handler delivers before it checks the map, or the key is a slot or a timestamp. Look the signature up first and deliver only when it is absent.
One feed shows a large only count and the other shows none.The feeds subscribed at different commitment levels, or the quiet one dropped its connection mid-run. Confirm both send confirmed, then compare again with a longer run.
The second socket is refused after a few reconnects.Old sockets still count against the plan's connection cap. Close the previous socket before opening the next, and back off between attempts.
Memory grows in a long run.The record never forgets a signature. Delete entries older than the largest feed lag you accept, on an interval.
08

Questions

Should I dedup by slot instead of signature?

No. One slot carries many transactions, so a slot key merges distinct events, and a slot notified at processed can end up skipped. The signature is unique to one transaction and the same everywhere.

Do two feeds guarantee I miss nothing?

They lower the chance that one dropped message costs you an event, but a drop on both is still possible. Backfill with getSignaturesForAddress after any reconnect.

How long should the dedup record live?

Longer than the largest delay between your feeds, and no longer than your memory allows. A minute is a common start, and you tune it from measured lag.

Can the second feed come from another provider?

Yes. Put its WebSocket URL in EXTRA_WS_URLS with its own credential. Carbium's key is only ever attached to the Carbium URL.