Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Google pubsub push subscription ack

I have a cloud run endpoint that gets triggered by a push type pubsub subscription and it recives the user specified message thorugh publsiher,I am trying to get the message acknowledged by the acknowldgement time but the cloud run endpoint is getting triggered multiple times ,not sure if my message is getting acknowldged or not.I want to check what is the process to make sure the message gets acknolwedged with status 200ok response to pubsub in python so that there will not be any retires after one successful attempt.

Solved Solved
1 11 9,505
1 ACCEPTED SOLUTION

Here is how to acknowledge a message in a Cloud Run endpoint triggered by a push-type Pub/Sub subscription and prevent retries:

Acknowledgment in Push Subscriptions:

For push subscriptions, where Pub/Sub sends messages to your Cloud Run service endpoint, acknowledgment occurs implicitly through an HTTP response. There's no need for the .ack() or .nack() methods used in pull subscriptions.

Acknowledgement with 200 OK:

To acknowledge a message successfully and prevent retries, your Cloud Run service needs to respond with an HTTP 200 OK status code. This tells Pub/Sub that the message was processed successfully and shouldn't be redelivered.

Example Code:

The following Python code demonstrates how to handle message processing and acknowledgment in a Cloud Run service:

 
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    # Extract Pub/Sub message from request
    envelope = request.get_json()
    message = envelope['message']

    try:
        # Process message
        # ...

        # Acknowledge message with 200 OK
        return '', 200
    except Exception as e:
        # Log exception
        # ...

        # Message not acknowledged, will be retried
        return '', 500

if __name__ == '__main__':
    app.run(port=8080, debug=True)

Additional Considerations:

  • Error Handling: Implement robust error handling and logging to capture any issues during message processing.
  • Idempotency: Ensure your message processing logic is idempotent, meaning it can be safely executed multiple times without unintended consequences. This is important as Pub/Sub might redeliver messages even after successful acknowledgment in certain scenarios.
  • Response Time: Be mindful of your service's response time. If it takes too long to respond, exceeding the acknowledgment deadline configured in the subscription, Pub/Sub might consider the message unreceived and send it again.

View solution in original post

11 REPLIES 11