advanced

Pub/Sub

Build asynchronous event pipelines with topics, subscriptions, acknowledgment deadlines, retry policy, ordering keys, and dead-letter topics.

Pub/Sub decouples producers and consumers with topics, subscriptions, at-least-once delivery, and acknowledgment deadlines. In event-driven Node.js systems it buffers spikes, fans out notifications, and connects Cloud Functions or Cloud Run workers without tight coupling.

					import { PubSub } from '@google-cloud/pubsub';

const pubsub = new PubSub();
const topic = pubsub.topic('orders-created');

await topic.publishMessage({
  json: { orderId: 'ord_123', total: 42.5 },
  attributes: { schemaVersion: '1' },
});
				

| Setting | Purpose | |---------|---------| | Ack deadline | Time to process before redelivery | | Dead-letter topic | Isolate poison messages after max attempts | | Ordering key | Per-key sequence when strictly needed | | Push vs pull | HTTP push to Cloud Run or pull in long-running worker |

Consumers must be idempotent because duplicates happen. Extend ack deadline for long tasks or use lease patterns.

On interviews: at-least-once semantics; dead-letter handling; ordering keys cost; push subscription auth; backpressure when consumers lag.

Common pitfalls: assuming exactly-once without deduplication keys; acking before work completes; unbounded subscriber count on one subscription; no monitoring on oldest unacked age.

The trade-off is elastic async decoupling versus operational complexity of retries, ordering, and observability.

Checklist:

  • Make consumers idempotent with dedupe store or keys.
  • Configure dead-letter topics and alert on depth.
  • Tune ack deadline to realistic handler duration.
  • Monitor subscription backlog and processing latency.