CodexBloom - Programming Q&A Platform

GCP Pub/Sub message ordering implementing Node.js SDK when using multiple subscriptions

๐Ÿ‘€ Views: 166 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
google-cloud-pubsub node.js message-queue JavaScript

I'm having trouble with I've been banging my head against this for hours... I'm working with a question with message ordering in Google Cloud Pub/Sub when using the Node.js SDK. I've set up a topic with two subscriptions and I'm trying to ensure that messages sent to the topic are processed in the same order by both subscriptions. However, I am seeing messages being delivered out of order when using the async subscription pull method. Here's a snippet of how I'm publishing messages: ```javascript const { PubSub } = require('@google-cloud/pubsub'); const pubsub = new PubSub(); async function publishMessages() { const topicName = 'my-topic'; const messages = ['msg1', 'msg2', 'msg3']; for (const message of messages) { const dataBuffer = Buffer.from(message); await pubsub.topic(topicName).publish(dataBuffer); console.log(`Message ${message} published.`); } } publishMessages(); ``` And hereโ€™s how Iโ€™m subscribing to those messages: ```javascript const subscriptionName = 'my-subscription'; const subscription = pubsub.subscription(subscriptionName); const messageHandler = message => { console.log(`Received message: ${message.data.toString()}`); message.ack(); }; subscription.on('message', messageHandler); ``` The scenario arises when I publish these messages in quick succession; I notice that they arrive at the subscriber out of order. Iโ€™ve also ensured that the delivery type for the subscriptions is set to `EXACTLY_ONCE`. I've read that configuring the `enableMessageOrdering` option might help, but Iโ€™m not sure how to implement it correctly. Could someone provide insights on how to ensure message ordering across multiple subscriptions? Any best practices or configuration settings I might be missing? Iโ€™m using the `@google-cloud/pubsub` version 2.9.0. I'm working on a web app that needs to handle this. Is there a better approach? Am I missing something obvious?