Quickstart: Using Client Libraries

The Google Cloud Pub/Sub service allows applications to exchange messages reliably, quickly, and asynchronously. To accomplish this, a producer of data publishes a messages to a Cloud Pub/Sub topic. A subscriber client then creates a subscription to that topic and consumes messages from the subscription. Cloud Pub/Sub persists messages that could not be delivered reliably for up to seven days. This page shows you how to get started publishing messages with Cloud Pub/Sub using client libraries.

Before you begin

  1. Sign in to your Google account.

    If you don't already have one, sign up for a new account.

  2. Set up a GCP Console project.

    Set up a project

    Click to:

    • Create or select a project.
    • Enable the Cloud Pub/Sub API for that project.
    • Create a service account.
    • Download a private key as JSON.

    You can view and manage these resources at any time in the GCP Console.

  3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key.

  4. Install and initialize the Cloud SDK.


Install the client libraries in your choice of programming language:


Install-Package Google.Cloud.PubSub.V1 -Pre


go get -u cloud.google.com/go/pubsub


If you are using Maven, add this to your pom.xml file:
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud:google-cloud-pubsub:0.32.0-beta'
If you are using SBT, add this to your dependences:
libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "0.32.0-beta"


npm install --save @google-cloud/pubsub


composer require google/apiclient


For more on setting up your Python development environment, refer to Python Development Environment Setup Guide.

pip install --upgrade google-cloud-pubsub


gem install google-cloud-pubsub

Create a topic and a subscription

You must first create a topic before you can subscribe or publish to it. You can create a topic using the gcloud command-line tool (included in the Cloud SDK you installed in Before you begin) as follows:

gcloud pubsub topics create my-topic

Now use gcloud to create a subscription to the topic. Only messages published to the topic after the subscription is created are available to subscriber applications.

gcloud pubsub subscriptions create my-sub --topic my-topic

Publish messages

You are now ready to publish messages to the topic:


PublisherServiceApiClient publisherClient = PublisherServiceApiClient.Create();
PublisherClient publisher = PublisherClient.Create(
    new TopicName(projectId, topicId), new[] { publisherClient });
var publishTasks = new List<Task<string>>();
// SimplePublisher collects messages into appropriately sized
// batches.
foreach (string text in messageTexts)
foreach (var task in publishTasks)
    Console.WriteLine("Published message {0}", task.Result);


For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t := client.Topic(topic)
result := t.Publish(ctx, &pubsub.Message{
	Data: []byte(msg),
// Block until the result is returned and a server-generated
// ID is returned for the published message.
id, err := result.Get(ctx)
if err != nil {
	return err
fmt.Printf("Published a message; msg ID: %v\n", id)


import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;

public class PublisherExample {

  // use the default project id
  private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();

  /** Publish messages to a topic.
   * @param args topic name, number of messages
  public static void main(String... args) throws Exception {
    // topic id, eg. "my-topic"
    String topicId = args[0];
    int messageCount = Integer.parseInt(args[1]);
    TopicName topicName = TopicName.of(PROJECT_ID, topicId);
    Publisher publisher = null;
    try {
      // Create a publisher instance with default settings bound to the topic
      publisher = Publisher.newBuilder(topicName).build();

      for (int i = 0; i < messageCount; i++) {
        String message = "message-" + i;

        // convert message to bytes
        ByteString data = ByteString.copyFromUtf8(message);
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder()

        //schedule a message to be published, messages are automatically batched
        ApiFuture<String> future = publisher.publish(pubsubMessage);

        // add an asynchronous callback to handle success / failure
        ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

          public void onFailure(Throwable throwable) {
            if (throwable instanceof ApiException) {
              ApiException apiException = ((ApiException) throwable);
              // details on the API exception
            System.out.println("Error publishing message : " + message);

          public void onSuccess(String messageId) {
            // Once published, returns server-assigned message ids (unique within the topic)
    } finally {
      if (publisher != null) {
        // When finished with the publisher, shutdown to free up resources.


// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

 * TODO(developer): Uncomment the following lines to run the sample.
// const topicName = 'your-topic';
// const data = JSON.stringify({ foo: 'bar' });

// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);

  .then(results => {
    const messageId = results[0];
    console.log(`Message ${messageId} published.`);
  .catch(err => {
    console.error('ERROR:', err);


use Google\Cloud\PubSub\PubSubClient;

 * Publishes a message for a Pub/Sub topic.
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $message  The message to publish.
function publish_message($projectId, $topicName, $message)
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    $topic = $pubsub->topic($topicName);
    $topic->publish(['data' => $message]);
    print('Message published' . PHP_EOL);


def publish_messages(project, topic_name):
    """Publishes multiple messages to a Pub/Sub topic."""
    publisher = pubsub_v1.PublisherClient()
    topic_path = publisher.topic_path(project, topic_name)

    for n in range(1, 10):
        data = u'Message number {}'.format(n)
        # Data must be a bytestring
        data = data.encode('utf-8')
        publisher.publish(topic_path, data=data)

    print('Published messages.')


pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

topic.publish "A Message"

Receive messages

Now set up a subscriber to pull the messages you just published. Every subscriber must acknowledge each message within a configurable time window. Unacknowledged messages are redelivered. Note that Cloud Pub/Sub occasionally delivers a message more than once to ensure that all messages make it to a subscriber at least once. Here is an example of how you might receive and acknowledge messages:


SubscriptionName subscriptionName = new SubscriptionName(projectId,
SubscriberServiceApiClient subscriberClient = SubscriberServiceApiClient.Create();
SubscriberClient subscriber = SubscriberClient.Create(
    subscriptionName, new[] { subscriberClient });
// SimpleSubscriber runs your message handle function on multiple
// threads to maximize throughput.
    async (PubsubMessage message, CancellationToken cancel) =>
        string text =
        await Console.Out.WriteLineAsync(
            $"Message {message.MessageId}: {text}");
        return acknowledge ? SubscriberClient.Reply.Ack
            : SubscriberClient.Reply.Nack;
// Run for 3 seconds.


// Consume 10 messages.
var mu sync.Mutex
received := 0
sub := client.Subscription(name)
cctx, cancel := context.WithCancel(ctx)
err := sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
	defer mu.Unlock()
	if received >= 10 {
	fmt.Printf("Got message: %q\n", string(msg.Data))
if err != nil {
	return err


import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.AckReplyConsumer;
import com.google.cloud.pubsub.v1.MessageReceiver;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.SubscriptionName;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class SubscriberExample {

  // use the default project id
  private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();

  private static final BlockingQueue<PubsubMessage> messages = new LinkedBlockingDeque<>();

  static class MessageReceiverExample implements MessageReceiver {

    public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {

  /** Receive messages over a subscription. */
  public static void main(String... args) throws Exception {
    // set subscriber id, eg. my-sub
    String subscriptionId = args[0];
    SubscriptionName subscriptionName = SubscriptionName.of(PROJECT_ID, subscriptionId);
    Subscriber subscriber = null;
    try {
      // create a subscriber bound to the asynchronous message receiver
      subscriber =
          Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
      // Continue to listen to messages
      while (true) {
        PubsubMessage message = messages.take();
        System.out.println("Message Id: " + message.getMessageId());
        System.out.println("Data: " + message.getData().toStringUtf8());
    } finally {
      if (subscriber != null) {


// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

 * TODO(developer): Uncomment the following lines to run the sample.
// const subscriptionName = 'your-subscription';
// const timeout = 60;

// References an existing subscription
const subscription = pubsub.subscription(subscriptionName);

// Create an event handler to handle messages
let messageCount = 0;
const messageHandler = message => {
  console.log(`Received message ${message.id}:`);
  console.log(`\tData: ${message.data}`);
  console.log(`\tAttributes: ${message.attributes}`);
  messageCount += 1;

  // "Ack" (acknowledge receipt of) the message

// Listen for new messages until timeout is hit
subscription.on(`message`, messageHandler);
setTimeout(() => {
  subscription.removeListener('message', messageHandler);
  console.log(`${messageCount} message(s) received.`);
}, timeout * 1000);


use Google\Cloud\PubSub\PubSubClient;

 * Pulls all Pub/Sub messages for a subscription.
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
function pull_messages($projectId, $subscriptionName)
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    $subscription = $pubsub->subscription($subscriptionName);
    foreach ($subscription->pull() as $message) {
        printf('Message: %s' . PHP_EOL, $message->data());
        // Acknowledge the Pub/Sub message has been received, so it will not be pulled multiple times.


def receive_messages(project, subscription_name):
    """Receives messages from a pull subscription."""
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path(
        project, subscription_name)

    def callback(message):
        print('Received message: {}'.format(message))

    subscriber.subscribe(subscription_path, callback=callback)

    # The subscriber is non-blocking, so we must keep the main thread from
    # exiting to allow it to process messages in the background.
    print('Listening for messages on {}'.format(subscription_path))
    while True:


pubsub       = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
subscription = pubsub.subscription "my-subscription"

puts "Messages pulled:"
subscription.pull.each do |message|
  puts message.data

Clean up (Optional)

To avoid incurring charges to your Google Cloud Platform account for the resources used in this guide, you can delete the topic and subscription.
  gcloud pubsub subscriptions delete mySubscription
  gcloud pubsub topics delete myTopic

What's next

For complete examples that you can build and run, see the Cloud Pub/Sub tutorials.

To get details about the client library for your language of choice, see Client Libraries.

For an overview of Cloud Pub/Sub, see What is Google Cloud Pub/Sub?.

See the Publisher and Subscriber guides to learn more about the concepts discussed in this page.

Send feedback about...

Cloud Pub/Sub Documentation