FIELD NOTESGOOGLE CLOUD · ARCHITECTURE

Pub/Sub single message transforms: when the subscription replaces a function

A Cloud Run function that only reshapes Pub/Sub messages and writes them to BigQuery can go: a JavaScript UDF on a BigQuery subscription does both. Where the transform belongs, when the function stays, and why small messages save the most.

By Space Toucan4 min readPublished
ON THIS PAGE
Before and after: an orders topic feeding a Cloud Run function that writes to a BigQuery table, then the same topic feeding a BigQuery subscription with a JavaScript UDF that writes the table directly and sends rejected messages to a dead-letter topic. Drawn in archhy.

If a Cloud Run function exists only to parse a Pub/Sub message, drop or rename a few fields, discard the events nobody wants and write the rest to BigQuery, delete it. A single message transform (SMT) reshapes and filters, and a BigQuery subscription writes, with nothing to deploy or scale. Keep the function when the transform needs state, a lookup in another system, a credential Pub/Sub cannot present, or a release process of its own.

Three jobs, three replacements#

The function (Cloud Run functions, formerly Cloud Functions) did three jobs:

  • Reshape. A JavaScript user-defined function (UDF) runs inside Pub/Sub and rewrites one message's data and attributes. A topic or a subscription can chain up to five transforms.
  • Filter. A UDF that returns null drops the message: Pub/Sub acknowledges it and nobody receives it. The built-in filter reads only attributes; a UDF can read the body.
  • Deliver. A BigQuery subscription writes rows through the Storage Write API, a Cloud Storage subscription writes files, and a push subscription with payload unwrapping posts the bare body to an HTTPS endpoint.

The transform lives in a short file:

YAML
- javascriptUdf:
    functionName: toOrderRow
    code: |
      function toOrderRow(message, metadata) {
        const e = JSON.parse(message.data);
        if (e.type !== 'order.placed') return null;
        message.data = JSON.stringify({
          order_id: e.orderId,
          total_pence: Math.round(e.total * 100),
          placed_at: e.placedAt,
        });
        return message;
      }

Test it on a sample message, then attach it with a dead-letter topic:

Shell
gcloud pubsub message-transforms test --message-transforms-file=order-row.yaml \
  --message='{"type":"order.placed","orderId":"o-8812","total":42.5,"placedAt":"2026-12-14T09:00:00Z"}'

gcloud pubsub subscriptions create orders-to-bigquery --topic=orders \
  --bigquery-table=shop-prod:sales.orders --use-table-schema \
  --message-transforms-file=order-row.yaml \
  --dead-letter-topic=orders-dead-letter --max-delivery-attempts=5

Topic or subscription decides who hears about a failure#

The same UDF can sit on the topic or on one subscription. On the topic it runs before anything is stored, so a throw fails the publish and the producer gets the error. That is where redaction belongs: a field removed there is never stored, so no subscription can leak it, and every later delivery is billed on the smaller message. On a subscription, only that consumer sees the change, and a throw becomes a negative acknowledgement and a redelivery.

A UDF cannot reach anything outside itself, so the message that broke it once will break it every time. Retries only delay the dead-letter topic. Keep the attempts at the minimum of five, and grant the Pub/Sub service agent the publisher role on the dead-letter topic and the subscriber role on the subscription: without those grants Pub/Sub does not count attempts at all, and the backlog grows. The dead-lettered copy says why, in CloudPubSubDeadLetterSourceSMTErrorMessage.

If your UDF passes fields through instead of building the row, add --drop-unknown-fields, or the day a producer adds a field its messages stop reaching the table. The subscription also delivers at least once, so expect duplicates. To expose redeliveries, add message_id and the other metadata columns to the table and set --write-metadata. A producer's retry still arrives with a new ID, so deduplicate on a business key, as idempotent consumers and dead-letter topics explains.

When the function stays#

  • State. An SMT sees one message. Counting, windows and joins belong in Dataflow, or in a function with a database behind it.
  • Lookups. A UDF gets ECMAScript built-ins only: no imports, no external calls, 20 KB of code and 500 ms per message. The AI Inference SMT calls out, but only to a model on Gemini Enterprise Agent Platform. Enriching an order from Firestore still needs code.
  • Credentials. A push subscription authenticates with a token Pub/Sub signs. A partner API that wants its own key or a signature over the body needs something in between.
  • A release process. The UDF is plain JavaScript you can unit-test, but it ships as configuration: an edit reaches new messages within a few minutes, with no revision to roll back to and no traffic split. A transform whose next change deserves a canary is a service; Cloud Run services, jobs, functions or worker pools helps pick its shape.

The bill: bytes against requests#

List prices from the Pub/Sub, BigQuery and Cloud Run pricing pages, us-central1, checked 22 November 2026: a UDF $40 per TiB, on the larger of input and output, and a BigQuery subscription $50 per TiB, ingestion included, neither with a free tier; push delivery $40 per TiB (Pub/Sub's free 10 GiB goes on publishing); the Storage Write API $0.025 per GiB, 2 TiB a month free; Cloud Run $0.40 per million requests, 2 million free, compute aside.

  • 100 million events of 1 KiB (about 0.093 TiB): transform and BigQuery subscription about $8.40; push, requests and Storage Write API about $46, or $43 after free tiers.
  • One million events of 100 KiB, the same bytes: the managed path is still about $8.40; the function path drops to about $6.50 plus its compute, or $3.70 after free tiers.

The managed path is priced by the byte and the function by the request, so small, frequent messages are where removing the function pays most.

On AWS and Azure#

On AWS, EventBridge Pipes filter with event patterns and reshape with input transformers (JSON paths, not code), and hand anything harder to an enrichment step such as Lambda; Amazon Data Firehose delivers to S3 and Redshift without code, but its record transformation is a Lambda function. On Azure, Event Hubs Capture lands the raw stream in Blob Storage as Avro, and reshaping in flight means an Azure Stream Analytics job (SQL, billed by streaming unit) or an Azure Functions trigger. Where many teams share one bus, Eventarc Advanced can transform instead.

The diagram#

Before and after: a Cloud Run function between the orders topic and BigQuery, then a BigQuery subscription running the UDF, with a dead-letter topic for rejects. Open it in archhy and make a copy for your own pipeline.