library / Integrations / Relational databases / I0161
Postgres unchanged-update filter
A token program subscription reports every write, including writes that leave an account's bytes as they were. This watcher hashes each account and upserts only when the hash moves, so the table holds real changes.
Why unchanged accounts arrive
A program subscription sends one notification for each write to an account that the program owns. The web3.js name is onProgramAccountChange; in @solana/kit it is programNotifications. The notification says the account was written in a slot. It carries the account's data as it stands after that write, so a token account rewritten with the same contents still produces a message. A watcher that writes every message fills its table with rows that carry nothing new.
The filter belongs in the database. Keep one SHA-256 of the account data per address. The upsert compares that stored hash with the new one and writes the row only when they differ, so an unchanged write leaves the row as it was.
Subscribe to the SPL token program with a dataSize filter of 165. That size is the base token account layout, so the stream carries no mint accounts, which are 82 bytes, and no multisig accounts. Token-2022 accounts with extensions are larger and fall outside this filter.
The upsert that filters
The table has one row per token account. The statement below does the whole job in one step:
- pubkey is the primary key, so each token account has exactly one row.
- data_hash is a SHA-256 of the base64 data string the notification already carries. The same bytes always give the same string, so no decoding is needed.
- ON CONFLICT ... WHERE updates the row only when the stored hash differs from the new one. A write with identical bytes changes zero rows.
- The changed count is the number of real data changes. Every other notification is an unchanged write.
The code writes to SQLite through node:sqlite, so it runs with Node alone. The Postgres form uses $1, $2 and $3 in place of the question marks, and IS DISTINCT FROM in place of IS NOT, the comparison Postgres needs for two plain values. The WHERE clause is the whole filter, so no lookup runs before the write.
The watcher
Install the one dependency with npm install @solana/[email protected], and set "type": "module" in package.json. Node 24 strips the types on load. The socket takes the key as ?api-key= on its URL, so the key stays out of headers and logs. The file exits with a message when CARBIUM_KEY is missing; CARBIUM_WS_URL is optional.
// I0161 · Postgres unchanged-update filter// https://carbium.sh/library/integrate/postgres-unchanged-update-filter// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createSolanaRpcSubscriptions } from "@solana/kit";import { DatabaseSync } from "node:sqlite";import { createHash } from "node:crypto";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1);}const wsUrl = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const seconds = Number(process.argv[2] ?? 12);const db = new DatabaseSync("token-accounts.db");db.exec(`CREATE TABLE IF NOT EXISTS token_accounts ( pubkey TEXT PRIMARY KEY, data_hash TEXT NOT NULL, slot INTEGER NOT NULL)`);// Changes zero rows when the stored hash already matches the new data.const upsert = db.prepare(`INSERT INTO token_accounts (pubkey, data_hash, slot) VALUES (?, ?, ?) ON CONFLICT(pubkey) DO UPDATE SET data_hash = excluded.data_hash, slot = excluded.slot WHERE token_accounts.data_hash IS NOT excluded.data_hash`);const rpc = createSolanaRpcSubscriptions(`${wsUrl}?api-key=${key}`);const ac = new AbortController();setTimeout(() => ac.abort(), seconds * 1000);let seen = 0;let changed = 0;try { const notes = await rpc .programNotifications(TOKEN_PROGRAM, { commitment: "confirmed", encoding: "base64", filters: [{ dataSize: 165n }], }) .subscribe({ abortSignal: ac.signal }); for await (const note of notes) { const { pubkey, account } = note.value; // The base64 string is the same for the same bytes, so no decode is needed. const hash = createHash("sha256").update(account.data[0]).digest("hex"); seen++; if (Number(upsert.run(pubkey, hash, Number(note.context.slot)).changes) > 0) changed++; }} catch (err) { if (!(err instanceof Error && err.name === "AbortError")) { console.error("subscription ended:", err instanceof Error ? err.message : err); }}const rows = db.prepare("SELECT count(*) AS n FROM token_accounts").get()?.n;console.log(`notifications ${seen}, data changed ${changed}, unchanged ${seen - changed}, rows ${rows}`);db.close();process.exit(0);
run: node main.ts 12
Run it and read the counts
node main.ts 12 listens for 12 seconds, writes token-accounts.db in the folder you start it from, and prints one line with four counts: notifications seen, data changed, unchanged, and rows in the table. The token program sees many writes each second on mainnet, so a short run shows the counts moving.
Run it again in the same folder. The row count grows only by token accounts the first run did not see. A changed count below the notifications count shows the filter at work: the writes arrived, and some of them left the data as it was.
What it costs on your plan
A WebSocket subscription to a program opens at 200 credits, the weight given to program filters, and then costs 20 credits per MiB sent. Credits meter WebSocket work, and the limits are per account, so the keys on one account share one budget.
Free carries 5 sockets per account, and this watcher uses one. The filter does not lower the stream's cost. Every notification still arrives and is charged by the bytes it carries, so the hash saves storage and write work, while the credit bill follows the traffic.
Where it ends
- The filter keeps unchanged writes out of the table. Each notification still arrives and is billed by the bytes it sends.
- Token-2022 accounts with extensions are larger than 165 bytes, so this subscription does not see them.
- The hash covers the data field only. A change to lamports with identical data leaves the row as it was.
- The file has no reconnect and no replay. When the socket drops, writes during the gap are not replayed, and each account stays at its last stored state until its next write.
- The store here is SQLite. The Postgres form of the statement is untested here, so run it against a copy before relying on it.
- A matching hash means the bytes are the same. It says nothing about why the account was written.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The changed count is close to the notification count, so the table fills with rows whose data did not move. | The WHERE clause on the upsert is missing or wrong. Keep WHERE token_accounts.data_hash IS NOT excluded.data_hash, then run the file twice on one account: the second write should count as unchanged. |
| The process ends with subscription ended and a 401 message. | The key did not reach the socket, or it was cut short. Attach the whole key as ?api-key= on the WebSocket URL, copied from the account page without trimming. |
| A second process on the same account does not open its subscription. | Free carries 5 sockets per account, and other processes may hold them. Close the extra watchers, or move the account to a plan with more sockets. |
| Notifications arrive, but the table count stays at zero. | Check that the filter is dataSize 165 as a bigint and that the program address is the SPL token program, TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA, passed through address(). |
| The database file is missing after a run from another folder. | The path is relative to the working directory of the process. Start the file from the folder where the table should live. |
Questions
Does the program subscription skip writes that leave the bytes the same?
No. It sends a notification for each write, so the filter has to live in your storage. The hash comparison in the upsert keeps only the rows whose data moved.
Why hash the base64 string instead of the decoded bytes?
The notification already carries the data as base64, so one hash of that string matches identical bytes without a decode step. The same bytes always produce the same string.
Does this cover Token-2022 accounts?
Not with this filter. A base token account is 165 bytes, and Token-2022 accounts with extensions are larger. Use another data size or a memcmp filter to read those accounts.
Can I reuse the upsert for another program?
Yes. Use a new table and the account size of that program as the filter. The statement keeps one primary key, one hash and one conditional update.