---
title: "Google Pub/Sub | Speedscale Docs"
description: "Capture, mock and replay Google Pub/Sub traffic with Speedscale and proxymock, and drive a subscriber under test by republishing the messages it received."
canonical: "https://docs.speedscale.com/guides/message-brokers/google-pubsub/"
---

[Documentation index](https://docs.speedscale.com/guides/llms.txt) | [Markdown](https://docs.speedscale.com/guides/message-brokers/google-pubsub/index.md) | [Canonical page](https://docs.speedscale.com/guides/message-brokers/google-pubsub/)

# Google Pub/Sub

<a id="choose-a-workflow"></a>

## Choose a workflow

| If you want to | Start here |
| --- | --- |
| Capture a publisher or subscriber on your machine | [Record Google Pub/Sub traffic](https://docs.speedscale.com/proxymock/message-brokers/record/google-pubsub/) |
| Check retry behavior without a broker | [Mock a Pub/Sub subscriber](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-subscriber) |
| See whether a subscriber keeps up under load | [Republish recorded deliveries](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#drive-a-subscriber-by-republishing) and [check the subscriber's backlog and acknowledgements](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#check-that-the-subscriber-kept-up) |
| Check what a publisher sent | [Catch a publisher regression](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#catch-a-publisher-regression) |
| Replay a push subscriber's HTTP handler | [Push subscriptions](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#push-subscriptions) |

<a id="background"></a>

## Background

The Google Cloud client libraries talk to Pub/Sub over gRPC, on `pubsub.googleapis.com:443` or a regional endpoint, so Speedscale records Pub/Sub calls as gRPC calls. The PHP library falls back to the REST API when its gRPC extension is missing, and some clients are configured to use REST. Those calls are recorded as HTTP, and the mock and republish handle them as they handle the gRPC calls. See [REST clients](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#rest-clients).

A publisher sends unary `Publish` calls. A subscriber built on a high-level client opens a bidirectional `StreamingPull` stream, receives messages on it, and acknowledges them with separate unary `Acknowledge` and `ModifyAckDeadline` calls. Some subscribers use unary `Pull` instead.

A push subscription delivers messages to your service as inbound HTTP requests instead. See [push subscriptions](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#push-subscriptions).

For more information about Google Pub/Sub, see the [Google Cloud Pub/Sub documentation](https://cloud.google.com/pubsub).

<a id="what-is-supported"></a>

## What is supported

| Call | Capture | Mock | Replay |
| --- | --- | --- | --- |
| `Publish` | Yes, as gRPC | Yes, by topic with new message IDs ([mock a publisher](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-publisher)) | Yes, as gRPC |
| `Acknowledge` and `ModifyAckDeadline` | Yes, as gRPC | Yes, without matching ([mock a subscriber](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-subscriber)) | Yes, as gRPC |
| Other unary calls, such as `GetSubscription` | Yes, as gRPC | Yes, as gRPC | Yes, as gRPC |
| `Pull` | Yes, as gRPC | Yes, from the recorded messages ([mock a subscriber](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-subscriber)) | Its messages can be republished to drive a subscriber |
| `StreamingPull` | Yes, as a streamed gRPC call, kept in parts when it runs long | Yes, from the recorded messages ([mock a subscriber](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-subscriber)) | Its messages can be republished to drive a subscriber |
| REST `:pull`, `:acknowledge`, `:modifyAckDeadline` and `:publish` | Yes, as HTTP | Yes, as their gRPC equivalents are ([REST clients](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#rest-clients)) | `:pull` messages can be republished to drive a subscriber |
| Push deliveries to your service | Yes, as inbound HTTP | Not needed | Yes, as inbound HTTP ([push subscriptions](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#push-subscriptions)) |

Capture needs TLS interception, as for any gRPC service. A subscriber keeps its `StreamingPull` stream open and ends it by cancelling it; capture keeps such a stream as one or more parts of a [long-lived stream](https://docs.speedscale.com/proxymock/grpc/long-lived-streams/), which the mock serves as one stream. proxymock and cloud capture both record streamed calls.

<a id="record-a-subscriber-in-your-cluster"></a>

## Record a subscriber in your cluster

eBPF capture and the legacy sidecar record a subscriber's `StreamingPull` with no extra setting, including the messages it received. Check that the recording holds `/google.pubsub.v1.Subscriber/StreamingPull` calls with messages before you create a snapshot from it.

A recording that holds the subscriber's `Acknowledge` and `ModifyAckDeadline` calls but no `StreamingPull` was made with `GRPC_STREAMING_ENABLED=false` set on goproxy. That setting selects the older writer, which drops a stream the client cancels, and a subscriber always ends its `StreamingPull` that way. Remove it and record again.

<a id="mock-a-pubsub-subscriber"></a>

## Mock a Pub/Sub subscriber

When the service under test is a Pub/Sub subscriber, `proxymock mock` and the Speedscale responder answer its subscriber calls from the messages recorded for its subscription, so it runs with no Google Cloud project and no emulator. The Google client libraries call Pub/Sub over gRPC, and a high-level subscriber opens a bidirectional `StreamingPull` stream and acknowledges messages with separate unary `Acknowledge` and `ModifyAckDeadline` calls. Its keepalives, lease extensions and acknowledgement batches differ on every run, so the mock does not match these calls by signature.

Record the subscriber with proxymock, which records `StreamingPull` streams, including the long-lived streams a subscriber keeps open and ends by cancelling (see [long-lived gRPC streams](https://docs.speedscale.com/proxymock/grpc/long-lived-streams/)). Cloud capture records it the same way, as described in [record a subscriber in your cluster](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#record-a-subscriber-in-your-cluster). Then run the mock with the same mapping you recorded with, as for any [gRPC dependency](https://docs.speedscale.com/proxymock/grpc/mock-a-grpc-dependency/). With the emulator, set `PUBSUB_EMULATOR_HOST` to the mapped port.

| Call | What the mock does |
| --- | --- |
| `StreamingPull` | Matches the stream by the subscription in its first request only. Pushes the messages recorded for that subscription, with their data, attributes, ordering key and message ID, at the pace they arrived in the recording. Then keeps the stream open until the client cancels it. |
| `Pull` | Answers from the same recorded messages, up to `max_messages`, and returns an empty response once none are left. |
| `Acknowledge` | Ends the delivery of each ack ID the mock handed out, and answers success whatever the ack IDs. |
| `ModifyAckDeadline` | Extends the ack deadline of each delivery, or redelivers it when the deadline is 0 seconds (a nack), and answers success whatever the ack IDs. |
| `Publish` | Answered by topic, see [mock a publisher](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-publisher). |
| Other subscriber calls such as `GetSubscription` | Matched by signature, like any other gRPC call. |

The mock answers the four subscriber calls this way for a Pub/Sub host once the recording holds at least one of them for that host.

The mock uses the messages of every recorded `StreamingPull` and `Pull` call for the subscription, in the order they were recorded, including streams recorded as several parts and streams the client cancelled. Each message is sent once at its first recorded delivery, however many times it was delivered in the recording, because the mock redelivers what your subscriber nacks or lets expire. Use `proxymock mock --grpc-streaming-immediate` to send the messages without the recorded gaps.

The mock honors the `max_outstanding_messages` and `max_outstanding_bytes` that the client sends in its first `StreamingPull` request. It stops sending while the messages it sent and the client has not acknowledged reach either limit, and splits a recorded response when only part of it fits. An acknowledgement frees room whether it arrives on the stream or as an `Acknowledge` call, and so does a nack, which is a `ModifyAckDeadline` of 0 seconds. A lease extension frees nothing, and keepalives are ignored.

Each recorded message is sent once per mock instance and subscription, unless you [serve more than the recorded volume](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#serve-more-than-the-recorded-volume). Two subscribers on the same subscription share the recorded messages, as they share a real subscription, instead of both receiving all of them. A `Pull` takes from the same messages, so it gets only what the streams have not taken. Restart or reload the mock to send the messages again.

A `StreamingPull` for a subscription with no recorded `StreamingPull` or `Pull` call returns `NOT_FOUND`. A `Pull` for such a subscription goes to the normal gRPC match instead, which can answer it from a `Pull` recorded by an older release. A subscription whose recordings hold no messages keeps its stream open and answers `Pull` with an empty response.

Every call is saved to the mock's observed output as a match or a miss. A `StreamingPull` is saved when the stream ends, with the requests the client sent and the messages the mock sent.

The mock does not simulate exactly-once delivery or ordering-key delivery rules.

<a id="redelivery"></a>

### Redelivery

The mock redelivers a message the way Pub/Sub does when no retry policy is set:

*   A nack, which is a `ModifyAckDeadline` of 0 seconds on the stream or as a unary call, redelivers the message at once.
*   A message left unacknowledged past its ack deadline is redelivered. That includes a message outstanding on a stream the client cancelled or the mock dropped.
*   A redelivery has a new ack ID and the next `delivery_attempt`, counting the first delivery as 1. The message itself, its message ID included, is unchanged.
*   An ack with the old ack ID no longer ends the redelivered message.

The ack deadline of a `StreamingPull` delivery is the `stream_ack_deadline_seconds` of the stream. A `ModifyAckDeadline` with more than 0 seconds extends it from the time it arrives. A `Pull` delivery has the Pub/Sub default deadline of 10 seconds, because the subscription's own deadline is not in the recording.

Redelivery lets a recording test your subscriber's retry path, a poison message it keeps nacking, and the dead-letter handling it does itself. The mock has no dead-letter topic of its own.

<a id="faults-and-chaos"></a>

### Faults and chaos

The test config's [chaos rules](https://docs.speedscale.com/concepts/chaos/) and the [`proxymock mock --fault`](https://docs.speedscale.com/reference/proxymock-cli-reference/#mock) rules apply to `StreamingPull`, `Pull`, `Acknowledge`, `ModifyAckDeadline` and `Publish`. A rule sees each unary call once, and each `StreamingPull` once when the stream opens:

| Effect | Unary call | `StreamingPull` |
| --- | --- | --- |
| Latency | Delays the response. | Delays every message the stream sends. |
| Status code | Fails the call with the gRPC code a client reads from that HTTP status: 429, 502, 503 and 504 are `UNAVAILABLE`, 401 is `UNAUTHENTICATED`, 403 is `PERMISSION_DENIED`, 404 is `UNIMPLEMENTED`, 400 is `INTERNAL`, and others are `UNKNOWN`. | Ends the stream with that code before it sends anything. |
| No response | Leaves the call unanswered until the client gives up. | Keeps the stream open without sending anything. |
| Connection refuse, reset or stall | Faults the connection before anything is answered. | Faults the connection before anything is sent. |
| Connection drop | Sends part of the response, then cuts the connection. | Sends the first message, then cuts the connection. |

A call a fault stops changes nothing: a failed `Acknowledge` leaves its messages outstanding, and a failed `Pull` or `StreamingPull` hands nothing out. A message the mock sent before it dropped the connection stays outstanding until its ack deadline passes, and is then redelivered. Body, header and payload effects do not apply to Pub/Sub calls. Each perturbed call is marked in the observed output, as any other chaos is.

For example, this fails one `Acknowledge` in four with `UNAVAILABLE`, so your subscriber has to retry its acks:

```bash
proxymock mock --in proxymock/recorded-<timestamp> --fault 'Acknowledge:rate=1/4'
```

<a id="serve-more-than-the-recorded-volume"></a>

### Serve more than the recorded volume

By default the mock sends each recorded message once. To load test a subscriber offline, with no Google Cloud project and no emulator, serve the recorded messages several times or without end:

```bash
proxymock mock --in proxymock/recorded-<timestamp> --pubsub-passes 10
```

`--pubsub-passes` takes a whole number, or `loop` to start again each time the messages run out. In a test config, set `responder.pubsub`:

```json
{
  "responder": {
    "pubsub": {
      "passes": 10
    }
  }
}
```

Set `"loop": true` instead of `passes` to serve without end. A `--pubsub-passes` flag wins over the test config.

The first pass sends the messages as recorded. Every later pass sends them with new ack IDs and new message IDs, so a subscriber that deduplicates on the message ID processes them again. Each pass keeps the recorded gaps between messages unless you also use `--grpc-streaming-immediate`. A subscriber that deduplicates on a field inside the message data still sees the recorded data on every pass.

<a id="deliver-faster-or-slower-than-recorded"></a>

### Deliver faster or slower than recorded

The mock sends each `StreamingPull` delivery after the gap recorded before it. To replay the deliveries at a different speed, multiply every recorded gap:

```bash
proxymock mock --in proxymock/recorded-<timestamp> --pubsub-passes loop --pubsub-gap-multiple 0.5
```

A multiple of `0.5` delivers twice as fast as recorded, `2` delivers at half speed, and `1` keeps the recorded pace. The multiple applies to every pass, including `loop`. In a test config, set `gapMultiple` next to `passes`, which also works for a replay in your cluster:

```json
{
  "responder": {
    "pubsub": {
      "loop": true,
      "gapMultiple": 0.5
    }
  }
}
```

The multiple must be a number greater than zero, and the test config validation rejects `0`, negative numbers, `NaN` and `Infinity`. A `--pubsub-gap-multiple` flag wins over the test config. `--grpc-streaming-immediate` wins over the multiple and sends each delivery as soon as the subscriber's flow control allows. A latency from a chaos or fault rule is added after the gap is scaled, so `--pubsub-gap-multiple 0.5` with a 400ms latency turns a recorded 600ms gap into 700ms. The multiple paces Pub/Sub `StreamingPull` only, not other gRPC streams.

<a id="mock-a-pubsub-publisher"></a>

## Mock a Pub/Sub publisher

When the service under test publishes to Pub/Sub, the mock answers its `Publish` calls by topic instead of by signature. A client library batches messages by count, size and delay, and messages often carry timestamps or IDs, so a signature match of the whole request would miss.

The mock answers a `Publish` to any topic that the recording holds a `Publish` to on the same host. It returns a new message ID for each message, whatever the messages hold and however they are batched. A `Publish` to a topic the recording never published to is matched by signature, like any other gRPC call.

Each published message is saved to the observed output as its own `Publish` call, with that one message and its message ID, so a comparison with the recording sees messages instead of batches. The call is tagged with `pubsubTopic`, `pubsubMessageId`, and `pubsubPublishCall`, which the messages of one batch share.

<a id="catch-a-publisher-regression"></a>

## Catch a publisher regression

When the service under test publishes, its `Publish` calls are outbound calls, so a replay mocks them. With the [`httpOutput` assertion](https://docs.speedscale.com/reference/configuration/assertions/httpoutput/#google-pubsub-publishes) in the test config, the replay also compares what the service published with the recording.

It compares each published message on its own, grouped by topic, so a client library that batches the messages differently is not a difference. JSON data is compared field by field, along with each attribute and the ordering key. A changed amount or event type is reported on its field, such as `data.amount` or `attributes.eventType`, while IDs and timestamps that differ in every message are not compared. A message sent to another topic, or one fewer message than recorded, is reported too.

To compare only one topic, set `includeOnly` to its endpoint:

```json
{
  "type": "httpOutput",
  "config": {
    "includeOnly": "/google.pubsub.v1.Publisher/Publish/projects/shop/topics/orders"
  }
}
```

<a id="drive-a-subscriber-by-republishing"></a>

## Drive a subscriber by republishing

When the service under test is a subscriber, replaying its recorded calls to Pub/Sub would pull from the live subscription instead of feeding your service. Republish mode turns each message a recorded `StreamingPull` or `Pull` call received into a `Publish` of the same data, attributes and ordering key to the subscription's topic. Your subscriber then receives the messages again and acknowledges them itself.

The recorded `Acknowledge`, `ModifyAckDeadline` and other subscriber calls are not replayed, because your subscriber makes them. `Publish` calls your service made still replay as gRPC.

Each message is one request on the report, shown as `/google.pubsub.v1.Publisher/Publish` with the topic it went to. The latency is the time Pub/Sub took to accept the message, not the time your subscriber took to process it. A message Pub/Sub refuses fails the request.

Whether your subscriber kept up is measured separately, from the subscription's Cloud Monitoring metrics and from your subscriber's own acks. See [Check that the subscriber kept up](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#check-that-the-subscriber-kept-up).

<a id="turn-on-republish"></a>

### Turn on republish

Add `generator.pubsub` to the test config:

```json
{
  "generator": {
    "pubsub": {
      "republish": true
    }
  }
}
```

The topic is looked up from the subscription with `GetSubscription`, so the replay's credentials need `pubsub.subscriptions.get` on the subscription and `pubsub.topics.publish` on the topic. To publish to another topic, or when the replay cannot read the subscription, map the subscription to a topic with full names:

```json
{
  "generator": {
    "pubsub": {
      "republish": true,
      "subscriptionTopics": {
        "projects/shop/subscriptions/orders-worker": "projects/shop-staging/topics/orders"
      }
    }
  }
}
```

<a id="credentials-and-endpoint"></a>

### Credentials and endpoint

Without credentials in the test config, the replay uses Application Default Credentials, such as Workload Identity on GKE or `gcloud auth application-default login` on your machine.

To use a service account key, store the key file in a secret and reference it in `credentialsJson`. Speedscale mounts the secret into the generator, so it only has to exist in the namespace of the workload you replay. Do not paste the key itself, because a literal value is stored with the test config:

```json
{
  "generator": {
    "pubsub": {
      "republish": true,
      "credentialsJson": "${{secret:pubsub-replay/key.json}}"
    }
  }
}
```

With proxymock you can set `credentialsFile` to the path of a key file on your machine instead. Service account, authorized user, impersonated service account and external account files are accepted.

Set `endpoint` to a `host:port` such as `us-east1-pubsub.googleapis.com:443` to publish through a regional endpoint.

<a id="replay-into-the-pubsub-emulator"></a>

### Replay into the Pub/Sub emulator

Set `emulatorHost` to the emulator's `host:port`, or set the `PUBSUB_EMULATOR_HOST` environment variable as the Google client libraries do. The emulator is reached in plaintext without credentials, and `emulatorHost` wins over `endpoint`. Create the topic and the subscription in the emulator before the replay starts, as your subscriber's own setup would.

<a id="replay-in-your-cluster"></a>

### Replay in your cluster

**1\. Choose the subscriber's calls as the replay's tests** when you create the snapshot. A subscriber's calls to Pub/Sub are outbound, so a replay mocks them by default:

```bash
speedctl create snapshot --name orders-worker --service orders-worker --tests-filter '(location CONTAINS "google.pubsub.v1.Subscriber")'
```

In the dashboard, open the snapshot's **Traffic** tab and use **Choose replay tests** instead. [Choose What a Replay Tests](https://docs.speedscale.com/proxymock/guides/choose-replay-tests/) covers the filter syntax.

**2\. Replay the snapshot** with a test config that turns on republish. Leave Pub/Sub unmocked with `--mock-except`, so your subscriber reads the republished messages from Pub/Sub, while its other dependencies, such as its database and the HTTP services it calls, stay mocked:

```bash
speedctl infra replay orders-worker --snapshot-id <snapshot-id> --test-config-id <test-config-id> --mock-except 'host:pubsub.googleapis.com'
```

Use the host your subscriber recorded, such as `us-east1-pubsub.googleapis.com` for a regional endpoint. Add `--dry-run-mocks` to print which services the replay will mock before you run it. [Controlling Outbound Mocks](https://docs.speedscale.com/guides/replay/via-speedctl/#controlling-outbound-mocks) covers the selector syntax.

Keep the other dependencies mocked to catch regressions. A republished message passes when Pub/Sub accepts it, whatever your subscriber then does with it. The report's Pub/Sub metrics show whether your subscriber acked the messages, but what it did with them is visible only in the calls it makes downstream. The [`httpOutput` assertion](https://docs.speedscale.com/reference/configuration/assertions/httpoutput/) compares those calls with the recording, and it needs the responder that `--no-mocks` turns off.

<a id="replay-locally-with-proxymock"></a>

### Replay locally with proxymock

Run your subscriber against the emulator or a test project, then replay the recorded deliveries with a test config that turns on republish:

```bash
PUBSUB_EMULATOR_HOST=localhost:8085 proxymock replay --in proxymock/recorded-<timestamp> --tests-filter '(location CONTAINS "google.pubsub.v1.Subscriber")' --test-config pubsub-republish
```

See [test configs](https://docs.speedscale.com/proxymock/guides/test-configs/) for where `pubsub-republish` lives.

<a id="check-that-the-subscriber-kept-up"></a>

### Check that the subscriber kept up

After the last message is published, the replay waits for the subscription's backlog to drain before the report closes, so acks that arrive late still count. The wait ends as soon as Cloud Monitoring shows no undelivered messages in a sample taken after the last publish, or after `drainTimeout`. Cloud Monitoring publishes Pub/Sub samples a minute or more late, so expect the wait to take at least that long.

The report then gets the subscription's Cloud Monitoring metrics for the replay. They are read with the replay's own credentials, which need `monitoring.timeSeries.list` (in `roles/monitoring.viewer`) on the subscription's project:

| Metric | What it measures |
| --- | --- |
| `pubsubBacklogMax` | The most undelivered messages on the subscription during the replay |
| `pubsubBacklogEnd` | Undelivered messages when the replay ended |
| `pubsubOldestUnackedAgeMax` | The longest any message waited unacked, in seconds |
| `pubsubAckRate` | Acks per second, over the minutes the subscription acked messages |
| `pubsubExpiredAckDeadlineCount` | Ack deadlines that expired during the replay |
| `pubsubSubscriptionAckLatencyP95` | The subscription's ack latency p95 in its worst minute, in milliseconds |

These metrics count every message on the subscription, including any backlog from before the replay and messages from other publishers on the same topic.

The emulator has no Cloud Monitoring metrics. When the replay publishes to the emulator, or its credentials cannot read Cloud Monitoring, the report says so in a replay event and the replay carries on without these metrics. Without them there is no backlog to watch, so the replay waits for the ack window after the last publish instead.

Where your subscriber's own Pub/Sub calls are captured with the replay, each republished message is also checked. The message ID Pub/Sub gave it is followed through your subscriber's `StreamingPull` or `Pull` delivery to its ack, whether the ack went on the stream or as an `Acknowledge` call:

| Metric | What it measures |
| --- | --- |
| `pubsubRepublishedCount` | Messages Pub/Sub accepted |
| `pubsubAckedPct` | Republished messages acked within the ack window |
| `pubsubUnackedCount` | Republished messages not acked within the ack window, late acks included |
| `pubsubAckLatencyP50`, `pubsubAckLatencyP95`, `pubsubAckLatencyMax` | Time from delivery to ack, in milliseconds |
| `pubsubRedeliveryCount` | Deliveries of a republished message after its first |

With proxymock, pass `--mocks-out` with the directory `proxymock mock` wrote while your subscriber ran through it, and the replay reads your subscriber's calls from there. In your cluster, the report sees only the calls that went through the responder, so with Pub/Sub left out of mocking the messages are not checked one by one. The report says so in a notice, and the Cloud Monitoring metrics are the measure there.

Set how long your subscriber has to ack each message, and how long the replay waits for the backlog to drain:

```json
{
  "generator": {
    "pubsub": {
      "republish": true,
      "ackWindow": "30s",
      "drainTimeout": "2m"
    }
  }
}
```

`ackWindow` defaults to one minute. `drainTimeout` defaults to five minutes, and `0s` turns the wait off.

A message not acked within the ack window adds a warning to the report. When your subscriber's calls were not captured, the warning comes from the subscription's oldest unacked message instead: it fires when a message waited longer than the ack window. To fail the replay instead of warning, add a goal on the metric:

```json
{
  "rules": [
    { "metricName": "pubsubUnackedCount", "type": "TOO_HIGH", "value": 0, "action": "ALERT" },
    { "metricName": "pubsubBacklogEnd", "type": "TOO_HIGH", "value": 0, "action": "ALERT" },
    { "metricName": "pubsubAckLatencyP95", "type": "TOO_HIGH", "value": 500, "action": "ALERT" }
  ]
}
```

In a replay that republished messages, a goal on a Pub/Sub metric the replay could not measure fails as not measured, so a subscriber whose acks nobody saw cannot pass. With proxymock without `--mocks-out`, such a goal is listed as not evaluated, with the reason.

<a id="load-test-a-subscriber"></a>

### Load test a subscriber

A virtual-user stage with no request delay publishes as fast as it can. Set the stage's request delay to `RECORDED` to preserve the gaps between recorded deliveries or use `MULTIPLE` to scale them. A multiple of `0.5` halves every gap. Raise the number of vUsers to increase volume. Each vUser publishes the entire recording again. With proxymock, use `--vus` for concurrency or `--times` for repetitions. See [Pace and load](https://docs.speedscale.com/proxymock/message-brokers/test-a-consumer/#pace-and-load).

To find the rate your subscriber can sustain, raise the load until the backlog stops draining. Goals on `pubsubBacklogEnd`, `pubsubOldestUnackedAgeMax` or `pubsubAckLatencyP95` fail the replay at the point your subscriber falls behind.

Messages that share an ordering key are published in recorded order within one vUser. Pub/Sub delivers them in order only when the subscription has message ordering turned on.

<a id="give-every-vuser-its-own-keys"></a>

### Give every vUser its own keys

Every vUser republishes the same data. A subscriber that deduplicates on a business key, such as an order ID, then skips the copies and does less work than it would in production, so the load test looks better than it should. Add a transform that rewrites the key in each message with the [`pubsub_message`](https://docs.speedscale.com/guides/transformation/extractors/pubsub_message/) extractor:

```json
{
  "filters": {
    "filters": [{ "include": true, "detectedLocation": "/google.pubsub.v1.Publisher/Publish", "operator": "CONTAINS" }]
  },
  "extractor": {
    "type": "pubsub_message",
    "config": { "field": "data" }
  },
  "transforms": [
    { "type": "json_path", "config": { "path": "orderId" } },
    { "type": "rand_string", "config": { "pattern": "ord-[a-z0-9]{12}" } }
  ]
}
```

`pubsub_message` hands the message's data to `json_path`, which reaches the `orderId` field, and `rand_string` gives every published message a new value. To rewrite an attribute instead, set `name` to its key. The same extractor works on the `Publish` calls a publisher recorded.

Republished messages get new message IDs and publish times. Exactly-once delivery is not simulated.

<a id="rest-clients"></a>

## REST clients

A client on the Pub/Sub REST API, such as the PHP library without its gRPC extension, calls custom methods over HTTP instead of gRPC. Capture records each call as HTTP with JSON bodies, in which message `data` is base64. The mock and republish read these calls as the gRPC calls they stand for:

| REST call | Same as | What the mock does |
| --- | --- | --- |
| `POST /v1/projects/*/subscriptions/*:pull` | `Pull` | Answers from the messages recorded for the subscription in the path, up to `maxMessages`. |
| `POST /v1/projects/*/subscriptions/*:acknowledge` | `Acknowledge` | Ends the delivery of each ack ID, and answers `{}` whatever the ack IDs. |
| `POST /v1/projects/*/subscriptions/*:modifyAckDeadline` | `ModifyAckDeadline` | Extends each delivery, or redelivers it when `ackDeadlineSeconds` is 0, and answers `{}`. |
| `POST /v1/projects/*/topics/*:publish` | `Publish` | Answers a publish to a recorded topic with a new message ID for each message. |

The mock answers these calls for a Pub/Sub host once the recording holds a subscriber call, REST or gRPC, for that host. REST and gRPC calls share the recorded messages. A subscription recorded over REST serves a gRPC subscriber, a subscription recorded over gRPC serves a REST one, and each message is handed out once across both, as described in [mock a subscriber](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#mock-a-pubsub-subscriber). A topic recorded with either API answers a publish on the other.

A pull that finds no message ready waits up to one second for a nacked or expired message to come back before it answers `{}`, as Pub/Sub holds an idle pull open. A pull with `returnImmediately` set answers at once.

The mock refuses a request Pub/Sub would refuse with the REST error Pub/Sub sends. A pull with `maxMessages` of 0, for example, gets HTTP 400 with `"status": "INVALID_ARGUMENT"`. A pull of a subscription with no recorded `:pull`, `Pull` or `StreamingPull` call, and a publish to a topic never published to, are matched by signature like any other HTTP request.

The mock answers these calls through the same path as any HTTP match, so response transforms and chaos rules apply to them. A fault that fails a pull leaves its messages outstanding until their ack deadline passes, 10 seconds for a pull, and then redelivers them.

Each REST call is saved to the observed output as one call. A REST publish is tagged `pubsubTopic` and `pubsubMessageId`, which lists the message IDs the mock returned, separated by commas. Unlike a gRPC `Publish`, it is not split into one call per message, so [`httpOutput`](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#catch-a-publisher-regression) compares the whole call with the recorded one.

To drive a REST subscriber by republishing, choose its `:pull` calls as the replay's tests. Their messages are republished as gRPC `Publish` calls, like the messages of a recorded `Pull`, and its `:acknowledge` and `:modifyAckDeadline` calls are left to your subscriber:

```bash
speedctl create snapshot --name orders-worker --service orders-worker --tests-filter '(location CONTAINS ":pull")'
```

The ack metrics in [check that the subscriber kept up](https://docs.speedscale.com/guides/message-brokers/google-pubsub/#check-that-the-subscriber-kept-up) read a REST subscriber's own `:pull` and `:acknowledge` calls as they read the gRPC ones.

<a id="push-subscriptions"></a>

## Push subscriptions

A push subscription has Pub/Sub send each message to your service as an HTTP `POST` to the push endpoint, and your service acks it by answering with a 2xx status. The body is a JSON envelope:

```json
{
  "message": {
    "data": "eyJvcmRlciI6MX0=",
    "attributes": { "type": "created" },
    "messageId": "2070443601311540",
    "publishTime": "2026-11-16T09:00:00.000Z"
  },
  "subscription": "projects/shop/subscriptions/orders-push"
}
```

Capture records each push as an inbound HTTP request, so a replay sends the recorded pushes to your service like any other inbound traffic, at their recorded pace, and compares its responses with the recording. Republish and a Pub/Sub project are not needed. To multiply the load, raise the number of vUsers, as for any HTTP service.

<a id="replace-the-push-token"></a>

### Replace the push token

When the subscription has authentication turned on, Pub/Sub sends each push with a Google-signed OIDC token in the `Authorization: Bearer` header. The token expires an hour after Google issued it, so a service that verifies it rejects the recorded token on replay, usually with 401 or 403.

If your service does not verify the token itself, because Cloud Run or Identity-Aware Proxy checks it in front of your service and the replay sends straight to your service, there is nothing to do.

Otherwise give each replayed push a fresh token that your service accepts. It must be signed by Google, carry the audience your service checks, which is often the push endpoint URL and not the replay's target, and carry the email of the service account your service expects. The [`token_fetch`](https://docs.speedscale.com/guides/transformation/transforms/token_fetch/) transform requests one during the replay.

In your cluster, when the generator [runs as the push service account](https://docs.speedscale.com/guides/replay/generator-service-account/), ask the GKE metadata server for an ID token. `format=full` adds the `email` claim that most verifiers check. An ID token lasts an hour, so `ttl` reuses each one for 50 minutes:

```json
{
  "filters": {
    "filters": [{ "include": true, "detectedLocation": "/push/orders", "operator": "CONTAINS" }]
  },
  "extractor": { "type": "http_req_header", "config": { "name": "Authorization" } },
  "transforms": [
    {
      "type": "token_fetch",
      "config": {
        "grant": "request",
        "method": "GET",
        "url": "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://orders.example.com/push/orders&format=full",
        "headers": "{\"Metadata-Flavor\":\"Google\"}",
        "tokenPath": "@body",
        "ttl": "50m"
      }
    }
  ]
}
```

When the generator runs as another service account, have it mint a token for the push service account with the IAM Credentials API instead. The generator's service account needs the Service Account OpenID Connect Identity Token Creator role (`roles/iam.serviceAccountOpenIdTokenCreator`) on the push service account. The nested `google` fetch gets the generator's own access token from the metadata server, and the outer request exchanges it for an ID token:

```json
{
  "type": "token_fetch",
  "config": {
    "grant": "request",
    "method": "POST",
    "url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/pubsub-push@shop.iam.gserviceaccount.com:generateIdToken",
    "headers": "{\"Authorization\":\"Bearer ${{fetch:google}}\"}",
    "body": "{\"audience\":\"https://orders.example.com/push/orders\",\"includeEmail\":true}",
    "tokenPath": "token",
    "ttl": "50m",
    "fetches": "{\"google\":{\"grant\":\"request\",\"method\":\"GET\",\"url\":\"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token\",\"headers\":{\"Metadata-Flavor\":\"Google\"}}}"
  }
}
```

With proxymock on your machine there is no metadata server. Mint a token with `gcloud` before the replay:

```bash
export PUSH_TOKEN=$(gcloud auth print-identity-token --impersonate-service-account=pubsub-push@shop.iam.gserviceaccount.com --audiences=https://orders.example.com/push/orders --include-email)
```

Then send it with the [`constant`](https://docs.speedscale.com/guides/transformation/transforms/constant/) transform. The token lasts an hour, so this suits a replay that finishes within that time:

```json
{
  "extractor": { "type": "http_req_header", "config": { "name": "Authorization" } },
  "transforms": [
    { "type": "constant", "config": { "new": "Bearer ${{env_var:PUSH_TOKEN}}" } }
  ]
}
```
