library / Integrations / Queues and streams / I0088
Google Pub/Sub transaction stream
A Node walker reads whole blocks from Carbium by slot and turns each block's transactions into one ordered Pub/Sub publish request, with the slot as the ordering key and a count for completeness. The sample prints three blocks and one request body.
Block reads for full coverage
Two reads can cover every transaction. logsSubscribe streams transaction logs, all or by mention, over a WebSocket. A block read asks for one slot and gets that slot's whole transaction list back. For a pipeline whose consumers must know that nothing was dropped, the block read is the better base, because a block has a definite end. When the walker has read slot N, the list it holds is the complete list for that slot, and its length can travel with every message as a count.
A log subscription has no such total. When the socket drops, whatever passed in the meantime is gone, nothing announces the hole, and each reconnect opens a new subscription. An all-logs subscription also sits in the heaviest opening weight: it costs 200 credits to open, then 20 credits per MiB sent. The block walker pays for RPC calls instead, and credits meter that work as well.
The sample asks for signatures only. getBlock with transactionDetails: "signatures" returns the blockhash and the ordered list of transaction signatures, so each message stays small. A consumer that needs the whole transaction calls getTransaction for a signature, which costs 50 cells a call. If most consumers need it, switch the walker to full details and carry the transaction in the message.
Mainnet blocks carry no vote transactions, so the count on each message is the count of user transactions. A consumer that expects vote traffic in this topic will not find any. If you want a rate from the same counts, the non-vote TPS meter computes it.
Walking slots and skipped ones
getSlot gives the tip, and a long-running walker reads every slot from the last one it published up to that tip. Both calls in the sample name finalized. A topic has no undo, so a block from a fork that is later dropped must never reach it. @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, which is why the sample states the level. Finalized sits 0 to 1 slots behind processed, so reading there adds about one slot of delay.
A slot is about 200 ms, which means five slots a second to keep up with. Not every slot has a block. When a leader produced nothing, getBlock answers with an error for that slot. The standard codes are -32007 for a skipped slot and -32004 for a block that is not available yet.
- Skipped (-32007): the slot is final and will never have a block. Write it to your checkpoint and publish a marker message with count 0, so a consumer can tell a skipped slot from a lost one.
- Not available (-32004) at or below the finalized tip: retry a few times with a short wait before you treat it as skipped.
- Any other error: the slot is unread, so do not advance the checkpoint past it.
The sample does not branch on the code. It prints the error text for the slot, so you see which case you hit.
Message shape and ordering key
Each transaction becomes one Pub/Sub message. The data field holds the base64 of a small JSON object with the slot, the index in the block and the signature. The REST body takes data base64 encoded, and the sample prints it that way. Attributes carry what consumers filter or check on.
| Field | Value | Used for |
|---|---|---|
| data | base64 of {slot, index, signature} | The payload a consumer decodes |
| attributes.slot | The slot number as a string | Sorting across slots |
| attributes.index | Position in the block | Rebuilding block order |
| attributes.count | Transactions in the slot | Completeness check |
| orderingKey | The slot number as a string | Order within one slot |
Pub/Sub delivers messages that share an ordering key in the order they were published, provided the subscription has message ordering enabled and every publish goes to the same regional endpoint. With the slot as the key, one slot's transactions reach a consumer in block order. Slots are separate keys, so the order between slots is not guaranteed, and a consumer sorts across slots by the slot attribute. A slot is complete when the consumer holds count distinct indexes for it.
The walker
Install with npm install @solana/[email protected], set "type": "module" in package.json, and export CARBIUM_KEY. The run reads the three newest finalized slots, prints the transaction count for each, and prints the first publish request it built. It sends nothing to Google, because a publish needs an access token from your own service account. Set PUBSUB_TOPIC to your full topic path to see it in the printed URL.
// I0088 · Google Pub/Sub transaction stream// https://carbium.sh/library/integrate/google-pub-sub-transaction-stream// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("Set CARBIUM_KEY."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);const TOPIC = process.env.PUBSUB_TOPIC ?? "projects/my-project/topics/solana-transactions";const PER_REQUEST = 1000; // Pub/Sub's cap per publish requestconst LEVEL = "finalized"; // a topic has no undo: never publish a block from a dropped fork// One Pub/Sub message per signature: data, attributes and the slot as ordering key.function pubsubMessages(slot: bigint, signatures: readonly string[]) { const key = String(slot); const count = String(signatures.length); return signatures.map((signature, index) => ({ data: btoa(JSON.stringify({ slot: key, index, signature })), // base64, as the REST body wants it attributes: { slot: key, index: String(index), count }, orderingKey: key, // one key per slot keeps its transactions in block order }));}const tip = await rpc.getSlot({ commitment: LEVEL }).send();console.log(`finalized tip ${tip}`);let firstRequest: ReturnType<typeof pubsubMessages> | undefined;for (let back = 0n; back < 3n; back++) { const slot = (tip - back) as typeof tip; try { const block = await rpc .getBlock(slot, { commitment: LEVEL, transactionDetails: "signatures", rewards: false, maxSupportedTransactionVersion: 1 }) .send(); if (!block) { console.log(`slot ${slot}: no block returned`); continue; } const messages = pubsubMessages(slot, block.signatures); const requests = Math.ceil(messages.length / PER_REQUEST); console.log(`slot ${slot}: ${messages.length} transactions, ${requests} publish request(s), blockhash ${block.blockhash}`); if (messages.length > 0 && !firstRequest) firstRequest = messages.slice(0, PER_REQUEST); } catch (err) { console.log(`slot ${slot}: no block, skipped or not stored yet: ${err instanceof Error ? err.message : err}`); }}if (firstRequest) { console.log(`POST https://pubsub.googleapis.com/v1/${TOPIC}:publish (${firstRequest.length} messages in this request, first 2 shown)`); console.log(JSON.stringify({ messages: firstRequest.slice(0, 2) }, null, 1));} else { console.log("no transactions in these blocks, nothing to publish");}
run: node main.ts
Batch limits per publish request
A Pub/Sub publish request takes up to 1,000 messages and 10 MB in total. A busy slot can pass the message count, so a producer splits a block's list into chunks of 1,000 and sends them in index order. Send a chunk only after the one before it succeeded. The sample computes the number of requests per slot and prints the first one.
When a chunk fails, resend that chunk whole and hold the later chunks of the slot back. Pub/Sub delivers at least once, so a resend can put a message on the topic twice, and consumers drop repeats by signature. Write the slot to your checkpoint only after its last chunk succeeds.
With full transactions in data, the 10 MB total becomes the limit that bites first, so cut chunks by bytes as well as by count.
Where it ends
- Volume and cost. The walker makes at least one read per slot for as long as it runs, and credits meter RPC work. Plans carry 10M credits a month on Dev, 50M on Business and 200M on Pro, and Free gets 500K once. Add Google's own charges for the bytes you publish, and size both before you leave it running.
- Sustained load. A block read per slot suits a topic that needs completeness checks. For a continuous firehose, the gRPC Carbon stream at https://services.carbium.sh:9443 filters on the server, takes the key in x-token, and opens on Dev, Business and Pro. It needs a gRPC client and the proto files, so it is a larger build than this one.
- A walker that falls behind. If a read and a publish take longer than a slot, the lag grows with every slot. Keep the last fully published slot in durable storage and resume from the slot after it. The sample has no checkpoint and starts at the tip each run. A slot far behind the tip may no longer be served by the validator, and the walker then logs it as unavailable.
- Failed transactions. A transaction that landed and failed is in the block with its signature. The signatures-only read does not say which ones failed.
- The sample publishes nothing. Authentication to Google, the publish call and its retries are yours to add around the request it prints.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every getBlock fails and the log shows error -32015. | A block in range holds a v1 transaction and the call left maxSupportedTransactionVersion out or set it to 0. Pass 1 on every getBlock. The failed call is uncharged. |
| A slot prints as having no block, and a later run reads the same slot fine. | The block was not stored yet (-32004) when the first run asked for it. Retry a few times before you mark the slot skipped, and keep the checkpoint behind it meanwhile. |
| Pub/Sub rejects a publish with a size or message count error. | The request passed 1,000 messages or 10 MB. Split the slot into chunks of at most 1,000 messages, and by bytes as well when data carries full transactions. |
| Consumers see a slot's transactions out of order. | The subscription does not have message ordering enabled, or publishes went to different regional endpoints. Enable ordering on the subscription and publish every request to one endpoint. |
| A consumer holds fewer indexes than the count attribute for a slot. | One chunk of that slot never published. Resend the missing chunk whole, in index order, and have the consumer keep the slot open until it holds every index. |
| The first call answers 401 UNKNOWN_KEY. | Carbium does not know the key. Check that CARBIUM_KEY holds the whole key, with nothing trimmed or quoted. |
Questions
Why read blocks instead of subscribing to logs?
A block has a definite end, so the walker can publish a count with each slot and consumers can check they hold all of it. A log subscription has no per-slot total and no replay after a dropped socket.
Why does the sample read at finalized?
A published message cannot be pulled back from a topic, and a block read at a lower level can belong to a fork that is dropped. Finalized sits 0 to 1 slots behind processed, so the delay is small.
Can I publish a whole slot as one message?
Yes. Put the signature list in one message, with the slot as an attribute. A block's signature list fits comfortably under Pub/Sub's 10 MB message limit, but consumers then lose per-transaction ordering and filtering.
Does the list include failed transactions?
A failed transaction that landed is in the block with its signature. Read its status with getTransaction, or switch the walker to full details.