Google Cloud Pub/Sub is a fully managed, real-time messaging service that enables asynchronous communication between independent applications. It provides a scalable, durable message ingestion and delivery system that decouples services, allowing them to communicate reliably at scale. Pub/Sub supports multiple messaging patterns including publish/subscribe, push and pull delivery, and dead-letter queues, making it ideal for event-driven architectures, streaming analytics, and data integration pipelines.
The ballerinax/googleapis.pubsub package provides APIs to interact with Google Cloud Pub/Sub. It allows developers to programmatically publish messages to topics, create and manage subscriptions, configure message delivery policies, and implement robust, cloud-native event-driven solutions that leverage Google Cloud's globally distributed infrastructure and automatic scaling capabilities within Ballerina applications.
To use the Ballerina Google Cloud Pub/Sub connector, you need to have a Google Cloud account and a project with the Pub/Sub API enabled.
- Go to the Google Cloud Console.
- Click on the project dropdown and select New Project.
- Enter a project name and click Create.
- Note your project ID, as you'll need it for configuration.
- In the Google Cloud Console, navigate to APIs & Services > Library.
- Search for "Cloud Pub/Sub API".
- Click on it and then click Enable.
- Navigate to IAM & Admin > Service Accounts in the Google Cloud Console.
- Click Create Service Account.
- Enter a service account name and description, then click Create and Continue.
- Grant the service account the Pub/Sub Publisher and Pub/Sub Subscriber roles.
- Click Done.
- Click on the created service account, go to the Keys tab.
- Click Add Key > Create new key.
- Select JSON and click Create.
- Save the downloaded JSON file securely - you'll need the path to this file for authentication.
- In the Google Cloud Console, navigate to Pub/Sub > Topics.
- Click Create Topic.
- Enter the topic ID -
my-topic. - Click Create.
- In the Google Cloud Console, navigate to Pub/Sub > Subscriptions.
- Click Create Subscription.
- Enter the subscription ID -
my-subscription. - Select the topic you created earlier (
my-topic) from the dropdown. - Choose the delivery type (Pull is recommended for the Ballerina listener).
- Click Create.
To use the Google Cloud Pub/Sub connector in your Ballerina application, modify the .bal file as follows:
Import the ballerinax/gcloud.pubsub module into your Ballerina project.
import ballerinax/gcloud.pubsub;Create a pubsub:Publisher instance with your Google Cloud Pub/Sub configuration.
configurable string project = ?; // GCP Project ID
configurable string topic = ?; // Pub/Sub Topic Name
configurable string gcpCredentialsFilePath = ?; // Path to Service Account JSON file
pubsub:Publisher publisher = check new (
project,
topic,
auth = {
path: gcpCredentialsFilePath
}
);Now, utilize the available publisher operations to publish messages.
string messageId = check publisher->publish({
data: "Hello, Google Pub/Sub!".toBytes()
});string messageId = check publisher->publish({
data: "Hello, Google Pub/Sub!".toBytes(),
attributes: {
"source": "ballerina-app",
"version": "1.0"
}
});check publisher->publish({
data: "Message 1".toBytes(),
orderingKey: "customer-123"
});When done, close the publisher to release resources.
check publisher->close();Create a pubsub:Listener instance to consume messages from a subscription.
configurable string project = ?;
configurable string gcpCredentialsFilePath = ?;
listener pubsub:Listener pubsubListener = check new (
project,
projectId = projectId,
auth = {
path: gcpCredentialsFilePath
}
);Attach a service to the listener to process incoming messages.
configurable string subscription = ?;
@pubsub:ServiceConfig {
subscription
}
service on pubsubListener {
remote function onMessage(pubsub:Message message, pubsub:Caller caller) returns error? {
// Process the message
io:println("Received message: ", check string:fromBytes(message.data));
// Print attributes if present
if message.attributes is map<string> {
io:println("Attributes: ", message.attributes);
}
// Acknowledge the message
check caller->ack();
}
}@pubsub:ServiceConfig {
subscription
}
service on pubsubListener {
remote function onMessage(pubsub:PubSubMessage message, pubsub:Caller caller) returns error? {
// Process the message
error? result = processMessage(message);
if result is error {
// If processing fails, nack the message so it can be redelivered
io:println("Error processing message: ", result.message());
check caller->nack();
} else {
// If processing succeeds, acknowledge the message
check caller->ack();
}
}
}
function processMessage(pubsub:PubSubMessage message) returns error? {
// Your message processing logic here
io:println("Processing message: ", check string:fromBytes(<byte[]>message.data));
}bal runTo report bugs, request new features, start new discussions, view project boards, etc., go to the Ballerina library parent repository.
-
Download and install Java SE Development Kit (JDK) version 21 (from one of the following locations).
Execute the commands below to build from the source.
-
To build the library:
./gradlew clean build -
To run the tests:
./gradlew clean testNote: To run integration tests, you need:
- A Google Cloud project with Pub/Sub API enabled
- Service account credentials with appropriate permissions
- Set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable
-
To build the library without the tests:
./gradlew clean build -x test -
To debug library implementation:
./gradlew clean build -Pdebug=<port> -
To debug the library with Ballerina language:
./gradlew clean build -PbalJavaDebug=<port> -
Publish ZIP artifact to the local
.m2repository:./gradlew clean build publishToMavenLocal -
Publish the generated artifacts to the local Ballerina central repository:
./gradlew clean build -PpublishToLocalCentral=true -
Publish the generated artifacts to the Ballerina central repository:
./gradlew clean build -PpublishToCentral=true
As an open source project, Ballerina welcomes contributions from the community.
For more information, go to the contribution guidelines.
All the contributors are encouraged to read the Ballerina Code of Conduct.
- For more information go to the
gcloud.pubsublibrary. - For example demonstrations of the usage, go to Ballerina By Examples.
- Chat live with us via our Discord server.
- Post all technical questions on Stack Overflow with the #ballerina tag.