Pub/Sub interviews are rarely about remembering a list of product features. The stronger answers show that you understand delivery semantics, can make consumers safe under redelivery, and can explain how the system behaves when dependencies fail.
This guide focuses on one useful sub-area of GCP Cloud interviews: Pub/Sub delivery, ordering, and replay. It moves from fundamentals to system design and includes runnable Node.js examples using the Google Cloud Pub/Sub client.
Fundamentals
1. What does Pub/Sub guarantee when a publisher sends a message?
What the interviewer is testing: Whether you distinguish successful publication from successful business processing.
Model answer:
- A publisher sends a message to a topic. Pub/Sub assigns it a message ID and stores it according to the topic’s configuration.
- A successful publish response means Pub/Sub accepted the message. It does not mean that any subscriber has processed it.
- A subscription provides a delivery stream to its subscriber. With the usual at-least-once delivery behavior, a message can be delivered more than once.
- The consumer must therefore make its side effects idempotent or otherwise safe to repeat.
The critical boundary is between transport acceptance and business completion. If a publisher must know that a business operation completed, it needs an application-level response or workflow—not just a successful publish call.
Minimal runnable publisher, assuming the topic exists and Application Default Credentials are configured:
npm install @google-cloud/pubsub
const { PubSub } = require("@google-cloud/pubsub");
async function main() {
const pubsub = new PubSub();
const topic = pubsub.topic(process.env.TOPIC_ID);
const messageId = await topic.publishMessage({
json: {
eventId: crypto.randomUUID(),
type: "invoice.created",
invoiceId: "inv-123",
},
});
console.log(JSON.stringify({ messageId }));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Run it with TOPIC_ID set and Google Cloud credentials available to the process. What to notice: the returned message ID confirms publication, not subscriber completion.
Follow-up: How would the publisher learn that a downstream operation finished?
Hint: Separate transport acknowledgment from application-level completion.
2. How do topics and subscriptions relate?
What the interviewer is testing: Whether you understand fan-out and the difference between a message stream and a consumer’s delivery state.
Model answer:
A topic is the named destination for published messages. A subscription is a durable delivery relationship to a topic, with its own acknowledgment state, retention configuration, and delivery behavior.
Multiple subscriptions can receive copies of messages published to the same topic. Within one subscription, subscribers typically share the work: a message is delivered to one subscriber at a time for that subscription, subject to redelivery. That is different from having several subscriptions, each of which receives its own copy.
This distinction makes subscriptions useful for independent consumers—for example, one subscription for billing and another for analytics. It also means subscription configuration and lifecycle deserve the same attention as topic configuration.
Follow-up: What happens to an existing subscription’s backlog if you create a second subscription?
Hint: A new subscription has its own delivery state; it is not a shared cursor.
3. When would you use a pull subscription instead of a push subscription?
What the interviewer is testing: Whether you can choose a delivery mode based on workload control, not fashion.
Model answer:
A pull subscriber requests messages and controls how quickly it accepts work. This is a natural fit for worker services that need local flow control, long-running processing, or careful control over concurrency.
A push subscription sends messages to an HTTPS endpoint. It can simplify integration with an HTTP service, but the endpoint must be reachable and able to respond according to Pub/Sub’s delivery protocol. The service also needs to manage the relationship between its HTTP response and completion of the actual business work.
| Consideration | Pull | Push |
|---|---|---|
| Workload control | Consumer can control outstanding messages and concurrency | Delivery is driven by Pub/Sub requests to the endpoint |
| Network model | Subscriber connects to Pub/Sub | Pub/Sub calls an HTTPS endpoint |
| Typical fit | Worker pools and services with explicit backpressure | HTTP-based consumers that can process and respond promptly |
| Failure handling | Consumer controls acknowledgment or negative acknowledgment | Endpoint response affects delivery outcome |
| Main design concern | Bound in-flight work to processing capacity | Keep endpoint available and make response semantics correct |
Choose the mode that lets the consumer enforce its processing limits and failure policy clearly.
Follow-up: What would you do if a push handler’s downstream database becomes slow?
Hint: Consider response timing, concurrency, and how the endpoint signals failure.
4. What does message ordering mean in Pub/Sub?
What the interviewer is testing: Whether you can state the scope and cost of ordering precisely.
Model answer:
Ordering is not a global sequence across a topic. Pub/Sub can preserve ordering for messages that share an ordering key when the subscription is configured for ordered delivery and the publisher uses the key consistently.
Ordering constrains parallelism. If events for one customer must be applied in sequence, that customer can be the ordering key. Events for different customers can still be processed independently. A hot key, however, can become a throughput bottleneck, and a failed message can hold up later messages for that key until the delivery problem is resolved.
Do not use ordering to repair an underspecified domain model. If consumers need to handle stale or out-of-order updates, include a version or sequence number in the event and validate it at the point of applying the change.
Follow-up: How would you preserve per-account ordering while allowing parallel processing across accounts?
Hint: Choose a stable ordering key that maps to the account boundary.
Intermediate
5. When should a subscriber acknowledge a message?
What the interviewer is testing: Whether you know that acknowledgment timing determines loss and redelivery behavior.
Model answer:
Acknowledge only after the business work that must not be lost has completed durably. If a consumer acknowledges before committing its database transaction and then crashes, Pub/Sub may consider the message handled even though the business change was never saved.
If the consumer commits its change and crashes before the acknowledgment is recorded, Pub/Sub can redeliver the message. That is why “commit, then acknowledge” still requires idempotency. Acknowledgment is not a distributed transaction spanning Pub/Sub and your database.
The useful interview answer is to describe both failure windows and explain the deduplication strategy, rather than claim that one particular acknowledgment order gives exactly-once business effects.
Follow-up: What happens if the database commit succeeds but the acknowledgment fails?
Hint: Assume the message can arrive again and make the database operation safe to repeat.
6. How do retries and dead-letter topics help with poison messages?
What the interviewer is testing: Whether you can distinguish transient failures from messages that cannot succeed.
Model answer:
A negative acknowledgment or an acknowledgment deadline that expires can lead to redelivery. That is appropriate for transient problems, such as a short database outage. It is wasteful for a permanently invalid payload: repeatedly delivering the same message can consume capacity and block progress, especially when ordering is enabled.
A dead-letter topic gives messages that exceed a configured delivery-attempt policy another destination for inspection or remediation. It is not a substitute for understanding why the message failed. The attempt threshold should be chosen with the expected failure modes and recovery process in mind; delivery-attempt behavior should not be treated as a precise business retry counter.
A robust consumer should:
- Emit a useful failure reason without logging secrets or full sensitive payloads.
- Retry transient failures with bounded load on downstream services.
- Route persistent failures to a dead-letter path.
- Provide an operational process to inspect, correct, and deliberately replay messages.
The following example adds idempotency around a database side effect. It assumes a PostgreSQL database and a subscription configured with an appropriate dead-letter policy.
CREATE TABLE processed_events (
event_id text PRIMARY KEY,
processed_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE invoices (
invoice_id text PRIMARY KEY,
amount_cents bigint NOT NULL
);
const { PubSub } = require("@google-cloud/pubsub");
const { Pool } = require("pg");
const pubsub = new PubSub();
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const subscription = pubsub.subscription(process.env.SUBSCRIPTION_ID, {
flowControl: { maxMessages: 20 },
});
async function processMessage(message) {
const event = JSON.parse(message.data.toString());
if (!event.eventId || !event.invoiceId || !Number.isInteger(event.amountCents)) {
throw new Error("Invalid invoice event");
}
const client = await pool.connect();
try {
await client.query("BEGIN");
const inserted = await client.query(
`INSERT INTO processed_events (event_id)
VALUES ($1)
ON CONFLICT DO NOTHING
RETURNING event_id`,
[event.eventId],
);
if (inserted.rowCount === 1) {
await client.query(
`INSERT INTO invoices (invoice_id, amount_cents)
VALUES ($1, $2)
ON CONFLICT (invoice_id)
DO UPDATE SET amount_cents = EXCLUDED.amount_cents`,
[event.invoiceId, event.amountCents],
);
}
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
subscription.on("message", (message) => {
void processMessage(message)
.then(() => message.ack())
.catch((error) => {
console.error(JSON.stringify({
event: "message_processing_failed",
messageId: message.id,
error: error.message,
}));
message.nack();
});
});
What to notice: the deduplication record and business change commit in the same database transaction; acknowledgment happens afterward. In production, validate event schemas, configure process shutdown, and use dead-letter handling for messages that cannot succeed.
Follow-up: What would you change if the event triggers an external payment API instead of a database update?
Hint: A local database transaction cannot atomically commit an external side effect.
7. Does Pub/Sub exactly-once delivery mean exactly-once processing?
What the interviewer is testing: Whether you can explain the boundary of a delivery guarantee.
Model answer:
No. Pub/Sub supports an exactly-once delivery option for eligible pull subscriptions, but that guarantee is about delivery and acknowledgment behavior within Pub/Sub—not a transaction with your database, payment provider, or other external system.
Your consumer can still perform a side effect and fail before Pub/Sub records the acknowledgment. A retry can then repeat the side effect. Exactly-once delivery can reduce certain redeliveries, but it does not remove the need for idempotency when side effects must remain correct.
Describe exactly-once as one layer of a design, not a property that makes the whole business workflow exactly once.
Follow-up: When would you still use an idempotency key with exactly-once delivery enabled?
Hint: Follow the failure boundary between the subscriber and its downstream system.
8. How would you replay messages after discovering a consumer bug?
What the interviewer is testing: Whether you understand retention, subscription state, and safe recovery.
Model answer:
First decide whether the goal is to retry unacknowledged messages, replay a selected time range, or rebuild a consumer’s state. Those are different recovery operations.
Pub/Sub supports replay mechanisms such as seeking a subscription to a timestamp or to a snapshot. The messages must still be available under the relevant retention configuration; replay cannot recover data that has expired. A separate subscription can also isolate a backfill or corrected consumer from the live subscription’s progress.
Before replaying, verify that the consumer is idempotent, estimate the backlog’s impact on downstream capacity, and define how live traffic and replay traffic will interact. Replaying to a side-effecting consumer without a deduplication plan can repeat work that already succeeded.
Follow-up: How would you replay safely without slowing live processing?
Hint: Consider separate consumer capacity and an isolated subscription or processing path.
Senior and system-design level
9. How do you size and protect a subscriber under bursty traffic?
What the interviewer is testing: Whether you can design for backpressure rather than just add more workers.
Model answer:
Start with measured arrival rate, message size, processing latency, and the capacity of dependencies. Treat any planning figures as assumptions until validated with production-like tests. A subscriber that can read faster than its database can commit simply moves the queue into memory or creates downstream overload.
Use flow control to bound outstanding messages, and set worker concurrency based on safe dependency capacity. Scale out when backlog or oldest-message age indicates sustained demand, but avoid reacting to a short burst in a way that overloads a shared database. If the dependency is saturated, scaling consumers can make recovery slower.
Separate independent workloads into different subscriptions or services when they have different latency and failure requirements. Monitor both queue delay and downstream saturation; queue depth alone does not tell you whether the system is recovering.
Follow-up: The backlog is growing, but database CPU is already high. What do you do?
Hint: More consumers may worsen the bottleneck; control intake and investigate the dependency.
10. How should event schemas evolve without breaking consumers?
What the interviewer is testing: Whether you treat events as long-lived contracts rather than internal method calls.
Model answer:
Prefer additive, backward-compatible changes: add optional fields with sensible defaults, and do not silently change the meaning or type of an existing field. Consumers should tolerate fields they do not recognize, while producers should not assume every consumer deploys at the same time.
For stronger contract control, use Pub/Sub schemas and choose an evolution strategy that matches the producer-consumer rollout model. Validate at publication boundaries and in consumer tests. A schema registry or schema validation does not make a breaking semantic change safe: a field can remain type-compatible while its meaning changes.
Version events when the domain meaning changes enough that old consumers cannot interpret the new contract correctly.
Follow-up: How would you introduce a required field when old consumers are still deployed?
Hint: Use a staged rollout that keeps the event readable by both versions.
11. How would you design regional resilience for a Pub/Sub workload?
What the interviewer is testing: Whether you can reason about failure domains without promising more than the service guarantees.
Model answer:
Begin with the required recovery objectives and the specific failure being addressed: a subscriber instance failure, a regional outage, a project-level issue, or a downstream dependency failure. A design that handles one does not automatically handle the others.
Deploy consumers so they can be replaced and scaled, and keep their processing state in a durable system with its own recovery plan. Understand the topic and subscription location configuration and the service’s documented behavior before making claims about regional availability or message residency. If you need a second independent processing path, account for duplicate effects and define how it is activated.
Test the recovery procedure, including credentials, network dependencies, replay limits, and database failover. “Multi-region” is not a recovery plan unless the activation and consistency behavior are explicit.
Follow-up: What would you test during a regional recovery exercise?
Hint: Validate the complete path from message availability through durable side effects.
12. Design a Pub/Sub pipeline that processes customer events, preserves per-customer order, and supports recovery.
What the interviewer is testing: Whether you can bring together ordering, idempotency, capacity, and operational recovery.
Model answer:
Use a topic for the event stream and a subscription for the business consumer. Publish each event with a stable customer ordering key if per-customer order is required. Include a unique application event ID and, where useful, a customer-scoped sequence or version number.
The consumer should have bounded concurrency and perform idempotent writes. It should acknowledge only after durable processing, send persistent failures to a dead-letter path, and expose a documented replay procedure. Keep replay capacity from overwhelming the live workload; a separate subscription or controlled backfill process may be appropriate.
flowchart LR Producer["Event producer"] --> Topic["Pub/Sub topic"] Topic --> Subscription["Ordered subscription"] Subscription --> Worker["Bounded consumer workers"] Worker --> Database["Idempotent database writes"] Subscription --> DeadLetter["Dead-letter topic"] DeadLetter --> Review["Inspect and repair"] Review --> Replay["Controlled replay"] Replay --> Worker
Caption: A recovery-capable pipeline separates normal processing, durable side effects, and deliberate replay.
The architecture still needs explicit choices for retention, schema compatibility, ordering keys, database capacity, and who is authorized to replay. A good design answer states those assumptions rather than presenting the diagram as a complete specification.
Follow-up: What changes if one customer produces enough traffic to dominate the subscription?
Hint: Revisit the ordering requirement and the hot-key trade-off.
Comparison: Pub/Sub, Cloud Tasks, and Eventarc
These products can all participate in asynchronous systems, but they solve different problems.
| Product | Best fit | Delivery model | Design emphasis |
|---|---|---|---|
| Pub/Sub | Event distribution and independent consumers | Topic and subscription; fan-out across subscriptions | Consumer idempotency, backlog, ordering, retention, replay |
| Cloud Tasks | Dispatching individual work items to a specific handler | Managed task delivery to an endpoint | Scheduling, rate control, task-level retry behavior |
| Eventarc | Routing events from supported sources to destinations | Event routing based on source and filters | Event source integration and destination configuration |
Use Pub/Sub when consumers need an event stream and independent delivery state. Use Cloud Tasks when the application needs to dispatch controlled work to a handler. Use Eventarc when the central requirement is routing supported events to a target. Avoid selecting by product label alone: compare the retry, ordering, replay, and destination requirements of the actual workflow.
Common mistakes candidates make
- Calling a successful publish “processed.” It only confirms acceptance by the publishing API.
- Assuming messages arrive exactly once. Redelivery is a normal failure mode; side effects need a deduplication strategy.
- Claiming exactly-once delivery makes business effects exactly once. Pub/Sub cannot make an external database transaction atomic.
- Using ordering as a substitute for version checks. Ordering has a key scope and can limit throughput; consumers may still need to reject stale updates.
- Acknowledging before durable work completes. A process crash can turn that shortcut into lost business work.
- Retrying poison messages forever. Persistent failures need inspection and a controlled dead-letter workflow.
- Scaling consumers without checking dependencies. More workers can amplify database saturation.
- Treating replay as harmless. A replay can repeat side effects and compete with live traffic.
- Ignoring event contract evolution. Producers and consumers deploy independently; additive changes and compatibility tests matter.
- Describing regional recovery vaguely. State which failure is handled and how the processing path is restored.
Observability for a Pub/Sub consumer
Good observability distinguishes a healthy queue from a healthy business workflow. Instrument the consumer service, its dependencies, and the Pub/Sub delivery path together.
What to log
Use structured logs with stable identifiers that support investigation across publisher, subscriber, and business storage. Avoid logging full message bodies, credentials, or other sensitive fields.
{
"severity": "ERROR",
"event": "message_processing_failed",
"subscription": "invoice-worker",
"message_id": "pubsub-message-id",
"event_id": "invoice-event-id",
"attempt_context": "delivery",
"error_type": "database_timeout",
"trace_id": "trace-id"
}
Log processing outcomes, retryable versus permanent failure classification, dead-letter routing, replay operations, and changes to subscription configuration. Keep high-cardinality identifiers in logs or traces rather than using them as metric labels.
Metrics to watch
Use RED for the consumer service and USE for its constrained resources.
| View | Signals | Questions answered |
|---|---|---|
| RED: consumer | Messages processed, processing latency, failures | Is the service handling work reliably and quickly? |
| RED: dependencies | Database request rate, latency, errors | Is downstream work limiting throughput? |
| USE: worker capacity | CPU and memory utilization, worker saturation, in-flight messages | Are workers or their resources saturated? |
| Queue health | Backlog, oldest unprocessed message age, dead-letter volume | Is work keeping up, and are failures accumulating? |
Names and availability of individual Cloud Monitoring metrics depend on the service and configuration; choose the relevant Pub/Sub and runtime metrics from the current metric catalog.
Distributed tracing with OpenTelemetry
Create a span around message processing and attach non-sensitive identifiers. Propagate trace context in message attributes if end-to-end producer-to-consumer trace continuity is required; do not assume an application-level publish call automatically establishes that propagation.
const {
trace,
SpanStatusCode,
} = require("@opentelemetry/api");
const tracer = trace.getTracer("invoice-consumer");
async function traceMessageProcessing(message, processMessage) {
return tracer.startActiveSpan("pubsub.process", async (span) => {
span.setAttribute("messaging.system", "gcp_pubsub");
span.setAttribute("messaging.message.id", message.id);
try {
await processMessage(message);
} catch (error) {
span.recordException(error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
throw error;
} finally {
span.end();
}
});
}
This snippet uses the OpenTelemetry API; configure an SDK and exporter in the application to send spans to your chosen telemetry backend.
SLI and SLO examples
These are illustrative target assumptions, not Google Cloud defaults. Define the measurement window and eligible traffic precisely before adopting them.
| SLI | Example SLO target assumption | Why it matters |
|---|---|---|
| Successful processing latency | 99% of eligible messages processed within the agreed latency objective | Measures whether events reach useful completion in time |
| Processing success | 99.9% of valid messages complete without manual intervention over the chosen window | Captures the consumer’s operational reliability |
| Oldest-message age | Remains below the business-approved delay objective during normal operation | Detects a queue that is falling behind |
Alerts worth paging on
Page when the service is likely to need immediate human action: oldest-message age breaches the business objective and continues rising; processing failures or dead-letter volume rise sharply; or a downstream dependency is saturated and the backlog is growing. Alert on sustained symptoms and clear recovery criteria, not every short-lived delivery retry. Route lower-urgency configuration drift and isolated invalid messages to a ticket or operational dashboard.
Quick-revision checklist
Before an interview, make sure you can explain:
- Why publish success does not mean business processing succeeded.
- How topics differ from subscriptions and why subscriptions have independent state.
- When pull, push, Cloud Tasks, or Eventarc fits the workload.
- The scope and trade-off of ordering keys.
- Why acknowledgment should follow durable work.
- How idempotency handles the commit-before-ack failure window.
- What exactly-once delivery does—and does not—guarantee.
- How dead-letter handling and replay fit a recovery process.
- How backpressure protects downstream dependencies.
- How event schemas evolve across independently deployed consumers.
- Which metrics, traces, logs, and SLOs reveal delayed or failing processing.
A strong Pub/Sub interview answer is concrete about boundaries: what Pub/Sub guarantees, what the application must guarantee, and how the team will detect and recover when those guarantees meet a real failure.
This article was generated with AI. #AIGenerated