library / Integrations / Document and key-value stores / I0086
Firebase Realtime TPS feed
A small Node writer reads recent performance samples from Carbium, turns them into transactions per second, and overwrites one Firebase Realtime Database path. Browsers listen to that path and update live, and none of them calls RPC.
One writer, many listeners
One process does the Solana work. Once a minute it calls getRecentPerformanceSamples, computes transactions per second, and replaces a single path in Firebase Realtime Database. Every browser, widget or app that wants the number attaches a listener to that path and receives each new value as it lands. No client holds a Carbium key, and the number of viewers has no effect on how many RPC calls you make.
That split suits a status widget. The database fans the value out to as many listeners as you have, and the writer stays a cron-sized script with one outgoing read.
| Step | Where | What happens |
|---|---|---|
| Read | Carbium RPC | getRecentPerformanceSamples with a limit of 5. |
| Compute | The writer | Transactions divided by samplePeriodSecs for each sample, then the mean. |
| Write | Firebase REST | One PUT to /network/tps.json. |
| Listen | Browsers | onValue on the network/tps reference. |
From samples to TPS
getRecentPerformanceSamples takes a limit of up to 720 and returns the newest samples first. Each sample holds slot, numSlots, numTransactions, numNonVoteTransactions and samplePeriodSecs. On mainnet a sample is a window of about 60 seconds, and the two counts are totals for that window.
TPS for one sample is its transaction count divided by samplePeriodSecs. Divide by the field and skip a sample whose period is 0, since the window length is the node's to choose. The published figure is the mean of five sample rates, which smooths over a single odd minute.
The method takes no commitment argument. A new sample appears about once a minute, so a writer that asks more often gets the same newest sample back and writes the same number again.
The two transaction counts
numTransactions counts every transaction in the window's blocks, failed ones included. numNonVoteTransactions leaves out validator vote transactions. Mainnet blocks carry no vote transactions since Alpenglow, so the two counts now agree on mainnet. Before that switch the first count was dominated by votes and ran far above the second.
The writer still reads both and publishes the non-vote rate as tps. That is the figure people mean by TPS, and it stays correct on any cluster whose blocks still hold votes. The output prints the pair for each sample, so a glance shows whether they match. The Non-vote TPS meter reads the same two fields without a database.
Path, payload and history
The writer owns one path, /network/tps, and replaces it whole on every run with a PUT to /network/tps.json. The body carries four fields.
- tps: the mean non-vote rate of the five samples, rounded to one decimal.
- slot: the slot of the newest sample.
- history: the five per-sample non-vote rates, oldest first, which is enough for a sparkline.
- updatedAt: the value {".sv": "timestamp"}, which Firebase swaps for its own clock in milliseconds.
Because Firebase stamps updatedAt, a client can subtract it from its own Date.now() to learn the age of the number, and the writer's clock never enters. A PUT replaces the path in one step, so a listener attached with onValue always receives a tps and a history from the same run.
A longer chart wants a second path that grows, written with POST and trimmed by a cleanup job. This writer keeps only the short list.
Rules that keep the path read-only
Clients need to read the path and never write it. In the rules file this reads {"rules": {"network": {"tps": {".read": true, ".write": false}}}}, and Firebase treats every other path as closed.
| Path | `.read` | `.write` |
|---|---|---|
| /network/tps | true | false |
| Everything else | false by default | false by default |
The writer is outside these rules. A REST call made with a service account's OAuth2 access token runs with admin rights, so .write: false stops every browser while the writer still gets through. Give the token the https://www.googleapis.com/auth/firebase.database and https://www.googleapis.com/auth/userinfo.email scopes and pass it in FIREBASE_TOKEN. Such tokens last about an hour, so mint a new one for each run or each batch of runs.
The writer
Install it with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. Create the key from your account keys and export it as CARBIUM_KEY, which is required.
FIREBASE_DB_URL (the database root from your console) and FIREBASE_TOKEN are optional. With no URL the file prints the path and the JSON body and stops, so you can check the numbers before anything is written.
// I0086 · Firebase Realtime TPS feed// https://carbium.sh/library/integrate/firebase-realtime-tps-feed// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY. Optional: FIREBASE_DB_URL (database root) and FIREBASE_TOKEN (OAuth2 access token)."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const PATH = "/network/tps.json";const one = (n: number) => Math.round(n * 10) / 10;async function main() { // The node answers newest first; flip to oldest first for the history list. const samples = await rpc.getRecentPerformanceSamples(5).send({ abortSignal: AbortSignal.timeout(10_000) }); const rows = samples .filter((s) => s.samplePeriodSecs > 0) .map((s) => ({ slot: Number(s.slot), all: Number(s.numTransactions) / s.samplePeriodSecs, nonVote: Number(s.numNonVoteTransactions) / s.samplePeriodSecs, })) .reverse(); if (rows.length === 0) throw new Error("no performance samples returned"); for (const r of rows) console.log(`sample slot ${r.slot}: all ${one(r.all)} TPS, non-vote ${one(r.nonVote)} TPS`); const payload = { tps: one(rows.reduce((t, r) => t + r.nonVote, 0) / rows.length), slot: rows[rows.length - 1].slot, history: rows.map((r) => one(r.nonVote)), updatedAt: { ".sv": "timestamp" }, // Firebase fills in its own clock, in ms }; console.log("path", PATH); console.log("body", JSON.stringify(payload)); const base = process.env.FIREBASE_DB_URL; if (!base) return void console.log("FIREBASE_DB_URL not set: nothing written"); const url = new URL(PATH, base); if (process.env.FIREBASE_TOKEN) url.searchParams.set("access_token", process.env.FIREBASE_TOKEN); const res = await fetch(url, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }); console.log("PUT", PATH, res.status); if (!res.ok) throw new Error(await res.text());}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1);});
run: node main.ts
Run it from cron or a systemd timer every minute. Each run prints five lines, one per sample with both rates, then the path, the body and the PUT status when a URL is set.
Where it ends
- The number is a recent average. A sample is about a minute wide and the mean covers five of them, so a spike that lasts seconds is flattened and the figure says nothing about the current slot or a peak.
- The newest sample ends when its window closes, so the value can be up to a minute old before the writer sees it.
- A writer outage freezes the number. Firebase keeps the last value and every listener keeps showing it with no sign of trouble. Have the widget compare updatedAt with the current time and mark the number stale once it is a few minutes old.
- One writer owns the path. Two writers on different schedules overwrite each other, and the older sample can land last.
- History is five points, replaced with each run. Anything longer needs a second path of your own.
- TPS counts every transaction, whether it moved value or not. It measures how busy the network is, which differs from how many people used it.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run ends with an HTTP 401 from Carbium before anything prints. | The key was cut short or is wrong. An unknown key gets a 401 at the door, so check that CARBIUM_KEY holds the whole key and that CARBIUM_RPC_URL, if set, points at the Carbium endpoint. |
| The Carbium read fails with 429 on a minute when other jobs on the account are busy. | All keys on an account share one rate budget. The previous value stays in the database, and the next scheduled run tries again. If it happens often, move the writer's run off the minute mark the other jobs use. |
| The PUT prints 401 with a permission message from Firebase. | The access token is missing, expired, or lacks the two scopes. Mint a fresh token from the service account and send it as FIREBASE_TOKEN. A browser key or the web config cannot write past .write: false. |
| The PUT fails with an error that names the database, or the console shows no data at the path. | FIREBASE_DB_URL must be the root URL of the right instance, including its region host, with no path and no .json. The writer adds the path itself. |
| A browser listener logs permission_denied. | The rules do not open network/tps for reads, or the listener is attached higher up, at the root, where reads stay closed. Attach it to network/tps exactly. |
| The widget shows the same TPS for several refreshes in a row. | A new sample appears about once a minute. A schedule faster than that rewrites the same sample, so run the writer once a minute. |
Questions
Why not let each browser call getRecentPerformanceSamples?
Every viewer would spend RPC calls of its own and need a key in the page. One writer makes one call a minute, and the database copies the result to every listener.
Which count should the widget show?
The non-vote one. On mainnet the two match now, and the non-vote field keeps the figure right if the same code ever runs against a cluster whose blocks include votes.
Can I write with a database secret instead of an OAuth token?
A legacy database secret still works as the auth query parameter, but Firebase has deprecated it. A service account token carries a scope and expires, so prefer it for a writer that runs unattended.
When should the widget call the number stale?
A new sample lands about every minute, so an updatedAt older than three minutes means at least two runs were missed. Show a stale marker then, and clear it when updatedAt moves again.