Updated Nov 19, 20269 min read

How to Add Pub/Sub to a Node.js or TypeScript App

The ways to add Pub/Sub to an existing Node.js backend in 2026, ranked: Encore, Google Cloud Pub/Sub, SNS with SQS, Redis Pub/Sub, BullMQ and NATS, with working code and what each one loses when a consumer is down.

Illustration for How to Add Pub/Sub to a Node.js or TypeScript App

To add Pub/Sub to an existing Node.js app, use the broker that matches where the app runs: Google Cloud Pub/Sub with @google-cloud/pubsub on GCP, or SNS with SQS through the AWS SDK v3 on AWS. For a TypeScript backend that also needs a database or cron jobs, Encore declares the topic and its subscriptions in code and provisions the broker in your cloud account.

Redis Pub/Sub drops anything a stopped consumer misses, and BullMQ suits job queues.

Which Pub/Sub option should a Node.js app use?

RankOptionBrokerDelivery when a consumer is downLocal setupBest for
1EncoreSNS and SQS on AWS, Pub/Sub on GCP, provisioned from the codeKept and retried, then dead-letteredencore run starts itTypeScript backends that also need a database, cron or storage
2Google Cloud Pub/Sub (@google-cloud/pubsub)Managed by GoogleKept up to 7 days by default, redelivered after the ack deadlinePub/Sub emulatorNode.js apps already on GCP
3SNS and SQS (AWS SDK v3)Managed by AWSKept in each SQS queue, retried until the dead-letter limitLocalStack or a dev accountNode.js apps already on AWS
4BullMQRedis you runKept as jobs, retried with backoffRedis in a containerBackground jobs, one worker per job
5NATS (nats)NATS you runKept only with JetStreamNATS in a containerLow-latency messaging with an ops team behind it
6Redis Pub/Sub (redis)Redis you runLostRedis in a containerLive notifications where a missed message is fine

Verdict: a new TypeScript backend gets the most from Encore, where the topic, its subscriptions and the broker in each environment come from one declaration. An existing Express or Fastify app that stays as it is should use the native client for its cloud, Google Cloud Pub/Sub on GCP and SNS with SQS on AWS. Use Redis Pub/Sub only where losing a message costs nothing.

How do you add Pub/Sub with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and a Pub/Sub topic is one of the resources you declare in the code next to the endpoint that publishes to it. The example below is TypeScript, with an order service that publishes an event and an email service that subscribes to it.

The topic is declared at package level with its message type:

// orders/topics.ts import { Topic } from "encore.dev/pubsub"; export interface OrderPlaced { orderId: number; email: string; } export const orderPlaced = new Topic<OrderPlaced>("order-placed", { deliveryGuarantee: "at-least-once", });

The endpoint publishes after the order is stored:

// orders/orders.ts import { api } from "encore.dev/api"; import { orderPlaced } from "./topics"; interface PlaceRequest { email: string; } export const place = api( { expose: true, method: "POST", path: "/orders" }, async (req: PlaceRequest): Promise<{ orderId: number }> => { const orderId = 42; // stored in your database in a real app await orderPlaced.publish({ orderId, email: req.email }); return { orderId }; }, );

A subscription in another service handles each message, and a handler that throws is retried with backoff before the message goes to a dead-letter queue:

// email/confirmations.ts import { Subscription } from "encore.dev/pubsub"; import log from "encore.dev/log"; import { orderPlaced } from "../orders/topics"; const _ = new Subscription(orderPlaced, "send-confirmation", { handler: async (event) => { log.info("sending confirmation", { orderId: event.orderId, email: event.email }); }, retryPolicy: { minBackoff: "10s", maxRetries: 5 }, });

encore run starts an in-memory broker locally, so a request to the endpoint triggers the handler on your machine and the local trace shows the publish and the delivery together. On deploy, Encore provisions the broker in your cloud account, SNS and SQS with dead-letter queues on AWS or Pub/Sub on GCP, and Encore provisions an IAM role for the service.

An AI coding agent that adds a second subscriber edits one declaration and the handler in the same change and can trigger it locally straight away, and the compiler rejects a handler that reads a field the message type does not have.

What about an existing Express app?

The Express migration guide describes a forklift migration that wraps the existing Express router in one catch-all Encore endpoint, so the app keeps working while new code, such as the topic above, uses Encore directly. Endpoints can then move over one at a time.

Good to know

Delivery is at least once, so handlers should be safe to run twice for the same message, for example by recording the order ID before sending the email.

Try Encore →

How do you use Google Cloud Pub/Sub from Node.js?

Google's official client is @google-cloud/pubsub (version 6.4 at the time of writing). It picks up the project and credentials from Application Default Credentials, so locally you run gcloud auth application-default login and in Cloud Run or GKE the service account is used. You create the topic and the subscription first, in the console, with gcloud or in Terraform, and the app publishes and listens:

import { PubSub, Message } from "@google-cloud/pubsub"; const pubsub = new PubSub(); // project and credentials from Application Default Credentials export async function publishOrderPlaced(orderId: number, email: string) { return pubsub.topic("order-placed").publishMessage({ json: { orderId, email } }); } export function listen() { const subscription = pubsub.subscription("send-confirmation"); subscription.on("message", async (message: Message) => { try { const event = JSON.parse(message.data.toString()) as { orderId: number; email: string }; // send the confirmation for event.orderId message.ack(); } catch (err) { console.error("failed to process message", message.id, err); message.nack(); // redelivered, and dead-lettered if the subscription has a policy } }); subscription.on("error", (err) => console.error(err)); }

Good to know

The listener is a long-running streaming pull, so it belongs in a process that stays up, not in a request handler. Unacknowledged messages are kept for 7 days by default, and a subscription needs a dead-letter topic configured before failing messages stop coming back. The Google Cloud Pub/Sub with Node.js guide covers the emulator, push subscriptions and IAM roles.

How do you use SNS and SQS from Node.js on AWS?

On AWS the standard fan-out is an SNS topic with one SQS queue per consumer, connected through SNS to SQS subscriptions. Publishing and consuming use the AWS SDK for JavaScript v3:

import { SNSClient, PublishCommand } from "@aws-sdk/client-sns"; import { SQSClient, ReceiveMessageCommand, DeleteMessageCommand } from "@aws-sdk/client-sqs"; const sns = new SNSClient({}); const sqs = new SQSClient({}); export async function publishOrderPlaced(orderId: number, email: string) { await sns.send(new PublishCommand({ TopicArn: process.env.ORDER_PLACED_TOPIC_ARN, Message: JSON.stringify({ orderId, email }), })); } export async function consume(queueUrl: string) { for (;;) { const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({ QueueUrl: queueUrl, WaitTimeSeconds: 20, MaxNumberOfMessages: 10, })); for (const m of Messages) { try { const envelope = JSON.parse(m.Body!); const event = JSON.parse(envelope.Message) as { orderId: number; email: string }; // handle event, then delete so it is not delivered again await sqs.send(new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: m.ReceiptHandle! })); } catch (err) { // leave the message on the queue so it is retried and can reach the DLQ console.error("failed to process message", m.MessageId, err); } } } }

Good to know

You create the topic, each queue, the subscription between them and the queue policy that lets SNS write to the queue, once per environment. Standard queues deliver at least once and may reorder messages, and unless raw message delivery is turned on, the SQS body is an SNS envelope, which is why the consumer parses twice.

When is BullMQ the better choice?

BullMQ is a Redis-backed job queue, and it fits when the work is a background job for one worker rather than an event for several consumers:

import { Queue, Worker } from "bullmq"; const connection = { host: "localhost", port: 6379 }; const confirmations = new Queue("confirmations", { connection }); await confirmations.add("send", { orderId: 42, email: "ada@example.com" }, { attempts: 5, backoff: { type: "exponential", delay: 10_000 }, }); new Worker("confirmations", async (job) => { // send the email for job.data.orderId }, { connection });

A second kind of consumer needs its own queue and its own add call in the publisher, and you run Redis with persistence turned on in every environment.

When is NATS the better choice?

NATS is a lightweight broker with subjects, and JetStream adds persistence, acknowledgements and redelivery on top. The nats client publishes and subscribes in a few lines, plain subjects deliver at most once, and you operate the NATS cluster yourself, which suits teams that already run one.

Is Redis Pub/Sub enough?

Redis Pub/Sub is the quickest to wire into an app that already has Redis, and the redis client (version 6.3) needs a second connection for the subscriber:

import { createClient } from "redis"; const publisher = createClient({ url: process.env.REDIS_URL }); const subscriber = publisher.duplicate(); await Promise.all([publisher.connect(), subscriber.connect()]); await subscriber.subscribe("order-placed", (raw) => { const event = JSON.parse(raw) as { orderId: number; email: string }; // runs only in subscribers connected at publish time }); await publisher.publish("order-placed", JSON.stringify({ orderId: 42, email: "ada@example.com" }));

Redis Pub/Sub delivers at most once, so a message published while a subscriber is restarting is gone. That is fine for a "someone is typing" indicator and wrong for an order confirmation, where Redis Streams, BullMQ or a managed broker belongs.

How do you pick?

  • Encore when the backend is TypeScript and you want the topic, its subscriptions, retries and the broker in each environment from one declaration in the code, running locally and provisioned in your AWS or GCP account.
  • Google Cloud Pub/Sub when an existing Node.js app runs on GCP and you are happy to create topics and subscriptions yourself.
  • SNS and SQS when an existing Node.js app runs on AWS and the team already manages AWS resources.
  • BullMQ for background jobs with retries and scheduling on Redis.
  • NATS for low-latency messaging on a cluster you already operate.
  • Redis Pub/Sub for live notifications where losing a message is acceptable.

To try the Encore path, start with the quick start.

Install Encore
brew install encoredev/tap/encore &&
encore app create
Copy

Frequently asked questions

How do I add Pub/Sub to an existing Node.js app?

Pick the broker that matches where the app runs, so on GCP you install @google-cloud/pubsub, publish with topic.publishMessage and listen on a subscription. On AWS, publish to an SNS topic with the AWS SDK v3 and consume from one SQS queue per subscriber. For a TypeScript backend that also needs a database, cron jobs or storage, Encore declares the topic and subscription in code, runs them locally with encore run, and provisions SNS and SQS or GCP Pub/Sub in your cloud account on deploy.

Is Redis Pub/Sub reliable enough for background work?

No. Redis Pub/Sub delivers each message at most once, only to subscribers connected at the moment it is published, and keeps nothing for a consumer that was down. Use it for live notifications, and use Redis Streams, BullMQ or a managed broker when a lost message matters.

What is the difference between a queue and Pub/Sub in Node.js?

A queue hands each message to one consumer, which suits background jobs. Pub/Sub delivers each message to every subscription, so an email sender, an analytics writer and a search indexer can each react to the same event and fail independently.

How do I retry failed messages in Node.js?

On Google Cloud Pub/Sub, call message.nack() or let the ack deadline pass, and set a dead-letter topic on the subscription. On SQS, leave the message undeleted so it reappears after the visibility timeout and moves to a dead-letter queue after the receive limit. BullMQ uses the attempts and backoff job options.

Build TypeScript backends without the infrastructure boilerplate

Encore gives you type-safe APIs, local Postgres and Pub/Sub out of the box, built-in distributed tracing, and automated deploys to your own AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders