CodexBloom - Programming Q&A Platform

implementing Google Cloud Pub/Sub message ordering in Node.js client library

πŸ‘€ Views: 46 πŸ’¬ Answers: 1 πŸ“… Created: 2025-05-31
google-cloud pubsub nodejs JavaScript

I'm upgrading from an older version and This might be a silly question, but This might be a silly question, but I'm currently working on a Node.js application that uses Google Cloud Pub/Sub to handle asynchronous tasks..... I've set up two subscriptions to the same topic with the intention of processing messages in a specific order. However, I’m noticing that messages are not being processed in the order they were published, even though I have enabled message ordering for my subscriptions. Here’s how I set it up: ```javascript const { PubSub } = require('@google-cloud/pubsub'); const pubsub = new PubSub(); const topicName = 'my-topic'; const subscriptionName = 'my-subscription'; // Create a topic with ordering enabled await pubsub.createTopic(topicName, { enableOrdering: true }); // Create a subscription with ordering enabled await pubsub.topic(topicName).createSubscription(subscriptionName, { enableOrdering: true }); ``` When I publish messages like this: ```javascript const messageIds = await pubsub.topic(topicName).publish(Buffer.from(JSON.stringify({ order: 1 })), { orderingKey: 'key1' }); const messageIds2 = await pubsub.topic(topicName).publish(Buffer.from(JSON.stringify({ order: 2 })), { orderingKey: 'key1' }); ``` I expect that the message with `order: 1` is delivered before `order: 2`, but that's not what I'm observing. I've also tried adding a delay between the publishes and using the same ordering key, but it still doesn't seem to help. Additionally, I'm receiving some errors in the logs like `UNAVAILABLE: Service unavailable` intermittently when I try to publish messages at a high rate. I suspect this might be linked to how the Pub/Sub service handles message ordering under load. Am I missing something in the configuration, or is there a best practice for ensuring ordered message delivery in a high-throughput scenario? Any insights would be appreciated! Is there a better approach? What am I doing wrong? This is for a microservice running on Windows 11. I'd really appreciate any guidance on this.