I'm building a job queue by using Cloud Pub/Sub and I want to receive the messages in the order that the Pub/Sub service receives them. I created a topic and a subscription with message ordering enabled. I'm developing my system in Python with the google-cloud-pubsub
package. As suggested in this doc, I must publish messages with ordering keys.
If messages have the same ordering key and you publish the messages to the same region, subscribers can receive the messages in order.
On the subscriber side, I need to process messages in batch, so I use the max_messages
parameter to control. However, when I enable the message ordering option, for every time I can't pull max_messages
messages as expected but only one message from the subscription. Strangely, when I disable the message ordering, it returns max_messages
messages.
Publisher code:
...
topic_path = 'xxx'
ordering_key = '202011240000'
while True:
job = {'job_id': 'xxxxxx', 'foo': 0, 'bar': 0}
data = json.dumps(job, default=str).encode('utf-8')
publisher.publish(topic_path, data=data, ordering_key=ordering_key)
time.sleep(1)
Subscriber code:
...
subscription_path = 'xxx'
subscriber.pull(request={'subscription': subscription_path, 'max_messages': 300})
...
I did something wrong or Pub/Sub is designed as this?