{"id":736,"library":"google-cloud-pubsub","title":"Google Cloud Pub/Sub Client Library","description":"The `google-cloud-pubsub` Python client library provides a fully-managed, real-time messaging service for Google Cloud Pub/Sub. It facilitates asynchronous communication, decoupling services that produce messages from those that consume them, offering 'at least once' delivery, low latency, and on-demand scalability. The library is actively maintained with frequent, often weekly, releases for bug fixes and minor features within the broader `google-cloud-python` monorepo.","status":"active","version":"2.36.0","language":"python","source_language":"en","source_url":"https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-pubsub","tags":["google-cloud","pubsub","messaging","asynchronous","event-driven"],"install":[{"cmd":"pip install google-cloud-pubsub","lang":"bash","label":"Install latest stable version"}],"dependencies":[],"imports":[{"wrong":"from google.cloud import pubsub_v1","symbol":"PublisherClient","correct":"from google.cloud.pubsub_v1 import PublisherClient"},{"wrong":"from google.cloud import pubsub_v1","symbol":"SubscriberClient","correct":"from google.cloud.pubsub_v1 import SubscriberClient"}],"quickstart":{"code":"import os\nimport time\nfrom concurrent.futures import TimeoutError\nfrom google.cloud import pubsub_v1\n\nproject_id = os.environ.get('GOOGLE_CLOUD_PROJECT') or os.environ.get('GCP_PROJECT') or 'your-gcp-project-id'\ntopic_id = 'my-topic-id'\nsubscription_id = 'my-subscription-id'\n\nif not project_id or project_id == 'your-gcp-project-id':\n    raise ValueError(\"Please set the GOOGLE_CLOUD_PROJECT environment variable or replace 'your-gcp-project-id'.\")\n\npublisher = pubsub_v1.PublisherClient()\nsubscriber = pubsub_v1.SubscriberClient()\n\ntopic_path = publisher.topic_path(project_id, topic_id)\nsubscription_path = subscriber.subscription_path(project_id, subscription_id)\n\n# Create topic if it doesn't exist\ntry:\n    publisher.get_topic(request={\"topic\": topic_path})\n    print(f\"Topic {topic_path} already exists.\")\nexcept Exception:\n    print(f\"Creating topic {topic_path}...\")\n    publisher.create_topic(request={\"name\": topic_path})\n    print(f\"Topic {topic_path} created.\")\n\n# Create subscription if it doesn't exist\ntry:\n    subscriber.get_subscription(request={\"subscription\": subscription_path})\n    print(f\"Subscription {subscription_path} already exists.\")\nexcept Exception:\n    print(f\"Creating subscription {subscription_path}...\")\n    subscriber.create_subscription(request={\"name\": subscription_path, \"topic\": topic_path})\n    print(f\"Subscription {subscription_path} created.\")\n\n\n# --- Publisher --- \nmessage_data = \"Hello, Pub/Sub!\"\nprint(f\"Publishing message: '{message_data}' to {topic_path}\")\nfuture = publisher.publish(topic_path, message_data.encode('utf-8'))\nmessage_id = future.result()\nprint(f\"Published message with ID: {message_id}\")\n\n# --- Subscriber --- \ndef callback(message: pubsub_v1.subscriber.message.Message):\n    print(f\"Received message: {message.data.decode('utf-8')}\")\n    print(f\"Acknowledging message: {message.message_id}\")\n    message.ack()\n\nprint(f\"Listening for messages on {subscription_path}...\")\nstreaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)\n\n# Wrap subscriber in a 'with' block to automatically call close() when done.\nwith subscriber:\n    try:\n        # `subscribe` is non-blocking, so we must keep the main thread from exiting to allow it to run.\n        streaming_pull_future.result(timeout=30) # Wait 30 seconds for messages\n    except TimeoutError:\n        streaming_pull_future.cancel()  # Trigger the shutdown.\n        streaming_pull_future.result()  # Block until the shutdown is complete.\n    except KeyboardInterrupt:\n        streaming_pull_future.cancel()  # Trigger the shutdown.\n        streaming_pull_future.result()  # Block until the shutdown is complete.\n\nprint(\"Finished listening for messages.\")\n\n# Clean up resources (optional)\n# publisher.delete_topic(request={\"topic\": topic_path})\n# subscriber.delete_subscription(request={\"subscription\": subscription_path})\n# print(f\"Topic {topic_id} and subscription {subscription_id} deleted.\")\n","lang":"python","description":"This quickstart demonstrates how to publish a message to a Google Cloud Pub/Sub topic and then subscribe to and consume that message from a subscription. It handles topic and subscription creation if they don't exist and uses environment variables for project configuration."},"warnings":[{"fix":"Upgrade your Python environment to 3.9+ or pin the library version: `pip install google-cloud-pubsub==2.34.0`.","message":"Versions of `google-cloud-pubsub` from `2.35.0` and higher require Python 3.9 or newer. If you are using Python 3.7 or 3.8, you must pin the library version to `google-cloud-pubsub==2.34.0` or earlier.","severity":"breaking","affected_versions":">=2.35.0"},{"fix":"For most applications, create a single `PublisherClient` and a single `SubscriberClient` instance per process and reuse them across operations to optimize resource utilization.","message":"Instantiating multiple `PublisherClient` or `SubscriberClient` instances unnecessarily can lead to resource inefficiencies. These clients handle connection pooling and caching internally.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Carefully tune your subscription's acknowledgment deadline to allow sufficient time for message processing. Implement appropriate flow control settings (`max_messages`, `max_bytes`) to prevent your application from being overwhelmed by messages. Always call `message.ack()` or `message.nack()` after processing.","message":"Incorrectly configuring subscriber acknowledgment deadlines or flow control (prefetch settings) can cause 'stuck subscribers', messages being redelivered repeatedly (poison pill effect), or excessive resource consumption.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Design your subscriber logic to be *idempotent*. Your message processing should produce the same result whether it's executed once or multiple times for the same message. Utilize unique business keys (like a transaction ID) and check against a fast-access store to prevent duplicate processing.","message":"Pub/Sub guarantees at-least-once delivery, meaning a message might be delivered more than once in certain scenarios (e.g., subscriber restarts, ack deadline issues).","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always store or log the `message_id` returned by the publish operation. This ID is the primary way to correlate a published message with its ingestion in Google Cloud Logs Explorer and track its lifecycle.","message":"Failing to capture and log the `message_id` returned by `publisher.publish().result()` can severely hinder debugging and traceability in production.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure the `GOOGLE_CLOUD_PROJECT` environment variable is set to your actual Google Cloud Project ID (e.g., `my-project-123`) before initializing clients, or explicitly pass the project ID to the client constructor, for example: `PublisherClient(project='my-project-123')`.","message":"The Google Cloud Project ID must be provided to the Pub/Sub client libraries to identify the project where resources reside. This can be done by setting the `GOOGLE_CLOUD_PROJECT` environment variable or by explicitly passing the `project` argument to client constructors. Failing to provide a valid project ID (or leaving it as a placeholder like 'your-gcp-project-id') will prevent client initialization.","severity":"breaking","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'activ':57 'asynchron':30,83 'broader':72 'bug':65 'client':4,12 'cloud':2,9,26,75,80 'communic':31 'consum':40 'decoupl':32 'deliveri':46 'demand':52 'driven':86 'event':85 'event-driven':84 'facilit':29 'featur':69 'fix':66 'frequent':60 'fulli':17 'fully-manag':16 'googl':1,8,25,74,79 'google-cloud':78 'google-cloud-pubsub':7 'google-cloud-python':73 'latenc':48 'least':44 'librari':5,13,55 'low':47 'maintain':58 'manag':18 'messag':22,36,82 'minor':68 'monorepo':77 'offer':42 'often':61 'on-demand':50 'produc':35 'provid':14 'pub/sub':3,27 'pubsub':10,81 'python':11,76 'real':20 'real-tim':19 'releas':63 'scalabl':53 'servic':23,33 'time':21 'week':62 'within':70","created_at":"2026-03-28T17:30:17.214541+00:00","updated_at":"2026-04-16T15:23:22.900669+00:00","problems":null,"ecosystem":"pypi","meta_description":null,"install_score":95,"quickstart_score":0,"quickstart_tag":"stale","pypi_latest":"2.39.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/googleapis/google-cloud-python","docs":null,"changelog":null,"pypi":"https://pypi.org/project/google-cloud-pubsub/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["gcp","http-networking","communication","data"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-30","last_verified":"2026-06-30","next_check":"2026-07-30","install_tag":"verified"}}