Pub/Sub Interview Questions and Answers Part 1 - Pub/Sub Fundamentals and Architecture

Pub/Sub Interview Q&A · Part 1 of 10

In this post we are going to cover Pub/Sub fundamentals and architecture. These are 7 real Pub/Sub interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: the business wants order events from the website available to billing, shipping and analytics in near real time, and you design it.

Pub/Sub is Google Cloud's messaging service. One service publishes a message to a topic, and every team that needs it reads it through its own subscription. Interviewers start here because everything else in a streaming pipeline, acks, ordering, dead letters, BigQuery, builds on these few ideas. If you can explain topics, subscriptions and fan-out clearly, and you know what happens to a message nobody is subscribed to yet, the rest of the interview gets much easier.

Part 1 of the Real Time Pub/Sub Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Pub/Sub is Google Cloud's fully managed, serverless messaging service: publishers write to a topic, and every subscription on that topic gets its own copy of each message, which its consumers ack. Delivery is at least once, messages published before a subscription exists are lost unless the topic retains them, and Managed Service for Apache Kafka is the choice when you need the Kafka API (Pub/Sub Lite was turned down in March 2026).

Let's set up the project

We run Google's official Pub/Sub emulator locally, with small Python scripts that use the google-cloud-pubsub client, so every output is real. Features the emulator doesn't support are shown as code. Everything lives in the project tb-shop-dev. Here are the starting files. The first step, python setup.py, creates the orders topic and three subscriptions, and we look at its output in question 2.

setup.py
from google.cloud import pubsub_v1

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()

topic = publisher.topic_path(project, "orders")
publisher.create_topic(name=topic)
print("topic", topic)
for name in ["billing", "shipping", "audit"]:
    sub = subscriber.create_subscription(request={
        "name": subscriber.subscription_path(project, name),
        "topic": topic,
        "retain_acked_messages": name == "audit"})
    print(f"{name}: ack deadline {sub.ack_deadline_seconds}s,",
          "retention", sub.message_retention_duration)
publish.py
import json, sys
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic = publisher.topic_path("tb-shop-dev", sys.argv[1])
first, count = int(sys.argv[2]), int(sys.argv[3])
for order_id in range(first, first + count):
    data = json.dumps({"order_id": order_id}).encode()   # bytes
    future = publisher.publish(topic, data,
                               event_type="order_created")
    print("published order", order_id, "as message", future.result())
pull.py
import sys
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
name = sys.argv[1]
path = subscriber.subscription_path("tb-shop-dev", name)
resp = subscriber.pull(subscription=path, max_messages=10, timeout=10)
msgs = sorted(resp.received_messages, key=lambda r: r.message.data)
for r in msgs:
    m = r.message
    print(name, "id", m.message_id, m.data.decode(),
          dict(m.attributes))
subscriber.acknowledge(subscription=path,
                       ack_ids=[r.ack_id for r in msgs])
print(name, "acked", len(msgs))
types_check.py
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic = publisher.topic_path("tb-shop-dev", "orders")
tries = {
    "text data": lambda: publisher.publish(topic, "order 1004"),
    "number attribute": lambda: publisher.publish(
        topic, b"order 1004", amount=19.99),
}
for label, publish in tries.items():
    try:
        publish()
    except TypeError as e:
        print(label, "->", e)
workers.py
import json
from google.cloud import pubsub_v1

path = "projects/tb-shop-dev/subscriptions/billing"
worker_a = pubsub_v1.SubscriberClient()
worker_b = pubsub_v1.SubscriberClient()
a = worker_a.pull(subscription=path, max_messages=2, timeout=10)
b = worker_b.pull(subscription=path, max_messages=10, timeout=10)
for name, client, resp in (("worker-a", worker_a, a),
                           ("worker-b", worker_b, b)):
    msgs = resp.received_messages
    ids = sorted(json.loads(r.message.data)["order_id"] for r in msgs)
    print(name, "got orders", ids)
    client.acknowledge(subscription=path,
                       ack_ids=[r.ack_id for r in msgs])
replay.py
import datetime
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
path = subscriber.subscription_path("tb-shop-dev", "audit")

def read_and_ack(label):
    resp = subscriber.pull(subscription=path, max_messages=50,
                           timeout=10)
    ack_ids = [r.ack_id for r in resp.received_messages]
    if ack_ids:
        subscriber.acknowledge(subscription=path, ack_ids=ack_ids)
    print(label, len(ack_ids), "messages")

read_and_ack("read and acked:")
read_and_ack("read again:")
now = datetime.datetime.now(datetime.timezone.utc)
an_hour_ago = now - datetime.timedelta(hours=1)
subscriber.seek(request={"subscription": path, "time": an_hour_ago})
read_and_ack("after seek to one hour ago:")
late.py
from google.cloud import pubsub_v1

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic = publisher.topic_path(project, "refunds")
publisher.create_topic(name=topic)              # no subscription yet
msg_id = publisher.publish(topic, b"r-1").result()
print("refund r-1 published as message", msg_id)

sub = subscriber.subscription_path(project, "refunds-audit")
subscriber.create_subscription(name=sub, topic=topic)
print("created subscription refunds-audit")
msg_id = publisher.publish(topic, b"r-2").result()
print("refund r-2 published as message", msg_id)

resp = subscriber.pull(subscription=sub, max_messages=10, timeout=10)
got = [r.message.data.decode() for r in resp.received_messages]
print("refunds-audit received", got)
design.py
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1.types import DeadLetterPolicy

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic = publisher.topic_path(project, "order-events")
dlq = publisher.topic_path(project, "order-events-dlq")
for t in (topic, dlq):
    publisher.create_topic(name=t)
subscriber.create_subscription(       # keeps the dead letters
    name=subscriber.subscription_path(project,
                                      "order-events-dlq-sub"),
    topic=dlq)
sub = subscriber.create_subscription(request={
    "name": subscriber.subscription_path(project, "billing-sub"),
    "topic": topic,
    "dead_letter_policy": DeadLetterPolicy(
        dead_letter_topic=dlq, max_delivery_attempts=5)})
policy = sub.dead_letter_policy
print("billing-sub dead letters go to",
      policy.dead_letter_topic.split("/")[-1])
print("after", policy.max_delivery_attempts, "delivery attempts")
billing_worker.py
import json
from concurrent.futures import TimeoutError
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
path = subscriber.subscription_path("tb-shop-dev", "billing-sub")
billed = []

def handle(message):
    billed.append(json.loads(message.data)["order_id"])  # bill it
    message.ack()

flow = pubsub_v1.types.FlowControl(max_messages=100)
future = subscriber.subscribe(path, callback=handle,
                              flow_control=flow)
with subscriber:
    try:
        future.result(timeout=10)      # a real worker runs forever
    except TimeoutError:
        future.cancel()
        future.result()
print("billing worker processed orders", sorted(billed))

Question 1: Your manager asks what Pub/Sub is and why the team should not just call each service directly. What do you say?

Pub/Sub is Google Cloud's fully managed, serverless messaging service. Publishers send messages to a topic, and subscribers receive them through subscriptions. Neither side needs to know about the other.

Why not direct calls? Direct calls couple everything. If checkout calls billing, shipping and analytics one by one, one slow or broken service slows or breaks checkout. With Pub/Sub, checkout publishes once and moves on.

Let's prove it. The shipping service is down, and checkout publishes three orders with python publish.py orders 1001 3.

Terminal
$ python publish.py orders 1001 3
published order 1001 as message 1
published order 1002 as message 2
published order 1003 as message 3

Each publish returns a message ID: published order 1001 as message 1, then messages 2 and 3. Checkout doesn't care that shipping is down. Now shipping comes back and reads its subscription with python pull.py shipping.

Terminal
$ python pull.py shipping
shipping id 1 {"order_id": 1001} {'event_type': 'order_created'}
shipping id 2 {"order_id": 1002} {'event_type': 'order_created'}
shipping id 3 {"order_id": 1003} {'event_type': 'order_created'}
shipping acked 3

The three orders were waiting: ids 1, 2 and 3, each with {'event_type': 'order_created'}, and then shipping acked 3. Shipping was down, and nothing was lost.

Publishers and subscribers also scale independently, from kilobytes to gigabytes per second per topic, and you pay for what you use.

Say the trade-off

Delivery is at least once, so consumers must handle duplicates. And typical latency is around 100 ms, so Pub/Sub doesn't replace a call that needs an answer right away.

Question 2: A new teammate asks how topics, subscriptions and messages fit together. How do you explain it?

A topic is a named feed that publishers write to. A subscription is attached to one topic, and it's one consumer's own stream: it keeps each message until that consumer acks it.

Let's run python setup.py. It creates the orders topic and three subscriptions: billing, shipping and audit.

Terminal
$ python setup.py
topic projects/tb-shop-dev/topics/orders
billing: ack deadline 10s, retention 7 days, 0:00:00
shipping: ack deadline 10s, retention 7 days, 0:00:00
audit: ack deadline 10s, retention 7 days, 0:00:00

The topic path is projects/tb-shop-dev/topics/orders. Each subscription gets the defaults: ack deadline 10s and retention 7 days, 0:00:00. That retention is for unacked messages, and we can set it from 10 minutes to 31 days.

Then the message itself. A message is data plus attributes:

  • data - bytes
  • attributes - a map of strings, like event_type=order_created
  • message_id, publish_time - set by the server
  • ordering_key - optional

In Python the types are checked before anything is sent. Let's try text data and a number attribute with python types_check.py.

Terminal
$ python types_check.py
text data -> Data being published to Pub/Sub must be sent as a bytestring.
number attribute -> All attributes being published to Pub/Sub must be sent as text strings.

Text data fails with Data being published to Pub/Sub must be sent as a bytestring., and the number attribute fails with All attributes being published to Pub/Sub must be sent as text strings.

There are three kinds of subscription:

  • Pull - your code asks for messages
  • Push - Pub/Sub calls your HTTPS endpoint
  • Export - BigQuery, Cloud Storage (Bigtable: Preview)
Real project

Each consuming service owns a subscription named after it. Two different services never share one.

Question 3: Two teams both need every order event. How does fan-out work with one topic and several subscriptions?

Give each team its own subscription on the same topic. Every subscription gets its own copy of every message, and each team acks at its own pace.

Shipping already read orders 1001 to 1003 in question 1. Let's see what billing gets with python pull.py billing.

Terminal
$ python pull.py billing
billing id 1 {"order_id": 1001} {'event_type': 'order_created'}
billing id 2 {"order_id": 1002} {'event_type': 'order_created'}
billing id 3 {"order_id": 1003} {'event_type': 'order_created'}
billing acked 3

Billing still gets the same three orders, with the same message IDs, 1, 2 and 3, and billing acked 3. Acks on one subscription don't touch the other.

Inside one subscription, it's the opposite: workers share the work. Let's publish four more orders, 1004 to 1007, and run python workers.py. Worker A pulls up to two messages and holds them. Then worker B pulls from the same billing subscription.

Terminal
$ python publish.py orders 1004 4
published order 1004 as message 4
published order 1005 as message 5
published order 1006 as message 6
published order 1007 as message 7
$ python workers.py
worker-a got orders [1004, 1005]
worker-b got orders [1006, 1007]

worker-a got orders [1004, 1005] and worker-b got orders [1006, 1007]. Worker B gets only the other two, because an outstanding message normally isn't handed to a second worker before its ack deadline.

So the rule is simple:

  • Scale a consumer - add workers to its subscription
  • Add a consumer - add a subscription

The publisher never changes.

Cost pitfall

Delivery throughput is billed for every subscription, so ten subscriptions pay to deliver the data ten times. Add a subscription when a team really needs the stream.

Question 4: Someone asks whether Pub/Sub is a queue or a log like Kafka. How do you compare them?

Each subscription works like a queue: acks are per message, and an acked message is done for that subscription. Kafka is a log: a consumer group tracks an offset per partition, and the data stays until retention removes it.

Pub/Sub subscriptionKafka consumer group
Progressan ack per messagean offset per partition
After processingacked: done for this subscriptionthe data stays until retention

Let's look at the audit subscription. It was created with retain acked messages on. python replay.py reads and acks everything, reads again, then seeks to one hour ago and reads a third time.

Terminal
$ python replay.py
read and acked: 7 messages
read again: 0 messages
after seek to one hour ago: 7 messages

First read and acked: 7 messages, then read again: 0 messages. That's the queue side. But Pub/Sub can replay too: after the seek we get after seek to one hour ago: 7 messages, all seven back. Topic retention and snapshots also give you replay.

Then the other differences.

Pub/SubKafka
Scalingno partitions to managepartitions cap a consumer group
Orderingper ordering keywithin a partition
Retentionup to 31 dayscan be indefinite
Per-record acksevery subscriptionshare groups (Kafka 4.2)
Replayseek: retain acked, topic retention, snapshotsreset offsets

Pub/Sub has no partitions to manage, ordering is per ordering key, and retention is at most 31 days. Kafka orders within a partition and can keep data indefinitely. Kafka 4.2 also added share groups, which ack per record.

My interview line

Pub/Sub is a managed message service with queue semantics per subscription, plus replay. Choose Kafka when you need the log itself: very long retention, event sourcing, or the Kafka API.

Question 5: A teammate asks what happens to a message published before any subscription exists. How do you answer?

It's lost. By default, a topic doesn't store messages. A message published to a topic with no subscription isn't retained, and a subscription created later never sees it.

Let's prove it with python late.py. It creates the refunds topic, publishes refund r-1, then creates the refunds-audit subscription, publishes r-2, and pulls.

Terminal
$ python late.py
refund r-1 published as message 8
created subscription refunds-audit
refund r-2 published as message 9
refunds-audit received ['r-2']

Refund r-1 gets message 8, and r-2 gets message 9. But refunds-audit received ['r-2']. Only r-2.

The first publish succeeded, so nobody got an error. That's why this is a silent data loss bug in new pipelines.

There are two fixes:

  • Fix 1 - create the subscriptions before the publishers go live, in the same Terraform or deployment as the topic
  • Fix 2 - turn on topic message retention, from 10 minutes to 31 days, so the topic keeps messages itself and you can replay them with seek

The emulator doesn't apply retention, so the second fix is shown as code.

topic-retention.sh
# real service: the topic itself keeps messages for 7 days
gcloud pubsub topics create refunds \
    --message-retention-duration=7d
Same rule

Dead-letter topics need a subscription too, or the forwarded messages are lost as well.

Question 6: Your manager asks when to choose Pub/Sub over Pub/Sub Lite or Managed Kafka on Google Cloud. How do you decide?

First, Pub/Sub Lite is off the table. It was deprecated in June 2024 and turned down on March 18, 2026. Google's migration paths are Pub/Sub or Managed Service for Apache Kafka.

So the real choice is between two. Let's compare them.

Pub/SubManaged Service for Apache Kafka (GA Nov 2024)
Capacityserverless, absorbs unpredictable loadyou plan partitions and capacity
Built indead lettering, filters, BigQuery and Cloud Storage exportKafka Connect, the Kafka ecosystem
APIPub/Sub API: not Kafka compatiblethe Apache Kafka API
Orderingper ordering keyper partition
Pick it fornew pipelines on Google CloudKafka clients, lift and shift, event sourcing

Choose Pub/Sub by default for new pipelines on Google Cloud. It's serverless, it absorbs unpredictable load, and dead lettering, filters, and export subscriptions to BigQuery and Cloud Storage are built in.

Choose Managed Service for Apache Kafka, generally available since November 2024, when you need the Kafka API: existing Kafka clients and connectors, a lift and shift, steady high throughput with ordering per key, or event sourcing.

One thing people miss: Pub/Sub has its own API. It isn't Kafka compatible, so moving from Kafka to Pub/Sub means changing the clients.

My rule

If the team already runs Kafka code, go to Managed Kafka. If you're building new on Google Cloud, start with Pub/Sub, and nobody has to plan partitions or capacity.

Scenario 7: The business wants order events from the website available to billing, shipping and analytics in near real time. How would you design it?

One order-events topic, published by the website's checkout service, and one subscription per consumer. That's fan-out: each team gets every event and acks on its own.

  • Checkout - website publisher
  • order-events - topic
  • billing-sub - pull: streaming pull worker
  • shipping-push - push: Cloud Run with OIDC
  • analytics-bq - export: BigQuery subscription

First, let's create the topic, a dead-letter topic with its own subscription, and the billing subscription with python design.py.

Terminal
$ python design.py
billing-sub dead letters go to order-events-dlq
after 5 delivery attempts

It prints billing-sub dead letters go to order-events-dlq, after 5 delivery attempts. So a bad event isn't redelivered forever, and the dead letters have a subscription that keeps them. Every subscription gets a dead-letter topic like this.

Billing runs a streaming pull worker with flow control. We start billing_worker.py, and three seconds later checkout publishes three orders.

Terminal
$ python billing_worker.py & sleep 3; python publish.py order-events 2001 3; wait
published order 2001 as message 10
published order 2002 as message 11
published order 2003 as message 12
billing worker processed orders [2001, 2002, 2003]

Checkout publishes messages 10, 11 and 12, and the worker prints billing worker processed orders [2001, 2002, 2003].

Shipping runs on Cloud Run, so it gets a push subscription with an OIDC token from a service account. Analytics needs no code: a BigQuery subscription writes every event into a table. The emulator can't call Cloud Run or write to BigQuery, so those two are gcloud commands.

subscriptions.sh
SA=push-sa@tb-shop-prod.iam.gserviceaccount.com   # has run.invoker
gcloud pubsub subscriptions create shipping-push \
    --topic=order-events --push-auth-service-account=$SA \
    --push-endpoint=https://shipping-abc123-uc.a.run.app/orders
# the Pub/Sub service agent needs roles/bigquery.dataEditor
gcloud pubsub subscriptions create analytics-bq \
    --topic=order-events --use-table-schema \
    --bigquery-table=tb-shop-prod:sales.order_events

Then the contract and the alerts. Add an event_type attribute for filtering, and a schema on the topic as the contract. Alert on the oldest unacked message age for each subscription.

Don't forget

Make every consumer idempotent, because delivery is at least once.

Key points to remember

  • Topic = where publishers write; subscription = one consumer's stream
  • Fan-out: one subscription per team; workers share a subscription
  • Per-message acks like a queue, plus replay with seek
  • No subscription yet = lost, unless the topic retains messages
  • Pub/Sub Lite is gone; Managed Kafka when you need the Kafka API

The full script

This is a Python script that writes every file and runs every command above in order against the Pub/Sub emulator: run pip install google-cloud-pubsub first.

Show the full script that writes the files and runs every step
Full script - writes the files and runs every step against the Pub/Sub emulator (pip install google-cloud-pubsub), run it with Python
# ========================================================================
# Pub/Sub Interview Q&A #1 - Pub/Sub fundamentals and architecture
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the official Google Cloud Pub/Sub emulator (gcloud component, version 0.8.37)
# with google-cloud-pubsub 2.43.0; the outputs in the video and the blog post are the real outputs.
# To run it yourself (Linux, macOS or WSL):
#   1. gcloud components install pubsub-emulator   then   gcloud beta emulators pubsub start --project=tb-shop-dev
#   2. In a second terminal: export PUBSUB_EMULATOR_HOST=localhost:8085 PUBSUB_PROJECT_ID=tb-shop-dev
#   3. pip install google-cloud-pubsub   then   python PubSub_Interview_QA_01_Code.py   in an empty folder.
# Steps that restart the emulator say so in a comment: stop and start it by hand at that point.
# ========================================================================

import os, subprocess, time

def write(path, text):
    if text is None:
        if os.path.exists(path): os.remove(path)
        return
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False, allow_error=False, env=None):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
    if rc != 0 and not (expect_error or allow_error):
        raise SystemExit("stopped: this command was expected to succeed")

# Step 0: the starting files
write('setup.py', """\
from google.cloud import pubsub_v1

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()

topic = publisher.topic_path(project, "orders")
publisher.create_topic(name=topic)
print("topic", topic)
for name in ["billing", "shipping", "audit"]:
    sub = subscriber.create_subscription(request={
        "name": subscriber.subscription_path(project, name),
        "topic": topic,
        "retain_acked_messages": name == "audit"})
    print(f"{name}: ack deadline {sub.ack_deadline_seconds}s,",
          "retention", sub.message_retention_duration)
""")
write('publish.py', """\
import json, sys
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic = publisher.topic_path("tb-shop-dev", sys.argv[1])
first, count = int(sys.argv[2]), int(sys.argv[3])
for order_id in range(first, first + count):
    data = json.dumps({"order_id": order_id}).encode()   # bytes
    future = publisher.publish(topic, data,
                               event_type="order_created")
    print("published order", order_id, "as message", future.result())
""")
write('pull.py', """\
import sys
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
name = sys.argv[1]
path = subscriber.subscription_path("tb-shop-dev", name)
resp = subscriber.pull(subscription=path, max_messages=10, timeout=10)
msgs = sorted(resp.received_messages, key=lambda r: r.message.data)
for r in msgs:
    m = r.message
    print(name, "id", m.message_id, m.data.decode(),
          dict(m.attributes))
subscriber.acknowledge(subscription=path,
                       ack_ids=[r.ack_id for r in msgs])
print(name, "acked", len(msgs))
""")
write('types_check.py', """\
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic = publisher.topic_path("tb-shop-dev", "orders")
tries = {
    "text data": lambda: publisher.publish(topic, "order 1004"),
    "number attribute": lambda: publisher.publish(
        topic, b"order 1004", amount=19.99),
}
for label, publish in tries.items():
    try:
        publish()
    except TypeError as e:
        print(label, "->", e)
""")
write('workers.py', """\
import json
from google.cloud import pubsub_v1

path = "projects/tb-shop-dev/subscriptions/billing"
worker_a = pubsub_v1.SubscriberClient()
worker_b = pubsub_v1.SubscriberClient()
a = worker_a.pull(subscription=path, max_messages=2, timeout=10)
b = worker_b.pull(subscription=path, max_messages=10, timeout=10)
for name, client, resp in (("worker-a", worker_a, a),
                           ("worker-b", worker_b, b)):
    msgs = resp.received_messages
    ids = sorted(json.loads(r.message.data)["order_id"] for r in msgs)
    print(name, "got orders", ids)
    client.acknowledge(subscription=path,
                       ack_ids=[r.ack_id for r in msgs])
""")
write('replay.py', """\
import datetime
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
path = subscriber.subscription_path("tb-shop-dev", "audit")

def read_and_ack(label):
    resp = subscriber.pull(subscription=path, max_messages=50,
                           timeout=10)
    ack_ids = [r.ack_id for r in resp.received_messages]
    if ack_ids:
        subscriber.acknowledge(subscription=path, ack_ids=ack_ids)
    print(label, len(ack_ids), "messages")

read_and_ack("read and acked:")
read_and_ack("read again:")
now = datetime.datetime.now(datetime.timezone.utc)
an_hour_ago = now - datetime.timedelta(hours=1)
subscriber.seek(request={"subscription": path, "time": an_hour_ago})
read_and_ack("after seek to one hour ago:")
""")
write('late.py', """\
from google.cloud import pubsub_v1

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic = publisher.topic_path(project, "refunds")
publisher.create_topic(name=topic)              # no subscription yet
msg_id = publisher.publish(topic, b"r-1").result()
print("refund r-1 published as message", msg_id)

sub = subscriber.subscription_path(project, "refunds-audit")
subscriber.create_subscription(name=sub, topic=topic)
print("created subscription refunds-audit")
msg_id = publisher.publish(topic, b"r-2").result()
print("refund r-2 published as message", msg_id)

resp = subscriber.pull(subscription=sub, max_messages=10, timeout=10)
got = [r.message.data.decode() for r in resp.received_messages]
print("refunds-audit received", got)
""")
write('design.py', """\
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1.types import DeadLetterPolicy

project = "tb-shop-dev"
publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic = publisher.topic_path(project, "order-events")
dlq = publisher.topic_path(project, "order-events-dlq")
for t in (topic, dlq):
    publisher.create_topic(name=t)
subscriber.create_subscription(       # keeps the dead letters
    name=subscriber.subscription_path(project,
                                      "order-events-dlq-sub"),
    topic=dlq)
sub = subscriber.create_subscription(request={
    "name": subscriber.subscription_path(project, "billing-sub"),
    "topic": topic,
    "dead_letter_policy": DeadLetterPolicy(
        dead_letter_topic=dlq, max_delivery_attempts=5)})
policy = sub.dead_letter_policy
print("billing-sub dead letters go to",
      policy.dead_letter_topic.split("/")[-1])
print("after", policy.max_delivery_attempts, "delivery attempts")
""")
write('billing_worker.py', """\
import json
from concurrent.futures import TimeoutError
from google.cloud import pubsub_v1

subscriber = pubsub_v1.SubscriberClient()
path = subscriber.subscription_path("tb-shop-dev", "billing-sub")
billed = []

def handle(message):
    billed.append(json.loads(message.data)["order_id"])  # bill it
    message.ack()

flow = pubsub_v1.types.FlowControl(max_messages=100)
future = subscriber.subscribe(path, callback=handle,
                              flow_control=flow)
with subscriber:
    try:
        future.result(timeout=10)      # a real worker runs forever
    except TimeoutError:
        future.cancel()
        future.result()
print("billing worker processed orders", sorted(billed))
""")

# Step 1: Create the orders topic and three subscriptions
run('python setup.py')

# Step 2: Data must be bytes, attributes must be strings
run('python types_check.py')

# Step 3: Shipping is down: checkout still publishes three orders
run('python publish.py orders 1001 3')

# Step 4: Shipping comes back and reads the orders waiting in its subscription
run('python pull.py shipping')

# Step 5: Fan-out: billing gets the same three orders
run('python pull.py billing')

# Step 6: Two workers on one subscription share the messages
run('python publish.py orders 1004 4')
run('python workers.py')

# Step 7: Queue or log: ack, read again, then seek back
run('python replay.py')

# Step 8: A message published before any subscription exists
run('python late.py')

# Step 9: Scenario: the order-events topic, a dead-letter topic and the billing subscription
run('python design.py')

# Step 10: Scenario: the billing worker is running when checkout publishes
run('python billing_worker.py & sleep 3; python publish.py order-events 2001 3; wait')
Next in this series

Part 2: Publishing and Message Attributes

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the official Google Cloud Pub/Sub emulator with google-cloud-pubsub 2.43.0. Features the emulator does not support are shown as code. Part of the Real Time Pub/Sub Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Pub/Sub documentation (cloud.google.com/pubsub/docs) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.