google-pubsub

v2026.09.24

Google Cloud Pub/Sub messaging service. Covers topics, subscriptions, push/pull delivery, and dead-letter handling. Use for GCP-native event-driven architectures and real-time analytics. USE WHEN: user mentions "google pub/sub", "pubsub", "gcp messaging", "push subscription", "pull subscription", asks about "cloud pub/sub", "ordering keys", "bigquery subscription" DO NOT USE FOR: AWS-native - use `sqs`; Azure-native - use `azure-service-bus`; event streaming - use `kafka` or Dataflow; on-premise - use `rabbitmq` or `activemq`; multi-cloud - use `kafka` or `pulsar`

GitHub
Install command
npx skhub add claude-dev-suite/google-pubsub
Markdown
SKILL.md

Google Cloud Pub/Sub Core Knowledge

Full Reference: See advanced.md for Java/Python/Go producer patterns, Spring Cloud GCP consumer, push subscription handlers, and Terraform for DLT, IAM, VPC Service Controls, and monitoring alerts.

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: google-pubsub for comprehensive documentation.

Quick Start (Emulator)

# docker-compose.yml
services:
  pubsub:
    image: gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators
    command: gcloud beta emulators pubsub start --host-port=0.0.0.0:8085
    ports:
      - "8085:8085"
docker-compose up -d

# Set emulator env
export PUBSUB_EMULATOR_HOST=localhost:8085

# Create topic and subscription
gcloud pubsub topics create orders
gcloud pubsub subscriptions create order-processor --topic=orders

# Test
gcloud pubsub topics publish orders --message='{"id":"123"}'
gcloud pubsub subscriptions pull order-processor --auto-ack

Core Concepts

ConceptDescription
TopicNamed resource for publishing messages
SubscriptionNamed resource for receiving messages
PublisherSends messages to topic
SubscriberReceives messages from subscription
Ack DeadlineTime to acknowledge before redelivery
Message RetentionHow long unacked messages are kept

Delivery Types

TypeDescriptionUse Case
PullSubscriber requests messagesBatch processing, variable load
PushPub/Sub sends to endpointServerless, webhooks
BigQueryDirect export to BigQueryAnalytics pipelines
Cloud StorageDirect export to GCSData archival

Architecture

Publisher ──▶ Topic ──▶ Subscription 1 (Pull) ──▶ Subscriber
                   ──▶ Subscription 2 (Push) ──▶ Cloud Run
                   ──▶ Subscription 3 ──▶ BigQuery

Node.js Producer (@google-cloud/pubsub)

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

const pubsub = new PubSub({
  projectId: 'my-project',
});

const topic = pubsub.topic('orders');

// Publish single message
const messageId = await topic.publishMessage({
  data: Buffer.from(JSON.stringify(order)),
  attributes: {
    'correlation-id': correlationId,
    'order-type': order.type,
  },
  orderingKey: order.customerId, // For ordered delivery
});

// Batch publishing (automatic batching)
const publishOptions = {
  batching: {
    maxMessages: 100,
    maxMilliseconds: 10,
  },
};
const batchTopic = pubsub.topic('orders', publishOptions);

Node.js Consumer (Pull Subscription)

const subscription = pubsub.subscription('order-processor', {
  flowControl: {
    maxMessages: 100,
    maxExtensionMinutes: 10,
  },
  ackDeadline: 30,
});

const messageHandler = async (message) => {
  try {
    const order = JSON.parse(message.data.toString());
    const correlationId = message.attributes['correlation-id'];

    await processOrder(order);
    message.ack();
  } catch (error) {
    console.error('Processing failed:', error);
    message.nack(); // Will be redelivered
  }
};

subscription.on('message', messageHandler);
subscription.on('error', (error) => console.error('Subscription error:', error));

// Graceful shutdown
process.on('SIGTERM', async () => {
  await subscription.close();
});

Dead Letter Topics

# Create DLT
gcloud pubsub topics create orders-dlq
gcloud pubsub subscriptions create orders-dlq-sub --topic=orders-dlq

# Create subscription with DLT
gcloud pubsub subscriptions create order-processor \
  --topic=orders \
  --dead-letter-topic=orders-dlq \
  --max-delivery-attempts=5

When NOT to Use This Skill

Use alternative messaging solutions when:

  • AWS-native architecture - SQS has better AWS integration
  • Azure-native architecture - Use Azure Service Bus
  • Event streaming with replay - Use Dataflow or Kafka
  • On-premise deployment - Use RabbitMQ or ActiveMQ
  • Multi-cloud portability - Use Kafka or RabbitMQ
  • Complex routing patterns - RabbitMQ provides more flexibility
  • JMS compliance required - Use ActiveMQ

Anti-Patterns

Anti-PatternWhy It's BadSolution
No dead letter topicFailed messages lostConfigure DLT for all subscriptions
Short ack deadlineDuplicate processingSet deadline > max processing time
No retry policyImmediate redelivery on failureConfigure exponential backoff
Synchronous publishPoor throughputUse batching and async publish
Pull without flow controlConsumer overwhelmedSet max_messages limit
No message ordering when neededOut of order processingUse ordering keys
Large message payloadsHigher costs, poor performanceUse Cloud Storage with reference
No IAM least privilegeSecurity riskUse service accounts with minimal roles

Quick Troubleshooting

IssueLikely CauseFix
Messages not receivedNo subscription or wrong topicCreate subscription, verify topic
Duplicate messagesAck deadline expiredIncrease ack deadline or process faster
Messages in DLTMax delivery attempts exceededCheck processing logic, review DLT
Permission deniedMissing IAM rolesGrant Publisher/Subscriber roles
Ordering not workingNo ordering key or wrong subscriptionSet ordering key, enable message ordering
High latencyBatching delay or networkReduce batch delay, check network
Push subscription failingEndpoint down or auth failureCheck endpoint health, verify auth
Backlog growingSlow consumersAdd consumers or optimize processing

Production Readiness

Monitoring Metrics

MetricAlert Threshold
num_undelivered_messages> 10000
oldest_unacked_message_age> 3600s
num_outstanding_messages> 10000
dead_letter_message_count> 0
publish_latenciesp99 > 1s

Checklist

  • IAM roles with least privilege
  • Service account per component
  • Dead letter topic configured
  • Retry policy configured
  • Ack deadline appropriate
  • Message retention set
  • Monitoring alerts configured
  • Schema validation (if needed)
  • Message ordering (if needed)
  • VPC Service Controls (if needed)

Reference Documentation

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: google-pubsub for comprehensive documentation.

Available topics: basics, producers, consumers, production

Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

MIT

Source path

skills/messaging/google-pubsub

Default branch

main

Latest commit

9496306

Tree SHA

fe4e2f1