AWS re:Invent happy hour: Dec 1, 6 PM PST at MGM Grand RSVP

Blue capsules travel through a sorter while an amber capsule circles back along a clear track.

How to Test a Google Pub/Sub Subscriber


A Google Pub/Sub publish can succeed while the worker that processes it is falling behind. A unit test that calls your handler with one JSON object can check the business logic, but it skips the part where the worker has to nack a delivery, see it again, and acknowledge it with a fresh ack ID.

This walkthrough uses the Go order worker in mock-lab’s gRPC lab. You’ll capture three synthetic order events with proxymock, force a retry against the recording, and republish the same events into a fresh test broker. The worker runs the same receive and acknowledgement code in each step.

StepWhere deliveries come fromWhat passes
CaptureAn in-memory Pub/Sub brokerThe worker acks three seeded events and the recording contains its StreamingPull call
Mockproxymock serves the recordingThe nacked message comes back with a fresh ack ID, and the worker acks six distinct messages across two passes
RepublishA fresh instance of the in-memory brokerThe broker accepts three publishes and the worker acks three messages

1. Record the worker’s Google Pub/Sub stream

Use Bash, Git, Make, Go 1.26 or newer, nc, and a current, initialized proxymock with Pub/Sub replay support. The lab needs free local ports 8085 and 18085 plus the default proxymock ports. The broker is the Go Pub/Sub client’s in-memory fake, so the exercise needs no Google Cloud project or Google credentials. Install and initialize the proxymock CLI.

git clone https://github.com/speedscale/mock-lab.git
cd mock-lab/labs/grpc
make pubsub-record

The target creates the orders topic and its orders-worker subscription in the local broker on port 8085. The worker opens a bidirectional StreamingPull through proxymock on port 18085. A separate process seeds three JSON order events directly into the broker about 400 ms apart. That puts the worker’s deliveries and acks in the capture while keeping the seed publisher’s requests out of it.

Look for ACKED 3 messages. The target checks that it wrote a /google.pubsub.v1.Subscriber/StreamingPull call under proxymock/results/pubsub/recorded. It stops the recorder after the worker closes the stream so the capture is ready for the next step. If you need another capture, set PUBSUB_RECORDING to a fresh directory and keep that setting for both follow-up targets.

AI coding assistant prompt for recording
Use my existing mock-lab clone or clone https://github.com/speedscale/mock-lab.git. From labs/grpc, check the prerequisites in the Pub/Sub subscriber README and run make pubsub-record. Use the local in-memory broker and leave the capture available for the next steps. Report the recording path, whether it contains StreamingPull, and how many messages the worker acknowledged. If a prior capture exists, set PUBSUB_RECORDING to a fresh directory and keep using it.

2. Nack one message and verify redelivery

make pubsub-mock

This time proxymock answers StreamingPull from the recording on port 18085, with the in-memory broker stopped. The worker asks for one outstanding message at a time. It calls ModifyAckDeadline with zero seconds on the first delivery, then checks that the same message ID returns with a fresh ack ID and delivery_attempt=2. The worker uses that new ack ID to acknowledge the redelivery.

Check three lines in the output. The ID shown by NACK and REDELIVERED must match, the redelivery line must contain attempt=2 fresh_ack_id=true, and the worker must finish with ACKED 6 messages. The six acknowledgements come from two passes of three events. The retry adds a delivery without adding another distinct message.

The target uses --pubsub-passes 2 and --pubsub-gap-multiple 0.5. The second pass gives the same payloads new message IDs. The gap multiplier halves the recorded gaps on StreamingPull, subject to the client’s flow control. A worker that deduplicates by orderId will still see repeated business keys. Account for that before treating two passes as twice the processing work. The mock also redelivers when a lease expires. Use a test broker for scenarios that depend on exactly-once delivery, ordering-key delivery rules, or dead-letter routing. Google Pub/Sub mock behavior · Considerations for testing gRPC streams.

AI coding assistant prompt for checking redelivery
From labs/grpc in the same mock-lab clone, run make pubsub-mock against the capture from step 1. Check that the message ID in the NACK line is the same as in the REDELIVERED line, that attempt is 2 with a fresh ack ID, and that the worker reports ACKED 6 messages. Report the process exit status and the path to the mock log if a check fails.

3. Republish the recording into a fresh broker

make pubsub-republish

The target starts a fresh broker with an empty subscription, then connects the worker directly to it. The proxymock replay command selects recorded Subscriber RPCs and loads a test config with generator.pubsub.republish enabled. Each captured delivery becomes a new Publish to the topic behind the recorded subscription. The worker makes its own ack calls, and the broker assigns the message IDs for this run.

Check both outputs. The replay gates on exactly three requests and zero failed requests, then the worker must report ACKED 3 messages. A publish success measures broker acceptance. The worker’s output is the separate proof that this subscriber received and acknowledged the messages. Each run keeps its logs and observed traffic under a new .run/pubsub.* directory.

The lab sends this small batch as quickly as the replay can publish it. For a sustained replay, choose a stage with recorded request delay to reproduce observed gaps, or choose a multiple of recorded delay to change the rate. Raising vUsers repeats the recording per vUser. If the worker deduplicates on a business key, apply a pubsub_message transform to give each copy its own key. Subscriber load and message transforms.

AI coding assistant prompt for verifying republish
From the same labs/grpc directory, run make pubsub-republish using the recording from step 1. Verify that the replay reports three requests and zero failed requests and that the worker independently reports ACKED 3 messages. Check that the worker acknowledged ord-001, ord-002, and ord-003. Report any error with its log path. Use the local broker only.

4. Turn the two checks into replay goals

With a real Pub/Sub test project, start on an isolated subscription. For a cluster replay, run speedctl infra replay with --mock-except 'host:pubsub.googleapis.com', using the hostname your worker recorded. The worker reads from Pub/Sub while its other dependencies can stay mocked, so you can compare the calls it makes after receiving an event. Give the replay’s credentials pubsub.topics.publish on the target topic and pubsub.subscriptions.get on the subscription, or configure an explicit subscription-to-topic mapping. The report reads the subscription’s Cloud Monitoring metrics with the same credentials, so they also need monitoring.timeSeries.list, which roles/monitoring.viewer grants on the subscription’s project. Speedscale’s cluster replay recipe.

QuestionSpeedscale report signalWhere it comes from
Did the subscription drain after the burst?pubsubBacklogEndCloud Monitoring
Did a message wait too long for an ack?pubsubOldestUnackedAgeMax in secondsCloud Monitoring
Did processing slow down?pubsubSubscriptionAckLatencyP95 in milliseconds, from the subscription’s worst minuteCloud Monitoring
Was each republished message acked within the window, and how fast?pubsubUnackedCount and pubsubAckLatencyP95The worker’s own Pub/Sub calls, when they go through proxymock mock during a local replay
Did a publisher change the events it emitted?httpOutput compares gRPC publishes by topic and per message, including JSON fields, attributes, and the ordering keyA replay of the publisher

The in-memory broker in this walkthrough provides no Cloud Monitoring data. In the cluster recipe, Pub/Sub is left out of mocking, so the report cannot follow each republished message to its ack and says so in a notice. Use the Cloud Monitoring metrics there. In a cloud test config for an isolated subscription, set an ALERT goal on pubsubBacklogEnd with type TOO_HIGH and value 0. That fails the run when the backlog is still above zero at the end of the drain period. Add a TOO_HIGH goal on pubsubSubscriptionAckLatencyP95 set to the worker’s latency budget. The per-message metrics apply to a local proxymock replay whose worker runs through proxymock mock, with the mock’s output directory passed as --mocks-out. Step 3 connects the worker straight to the broker, so it does not produce them. In a republish replay, a goal on a Pub/Sub metric the run could not measure fails as not measured, so set goals only on metrics your setup produces. Subscriber outcomes and goal behavior · Publisher regression checks.

Keep the redelivery check in your fast feedback loop. Run the broker-backed test when you need to know whether your Google Pub/Sub subscriber drains a realistic burst. Those checks catch different failure modes from the same recorded events. Try proxymock.

Frequently asked questions

Can I test a Google Pub/Sub subscriber without a Google Cloud project?

Yes. The lab captures and republishes against the Go Pub/Sub client's in-memory broker. The mock step serves the same recording with that broker stopped.

What is the difference between a redelivery and a new pass through the recording?

A redelivery keeps the message ID and gets a fresh acknowledgement ID. Each additional pass gives the recorded payloads fresh message IDs, so a consumer that deduplicates by message ID processes them again.

Can I use this example for a push subscription?

A push subscription delivers an HTTP request to your handler. Record and replay those inbound HTTP requests directly. The StreamingPull and republish steps here apply to a pull subscriber.

Why can publish latency stay flat while the subscriber falls behind?

Publish latency ends when the broker accepts the message. Use backlog and subscriber acknowledgement measurements to see when processing slows down.

Stop writing API mocks by hand

proxymock records real traffic from your running app and replays it as mocks for HTTP, gRPC, Postgres, Kafka, and more. Install locally, activate once, and start recording.