Skip to main content

Google Cloud Pub/Sub

Relayer.GooglePubSub wraps Google.Cloud.PubSub.V1 3.x. Native publishing, streaming pull, ordering, lease extension, flow control, recovery and acknowledgement remain owned by Google's client. Relayer composes its generated dispatch, serialization, failure handling and tracing around those operations. Install it with dotnet add package Relayer.GooglePubSub.

Register topics and subscriptions​

Supply prepared PublisherServiceApiClient and SubscriberServiceApiClient instances. They and their channels remain caller-owned. For a regular JIT application, Google's native builders can prepare them with application default credentials:

using Google.Cloud.PubSub.V1;
using Relayer;
using Relayer.GooglePubSub;

var publisher = await new PublisherServiceApiClientBuilder().BuildAsync();
var subscriber = await new SubscriberServiceApiClientBuilder().BuildAsync();
var topic = TopicName.FromProjectTopic("my-project", "orders");
var deadLetter = TopicName.FromProjectTopic("my-project", "orders-dead");
var subscription = SubscriptionName.FromProjectSubscription("my-project", "billing");

services.AddRelayer(relayer =>
{
relayer.AddMessageTypesFromThisAssembly();
relayer.GooglePubSub("events", pubsub =>
{
pubsub.TopologyMode = TopologyMode.Provision;
pubsub.Options.Configure(options =>
{
options.Publisher = publisher;
options.Subscriber = subscriber;
options.PublisherSettings = new() { EnableMessageOrdering = true };
options.Topics.Add(topic);
options.Topics.Add(deadLetter);
options.Subscriptions.Add(new Subscription
{
SubscriptionName = subscription,
TopicAsTopicName = topic,
AckDeadlineSeconds = 60,
});
});
pubsub.Send<OrderPlaced>(topic.ToString());
pubsub.Consume(subscription.ToString(), consumer =>
{
consumer.Failures(new()
{
DeadLetterEndpoint = deadLetter.ToString(),
RetryDelays = new[] { TimeSpan.FromSeconds(1) },
});
consumer.Handler<OrderPlacedHandler>();
});
});
});

Use fully qualified native endpoint names. Each Subscriptions entry needs a Name in the format projects/{project}/subscriptions/{subscription}. Startup errors for invalid names identify the transport and entry. Topics must be declared in Topics; consumers refer to entries in Subscriptions. These are ordinary named Options registrations. Use the generated handler and JSON registration described in messages.

PublisherClient.Settings and SubscriberClient.Settings pass through as native settings. Relayer snapshots settings when composing the transport. It creates native PublisherClientImpl instances per topic and SubscriberClientImpl instances per running consumer, using your prepared API clients. Stopping a named transport requests native shutdown on all its subscriptions before waiting for handlers and native acknowledgements to drain. A clean stop allows the transport to restart with fresh streaming subscribers over the same API clients. A fatal subscriber task fails the hosted background service. Recreate the application host after a fatal subscriber failure or a cancelled native shutdown.

If the host stop deadline expires during a drain, Relayer stops waiting and the native subscriber cancels handler processing and acknowledgement. Handler cleanup can continue after the stop call returns. Host disposal waits for that subscriber shutdown to finish, so keep caller-owned API clients and channels alive through host disposal.

Relayer builds every receive pipeline before registering the named transport's workers. If pipeline configuration throws, retrying startup on the same host rebuilds the pipelines from the declarations. If native startup fails after composition, the retry reuses the fully configured workers.

If a subscriber cannot start, Relayer shuts down the subscriptions already started by that attempt before returning the startup error. If shutdown also fails, the exception includes both errors.

For concurrency greater than one, declare the same limit in both places:

consumer.Concurrency(8);
consumer.Options.Settings = new SubscriberClient.Settings
{
FlowControlSettings = new Google.Api.Gax.FlowControlSettings(8, 16_000_000),
};

The default maximum outstanding element count is one. Native flow control supplies backpressure and the concurrency bound; Relayer does not add a scheduler. A mismatch fails startup. Streaming callbacks deliver individual messages; batch handlers fail startup.

Every transport with consumers must set PublisherSettings.EnableMessageOrdering = true. Poison-message copies preserve ordering keys received from external publishers, including on unordered subscriptions. Startup rejects disabled publisher ordering before processing can begin. Send-only transports can leave it disabled.

Request and response​

Declare the request topic, the reply topic, and a dedicated reply subscription attached to the reply topic in the transport options above. Give each requesting process its own reply endpoint. Use fully qualified native names throughout.

On the requester, pass the subscription as the reply consumer source and set ReplyDestination to the topic that feeds it. Configure the reply consumer's dead-letter topic in Replies.

pubsub.Request<GetPrice, Price>(requestTopic.ToString(), replySubscription.ToString(), request =>
{
request.ReplyDestination = replyTopic.ToString();
request.Replies(consumer => consumer.Failures(new()
{
DeadLetterEndpoint = deadLetter.ToString(),
}));
});

On the responder, declare pubsub.Send<Price>(replyTopic.ToString()) as the fixed CloudEvents route and call context.ReplyAsync(response) in the request handler. See the request/response guide for correlation and timeout behavior.

Ordering and native access​

For keyed ordering, set PublisherSettings.EnableMessageOrdering = true and set Subscription.EnableMessageOrdering = true on every declared subscription for the topic. Startup rejects a route with .OrderingKey(...) if publisher ordering is disabled or any declared subscription for that topic has ordering disabled. This check uses the subscription declarations for the named transport. For subscriptions managed outside those declarations, enable ordering on the broker to get ordered delivery.

Google's client retains responsibility for ordering keys in error, including PublisherClient.ResumePublish. Resolve IGooglePubSubClients with the transport name as its DI key, or use context.GooglePubSub().Clients, and call PublisherFor(topic) for those native operations. Do not dispose the returned publisher. Relayer does not claim exactly-once application effects, even when a native subscription enables exactly-once delivery.

Inside a handler, context.GooglePubSub().Message exposes the original PubsubMessage and .Subscriber exposes the native streaming client. Both are borrowed until processing ends. Configure outgoing messages with new SendOptions().GooglePubSub(message => ...); portable ordering keys and headers normally need no callback.

CloudEvents attributes use the Pub/Sub binary binding's ce- prefix, for example ce-id and ce-type. content-type, traceparent and tracestate remain unprefixed. Data is the serialized body. Incoming data and attribute values are read lazily without copying. Failure copies preserve original creation context and envelope attributes.

Settlement and limits​

CapabilityBehavior
DeliveryAt least once; Ack follows durable handler work and failure-copy completion
Native recoveryGoogle's streaming client reconnects and extends acknowledgement leases
BatchingNative publisher batching; up to 1,000 messages per native request, with native byte limits
Message sizeNative 10,000,000-byte limit; attributes and request overhead also consume native limits
Scheduled sendsNot available natively; use the durable outbox
Durable redelivery policyUnavailable: Nack cannot persist changed failure attributes; RedeliveryDelays fails startup
Dead-letteringExplicit durable copy to a declared topic, followed by Ack; configure Failure.DeadLetterEndpoint
Native DeadLetterPolicyCan be passed through, but cannot supply Relayer's on-demand dead-letter operation with error metadata
Transactions, tombstones, pause/resume, generic replayNot advertised

In-process RetryDelays reuse the core failure pipeline. Exhausted retries and poison messages are published to the explicit dead-letter topic with error history before acknowledging the original. A failed copy leaves the original unacknowledged. The settlement span records the callback decision as ack or nack when Relayer sets the reply. The SDK sends the broker acknowledgement separately. Google's callback Nack remains available for native processing failures; it redelivers unchanged attributes and cannot implement Relayer's durable retry history. The binding uses the native GetDeliveryAttempt() extension: a broker delivery count is available when native dead-letter queues supply it, otherwise it is null.

Use a separate dead-letter topic for an unfiltered subscription. Relayer rejects the source topic as its dead-letter destination at startup because Pub/Sub would deliver every failure copy back to the same consumer. If a filtered subscription shares its source and dead-letter topic, configure its native filter to exclude every dead-letter copy. Relayer checks only whether a filter is declared.

Pub/Sub attribute values are limited to 1,024 UTF-8 bytes. Larger Relayer error histories are framed losslessly into relayer.failure.history.part.0, .part.1, and subsequent attributes, with their count in relayer.failure.history.parts. The binding reconstructs the logical relayer.failure.history header only when requested. Replacing history removes old parts; the body, CloudEvents and creation context stay unchanged. Reserve attribute capacity for failure copies: the service permits 100 attributes in total, 256-byte keys and 1,024-byte values. If the full history and original attributes cannot fit, publishing fails explicitly and the original stays unacknowledged; history is never silently truncated. Native dead-letter policy can provide an additional broker-managed safety net for messages that cannot be copied within service limits. These limits are enforced on failure copies even where the emulator accepts oversized attributes.

PublisherClient.PublishAsync has no cancellation parameter. Cancellation before admission prevents publishing. Once admitted, Relayer waits for native completion before returning cancellation, so a serializer buffer cannot be reused while the publisher still borrows it. Cancellation can therefore outlive the portable send timeout; delivery may have occurred. Configure native API deadlines and retries on your prepared client. Batch failure may leave some messages delivered; every admitted publish is drained before borrowed storage is released.

Relayer emits gcp_pubsub process/send spans and an ack settlement span when committing the callback reply to the native client. This span does not promise that an acknowledgement RPC has reached the broker. Native acknowledgement batching and exactly-once acknowledgement responses retain their native semantics.

Topology​

None makes no administration calls. Validate only reads topic/subscription state and reports missing entities or differences. Provision creates missing topics/subscriptions, tolerates concurrent creation and never rewrites or deletes existing entities.

Topic declarations check existence. Subscription declarations support pull delivery, topic, acknowledgement deadline, ordering, exactly-once delivery, filter, native dead-letter/retry policies, retention, expiration and labels. Native subscription messages are passed unchanged to creation. A pull declaration can omit PushConfig or explicitly set an empty PushConfig. Unsupported fields such as push and export delivery fail startup. Unspecified acknowledgement deadline, retention and expiration accept service defaults. Declared values are checked. The topology report identifies missing declared labels, including labels whose expected value is empty. Provision preserves extra labels on existing subscriptions.

When a retry or dead-letter policy is declared, Validate and Provision compare its effective settings. Pub/Sub defaults an omitted retry minimum to 10 seconds, an omitted retry maximum to 600 seconds, and zero or omitted dead-letter attempts to 5. Explicit backoffs, including zero seconds, and explicit nonzero delivery attempts still affect the comparison. Omitting either policy checks that the corresponding policy is absent.

A declared expiration policy of 31 days also matches a broker response that omits its expiration policy, which represents the Pub/Sub default. A present policy without a TTL means the subscription never expires.

Native AOT and emulator validation​

The adapter and generated JSON/handler path are Native AOT tested. Google's convenience builders still retain reflection and authentication dependencies that fail strict AOT publication (upstream #13328). Prepare native API clients through Google's public constructors over an application-owned managed gRPC channel instead. For the emulator:

using Grpc.Net.Client;

using var channel = GrpcChannel.ForAddress("http://localhost:8085");
var publisher = new PublisherServiceApiClientImpl(
new Publisher.PublisherClient(channel), null, null);
var subscriber = new SubscriberServiceApiClientImpl(
new Subscriber.SubscriberClient(channel), null, null);

Keep the channel alive until Relayer stops and disposes its workers. Production channels require TLS and application-prepared credentials; validate the chosen authentication path separately under trimming/AOT. Relayer does not supply another authentication stack or suppress native warnings.

Google's subscriber intentionally treats some initial StreamingPull write failures as fatal, including a TCP reset while opening a replacement stream (upstream explanation). A previously established connection does not guarantee every later stream can reconnect. A faulted subscriber requires application host recreation; Relayer does not add a reconnect loop or hide the native failure. Keep the same durable topic and subscription when recreating the host.

The tests share an official Pub/Sub emulator per test session and isolate each scenario's topics and subscriptions. The conformance suite runs send/receive/settle, ordering, trace propagation, stored creation-context copies and recovery after Toxiproxy drops live TCP connections while the emulator preserves endpoint state. If a native initial-write TCP failure permanently faults the subscriber, the fixture explicitly disposes and recreates its DI application against the same topic and subscription; unrelated shutdown failures still fail the suite. A deterministic initial-write fault test exercises this application recreation path. Native delay, on-demand dead-letter and metadata-preserving durable retry cases return explicit capability skips. Separate emulator tests cover native Nack, unchanged creation attributes, handler drain and durable poison copies. IAM, authentication, regional ordering, exactly-once acknowledgement guarantees and production dead-letter-policy forwarding are not established by emulator tests.

tests/Relayer.GooglePubSub.AotSmoke publishes a warning-clean executable and exercises topology plus a generated JSON handler round trip. Set PUBSUB_EMULATOR_HOST to a ready emulator. GooglePubSubSendBenchmarks compares acknowledged native and Relayer JSON sends against that emulator. GooglePubSubBrokerReceiveBenchmarks compares native streaming pull and drained acknowledgements over fresh 512-message workloads, using the same JSON contract, native flow control and handler on both paths. GooglePubSubReceiveBenchmarks compares already-delivered JSON processing with the same scoped handler; it diagnoses pipeline cost independently of network acquisition and is not a broker-throughput result. GooglePubSubPoolBenchmarks measures reusable state bursts within and beyond the fixed retention capacity. All use MemoryDiagnoser; local results are diagnostic, not performance compliance claims.

Relayer retains at most 256 reusable send states per topic publisher and 256 callback replies per consumer. Larger concurrent bursts remain supported: a pool miss allocates and returned overflow is collected rather than retained for the transport lifetime. Native string-valued attributes and ordering keys require string conversions on send; the raw send benchmark performs the same conversions.

Poison copies omit service-owned attributes whose keys start with goog, which Pub/Sub rejects on publish. Application attributes, CloudEvents, body and ordering key remain preserved. The original delivery is unchanged.

Mixed-destination batches submit messages to each topic's native publisher in input order, then wait for confirmation of every admitted send. Each publisher applies its own native batching thresholds. If you omit the delay threshold, a partial native batch can remain pending until more messages reach its count or byte threshold or the publisher shuts down. Cancellation after admission still waits for the native publisher to finish. A failed batch can leave messages published to multiple destinations, so retrying the batch can produce duplicates under at-least-once delivery.