Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-solution-event-driven-decoupling@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cloud-solution-event-driven-decoupling v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cloud-solution-event-driven-decoupling Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cloud-solution-event-driven-decoupling/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-solution-event-driven-decoupling for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 16.9 KB
---
name: google-cloud-solution-event-driven-decoupling
metadata:
version: "1.0.0"
category: MultiProductSolutions
description: >-
Decouples tightly coupled services or monoliths with Google Cloud Pub/Sub so
services scale and fail independently, using Go reference implementations
adaptable to Java, Python, Node.js, and other stacks. Use when breaking apart
synchronous chains, defining transaction boundaries, bulkheads, and
Transactional Outbox or post-commit publishing; sizing Pub/Sub topics,
subscription filters, dead-letter policies, backoff, 10 MB Cloud Storage
claim-check, or database-bounded flow control; building idempotent consumers
with ack/nack/quarantine handling, SIGTERM draining, GKE HPA, Cloud Run push,
Eventarc, or Cloud Run functions (--retry); or instrumenting OpenTelemetry W3C
Trace Context across HTTP, gRPC, and Pub/Sub with Cloud Trace OTLP export and
Cloud Logging correlation. Don't use for querying existing traces (use
cloud-trace-querying), Kafka or non-Google brokers, or orchestration engines
such as Workflows or Managed Service for Apache Airflow.
---
# Event-driven decoupling with Pub/Sub
Break a distributed monolith or tightly coupled service chain apart with
asynchronous messaging on Pub/Sub so services scale and fail independently.
This skill uses **progressive disclosure** across **Phases 0–5** (with Phase 0
inline below and modular `references/` files for Phases 1–5): run the full
end-to-end migration sequence for architecture journeys, or load **only** the
single phase reference needed for a focused design, code, or troubleshooting
request.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Progressive disclosure: load only the phase you need
| Phase & module | Reference to load | Produces | Load when |
| --- | --- | --- | --- |
| **0. Frame the goal** | Inline in `SKILL.md` (see [End-to-end workflow and phase gates](#end-to-end-workflow-and-phase-gates)) | Business outcome, runtime/DB constraints, measurable acceptance criteria | Starting any end-to-end decoupling journey before design begins |
| **1. Assess** (Synchronous coupling assessment) | [Coupling assessment & transaction boundaries](references/phase1-coupling-assessment.md); plus [Go & SQL outbox, post-commit, and bulkheads](references/phase1-outbox-and-bulkheads-go.md) when authoring producer/outbox code | Measured baseline, call graph, transaction cut, outbox vs state-marker decision, event catalog, bulkhead plan | Auditing synchronous HTTP/gRPC/DB chains, Cloud Trace / Cloud SQL lock waits, dual writes, schema freezes, reference-lookup caching, or deciding what becomes an event |
| **2. Design messaging** (Pub/Sub topic and subscription design) | [Pub/Sub topology, flow-control sizing, DLQ, and claim-check](references/phase2-pubsub-topology-and-sizing.md) | Domain topics vs dedicated topics, subscription filters, dead-letter policy + service-agent IAM, backoff, DB-bounded flow control, 10 MB claim-check | Sizing `MaxOutstandingMessages`, ack deadlines, or retry delays; choosing filtered vs per-event topics; handling payloads near/above 1–10 MB; or fixing DLQ delivery |
| **3. Build consumers** (Event-driven workflow triggering) | [Consumer ack/nack matrix, SIGTERM drain, GKE HPA, and Cloud Run](references/phase3-consumer-and-autoscaling.md) | Idempotent Go dispatcher, sentinel-error ack/nack/quarantine matrix, single-deadline SIGTERM drain, GKE `autoscaling/v2` HPA, Cloud Run / Eventarc / Cloud Run functions (`--retry`) | Writing or reviewing consumer handlers, fixing rollout `context canceled` or duplicate bugs, scaling GKE on `num_undelivered_messages`, or configuring Cloud Run / Eventarc triggers |
| **4. Observe** (Distributed trace instrumentation) | [OpenTelemetry propagation, OTLP export, and Cloud Logging correlation](references/phase4-distributed-tracing.md) | `otelhttp`/`otelgrpc` wrapping, Pub/Sub built-in tracing or attribute carrier, `telemetry.googleapis.com:443` OTLP + Cloud Run sampler, `slog` correlation, `InMemoryExporter` tests | Propagating traces across Pub/Sub, instrumenting synchronous HTTP/gRPC-only services, fixing missing Cloud Run traces or unlinked `slog` logs, or **before Phase 1** when a service has no traces |
| **5. Cut over & validate** (Cut-over & acceptance) | [Solution checklist and hand-off template](references/solution-checklist.md) | Phase gate table, event catalog template, budget worksheet, observable acceptance checks | Defining measurable acceptance criteria, tracking phase hand-offs, executing Strangler dual-run cut-over, or validating post-cut-over gates |
**Routing rules**:
- **End-to-end requests**: run Phases 0–5 sequentially, loading each phase's
reference only when that phase begins. Two exceptions apply:
- *Greenfield consumers*: run Phases 3 and 4 together so new consumers
ship with distributed tracing from day one.
- *Missing observability*: if the user's primary problem is missing
latency visibility or absent distributed traces, run Phase 4
([references/phase4-distributed-tracing.md](references/phase4-distributed-tracing.md))
first to establish a trace baseline before proposing Pub/Sub changes,
then resume Phases 1–3.
- **Focused single-phase requests**: load **only** the matching phase
reference, name which phase file applies, and never dump unrelated phases:
- *Flow-control / subscription configuration questions*
(`MaxOutstandingMessages`, ack deadline, `max-delivery-attempts`,
backoff): load **only** Phase 2
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md)).
Relate flow control to the database connection pool and ack deadline to
the per-message processing timeout; do **not** present the Phase 1
coupling matrix, Transactional Outbox, or Phase 3 consumer handler code.
- *Consumer handler ack/nack questions*: load **only** Phase 3
([references/phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md)).
Provide the handler logic (never provisioning commands alone) and note
that the subscription ack deadline must exceed the handler's processing
timeout.
- **Non-Go languages and other SQL engines**: Phases 1, 3, and 4 provide
compiled Go (`cloud.google.com/go/pubsub/v2`, `database/sql`, OpenTelemetry
Go) and PostgreSQL reference code, while Phase 2 maps flow-control fields
across Go, Python, Java, and Node.js. When the user's workload uses another
language (such as Java, Python, or Node.js) or database (such as MySQL or
Oracle), keep every architectural invariant and phase gate unchanged,
translate the patterns into idiomatic SDK and SQL constructs for the
requested stack, and state explicitly that you are adapting the Go reference
patterns.
## Prerequisites
Use the Google Cloud CLI (install guide:
https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt) and, for GKE,
`kubectl`. Never install host tools or grant IAM bindings without explicit user
approval: both alter the user's host or production access. If `gcloud` is
unavailable, produce design artifacts, code, Kubernetes YAML, or Terraform
directly.
1. **Billing** is attached to `{project_id}`. Pub/Sub, Cloud Trace, and Cloud
Logging have free allotments, but an active billing account is still
required (https://cloud.google.com/pricing,
https://cloud.google.com/pubsub/pricing,
https://cloud.google.com/run/pricing,
https://cloud.google.com/kubernetes-engine/pricing,
https://cloud.google.com/stackdriver/pricing).
2. **Project, region, authentication, and APIs** (default `us-central1`,
https://cloud.google.com/about/locations):
```bash
gcloud config set project {project_id}
gcloud config set compute/region {region}
gcloud auth login # Local CLI
gcloud auth application-default login # SDK / ADC; workloads use Workload Identity Federation for GKE or GOOGLE_APPLICATION_CREDENTIALS
gcloud services enable pubsub.googleapis.com cloudtrace.googleapis.com telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com
# Add per workload: cloudprofiler.googleapis.com (Phase 1), storage.googleapis.com (claim-check),
# container.googleapis.com (GKE, default), or run.googleapis.com eventarc.googleapis.com cloudfunctions.googleapis.com (Cloud Run)
```
3. **Least-privilege IAM**: one service account per producer and consumer;
never `roles/editor` (*why:* basic roles grant project-wide write across
every service).
| Principal | Role | Scope | Phase |
| --- | --- | --- | --- |
| Assessor identity (read-only) | `roles/cloudtrace.user`, `roles/monitoring.viewer`, `roles/cloudprofiler.user` | `{project_id}` | 1 |
| Producer service account | `roles/pubsub.publisher` (`+ roles/storage.objectCreator` on `{claim_check_bucket}` if claim-check) | `{topic_id}` | 2 |
| Consumer service account | `roles/pubsub.subscriber` (`+ roles/storage.objectViewer` on `{claim_check_bucket}` if claim-check) | `{subscription_id}` | 2–3 |
| Pub/Sub service agent `service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com` | `roles/pubsub.publisher` on `{dlq_topic_id}` **and** `roles/pubsub.subscriber` on `{subscription_id}` | dead-lettering | 2 |
| Metrics adapter (`custom-metrics-stackdriver-adapter`) | `roles/monitoring.viewer` | `{project_id}` | 3 |
| Push / Eventarc trigger service account (Cloud Run path) | `roles/run.invoker`, `roles/eventarc.eventReceiver` | service / trigger | 3 |
| Producer and consumer service accounts | `roles/telemetry.tracesWriter`, `roles/logging.logWriter` | `{project_id}` | 4 |
## End-to-end workflow and phase gates
1. **Phase 0 - Frame the goal**: capture the business outcome (independent
scaling, isolated failure, shorter p99, removable batch windows) and
constraints (schema freeze, language, runtime GKE vs Cloud Run, data
residency) as measurable acceptance criteria before designing.
2. **Phase 1 - Assess** ([phase1-coupling-assessment.md](references/phase1-coupling-assessment.md),
[phase1-outbox-and-bulkheads-go.md](references/phase1-outbox-and-bulkheads-go.md)).
**Gate**: baseline p99 latency, connection saturation, and lock-wait
numbers recorded per hop; every outbound event has a name, owning team,
idempotency key, and Transactional Outbox vs state-marker decision; zero
network calls remain inside a database transaction. **Gate enforcement**:
if the user claims assessment is finished and asks for `gcloud` topic or
subscription creation commands while only naming events without confirming
those Phase 1 gate items, **do not** emit `gcloud pubsub topics create` or
`subscriptions create` commands and **do not** invent payload schemas or
owners; ask to confirm the missing Phase 1 gate items first and state that
Phase 2
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md))
is the next step once the gate is met.
3. **Phase 2 - Design messaging** ([phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md)).
**Gate**: per-replica flow control derived from the database pool;
dead-letter topic paired with its own pull subscription and both Pub/Sub
service-agent IAM bindings; Cloud Storage claim-check decision for any
payload that can exceed 1 MB (Pub/Sub hard limit: 10 MB).
4. **Phase 3 - Build consumers** ([phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md)).
**Gate**: unit tests for every branch of the ack/nack/quarantine matrix;
shutdown test proving the database pool closes strictly after `Receive`
returns and in-flight commits finish; GKE HPA `maxReplicas` or Cloud Run
concurrency capped within the database connection budget.
5. **Phase 4 - Observe** ([phase4-distributed-tracing.md](references/phase4-distributed-tracing.md)).
**Gate**: one continuous trace ID from producer request through Pub/Sub to
consumer database stages, structured logs correlated via
`logging.googleapis.com/trace`, explicit sampling policy per environment.
6. **Phase 5 - Cut over incrementally**: Strangler pattern per event type.
Dual-run (synchronous path plus event) behind `{feature_flag}` so a single
flip restores the synchronous call, compare outcomes, and remove the
synchronous call only after `{dlq_subscription_id}` stays empty for
`{soak_period}` (default: one full business cycle, at least 7 days).
7. **Validate → fix → repeat**: re-verify all phase gates post-cut-over using
[solution-checklist.md](references/solution-checklist.md).
## Cross-cutting rules and scope boundaries
- **One default, one escape hatch per decision**: every phase names one
default and one escape hatch; do not add a third option.
- **Idempotency is non-negotiable**: Pub/Sub delivers at least once. Every
consumer deduplicates on an event ID or natural key before side effects and
**acks** duplicates (nacking duplicates loops valid data into the DLQ).
- **Budgets flow downstream**: database connection budget → per-replica pool
→ `MaxOutstandingMessages` → HPA `maxReplicas`. Enforce the invariant
`per_replica_pool * max_replicas <= database_connection_budget` (derive
whichever of the three values is unknown, tie HPA `maxReplicas` to that
budget, never leave client flow-control defaults of 1000 messages / 1 GiB
in place, and derive per-replica flow control with Phase 2
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md))
and the HPA manifest with Phase 3
([references/phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md))).
- **Never leave a dead-letter topic without a subscription**: it silently
discards messages; alert on `subscription/dead_letter_message_count`.
- **Other brokers (Kafka, RabbitMQ, SQS, self-managed queues)**: state
plainly that this skill is specific to Google Cloud Pub/Sub, offer only
broker-agnostic principles explicitly labeled as such (or redirect to
broker-specific docs), never present Pub/Sub flags, flow-control settings,
or fabricated `gcloud` commands as Kafka config, and never suggest
migrating to Pub/Sub as the answer to a Kafka tuning question.
- **Synchronous HTTP/gRPC-only services (no Pub/Sub)**: load only Phase 4
(`TracerProvider` + Cloud Run `WithRemoteParentNotSampled` sampler,
`otelhttp`, `otelgrpc` stats handlers, DB stage spans, `slog` correlation);
never introduce Pub/Sub topics or message carriers.
- **Querying existing traces** (*"find traces slower than 2s"*): state that
this is a Cloud Trace query task rather than instrumentation; point to the
Cloud Trace console/API
(https://docs.cloud.google.com/trace/docs/finding-traces.md.txt) or the
`cloud-trace-querying` skill. Never emit OpenTelemetry SDK setup code,
never require re-instrumenting first, and never invent a trace query DSL.
- **Orchestration engines & sagas**: Workflows, Managed Service for Apache
Airflow (`managed-airflow-*`), Application Integration
(`application-integration-basics`), and multi-service compensating sagas
are out of scope; keep each aggregate's state change in one transaction.
## Validation checklist
- [ ] Producer and consumer deploy, scale, and fail independently: with the
consumer stopped, producer p99 is unchanged, `num_undelivered_messages`
grows, and the backlog drains on restart with matching row counts.
- [ ] No dual writes: a fault injected between commit and publish is
recovered by the outbox relay or sweeper with zero duplicate side effects.
- [ ] A malformed message lands in `{dlq_subscription_id}` after
`max-delivery-attempts` (or in quarantine when chosen) while healthy
messages keep flowing (`subscription/dead_letter_message_count` > 0).
- [ ] Rolling consumer restarts under load produce zero `context canceled`
commits and zero duplicate side effects.
- [ ] One trace ID links producer request, Pub/Sub hop, consumer processing,
and database stages, with `logging.googleapis.com/trace` on log lines.
- [ ] Every acceptance criterion names an observable signal (metric, log
field, row count, or test assertion), never a qualitative claim like
*"services are decoupled"*.
## Resource cleanup
Remove **only temporary test or dual-run resources** in a non-production
project. Before running or proposing any delete command after a migration,
explicitly ask the user to confirm the exact test resource names and
`{test_project_id}`, distinguish test/dual-run resources from live production
topics and subscriptions, and **never** delete production resources carrying
live traffic:
```bash
gcloud pubsub subscriptions delete {test_subscription_id} --project={test_project_id}
gcloud pubsub topics delete {test_topic_id} --project={test_project_id}
```
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-solution-event-driven-decoupling)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:google-cloud-solution-event-driven-decoupling)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-solution-event-driven-decoupling)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
phase1-coupling-assessment.md 9.9 KB
# Phase 1: Synchronous coupling assessment and transaction boundaries
- [1. Coupling diagnostic matrix](#1-coupling-diagnostic-matrix): Lines 19-30
- [2. Transaction boundary rules](#2-transaction-boundary-rules): Lines 31-66
- [3. Locate and measure chokepoints first](#3-locate-and-measure-chokepoints-first): Lines 67-88
- [4. Assessment workflow and Phase 1 checklist](#4-assessment-workflow-and-phase-1-checklist): Lines 89-137
Assess synchronous execution chains and draw transactional and failure-domain
boundaries **before** introducing asynchronous messaging. The output of Phase 1
is a decoupling design (measured baseline, call graph, transaction cut, outbox
or state-marker decision, event catalog, bulkhead plan) that Phase 2
(`references/phase2-pubsub-topology-and-sizing.md`) and Phase 3
(`references/phase3-consumer-and-autoscaling.md`) then implement.
Database diagnostics identity: use a database role scoped to the tables the
service owns plus the `pg_monitor` role for PostgreSQL lock/activity queries;
never use a shared admin login.
## 1. Coupling diagnostic matrix
Audit every hop of the synchronous request, batch loader, or stored-procedure
pipeline against four coupling dimensions:
| Coupling dimension | Symptom in code or architecture | Failure mode under load | Target decoupling pattern |
| --- | --- | --- | --- |
| **Temporal coupling** | Caller blocks until a downstream service, database job, or third-party API finishes. | Downstream slowness becomes upstream timeouts and cascading outages. | Durable asynchronous buffer (Pub/Sub topic with at-least-once delivery). |
| **Transactional dual write** | Code commits a database transaction and then publishes a message, or publishes inside the transaction. | Crash between commit and publish loses the event; rollback after publish emits a phantom event. | **Default:** Transactional Outbox table written in the same transaction. **Escape hatch:** post-commit idempotent publish plus a reconciliation sweeper. |
| **External reference coupling** | Hot-path transaction performs remote calls or unindexed cross-domain lookups per row. | Connection-pool exhaustion and long lock hold times. | **Default:** bounded TTL cache hydrated outside the transaction. **Escape hatch:** one batched `WHERE key IN (...)` read before the write transaction. |
| **Layer leakage** | Domain or use-case code imports messaging or database SDKs directly. | Business rules cannot be unit-tested without emulators. | Ports and adapters: domain depends on interfaces; SDKs live in adapters. |
## 2. Transaction boundary rules
Apply these rules when splitting a monolithic procedure into an atomic write
plus asynchronous events:
1. **Never perform network calls (HTTP, gRPC, broker publish) inside an open
database transaction.** *Why:* a network stall holds row locks and pins a
pooled connection, creating lock convoys and exhausting the pool.
2. **Keep the state transition of a single aggregate in one transaction.**
*Why:* splitting invariant-bearing tables across several local
transactions without a saga leaves partial writes when a step fails.
3. **Resolve read-only reference data before opening the transaction.**
*Why:* tax rates, reference attributes, or configuration change rarely;
pre-fetching shrinks the transaction to pure DML. *Caveat:* if a
reference value must be consistent with the write, store the value or
its version in the row and validate it inside the transaction
(optimistic check) instead of re-reading remotely.
4. **Eliminate dual writes deterministically**:
- **Default (Transactional Outbox):** insert the domain event (payload
**and** attributes such as `event_type` and `traceparent`) into an
`outbox_events` table in the same transaction as the business tables,
then relay it to Pub/Sub asynchronously with claim-then-publish so no
lock is held during the publish.
- **Escape hatch (post-commit publish + reconciler):** when schema
changes are frozen, persist a status column (for example
`publish_status = 'PENDING'`) on the aggregate's existing root table
inside the transaction, publish immediately after commit with a
deterministic event ID (never failing the caller's request if the
post-commit publish fails, because the business row is already
committed), mark `PUBLISHED`, and run a periodic sweeper for stale
`PENDING` rows.
See `references/phase1-outbox-and-bulkheads-go.md` for port definitions, a
tested Go Transactional Outbox repository and relay, the post-commit variant,
cache pre-fetch, bulkhead sizing, and PostgreSQL / MySQL DDL and sweeper SQL.
## 3. Locate and measure chokepoints first
Decouple what has been measured, not what feels slow. When a user asks which
steps of a slow endpoint to move to Pub/Sub without providing measurements,
**do not propose moving specific steps to Pub/Sub yet**; first ask for or
collect per-hop latency from Cloud Trace and a connection/lock signal from the
table below, and instruct them to record those baseline numbers in the design
document so the post-cut comparison is objective:
| Signal | Where | What it reveals |
| --- | --- | --- |
| Critical path and per-hop latency (p50/p99) | Cloud Trace: filter the entry span, sort by latency, open the waterfall (https://docs.cloud.google.com/trace/docs/finding-traces.md.txt) | Which downstream call dominates the request and whether it runs inside the transaction span |
| Fan-out count per request | Cloud Trace span counts per trace | N+1 lookups that belong in a batched pre-fetch |
| Request latency and instance count per revision (Cloud Run) | Cloud Monitoring: `run.googleapis.com/request_latencies`, `run.googleapis.com/container/instance_count` (https://docs.cloud.google.com/run/docs/monitoring.md.txt) | Whether latency grows with instance count (downstream-bound) or not (CPU-bound) |
| Connection-pool saturation | Cloud SQL for PostgreSQL: `cloudsql.googleapis.com/database/postgresql/num_backends` against the `max_connections` flag, and `num_backends_by_state` filtered to `state="idle_in_transaction"`; MySQL / SQL Server: `cloudsql.googleapis.com/database/network/connections`; otherwise the pool's own gauge (Go `sql.DB.Stats().WaitCount`) | Transactions left open while the application waits on something else, the symptom of locks held across network calls |
| Lock waits and long transactions | PostgreSQL: `SELECT pid, state, wait_event_type, wait_event, now() - xact_start AS tx_age, query FROM pg_stat_activity WHERE state = 'idle in transaction' OR cardinality(pg_blocking_pids(pid)) > 0;` plus Cloud SQL Query Insights lock-wait load (https://docs.cloud.google.com/sql/docs/postgres/using-query-insights.md.txt) | Which sessions hold locks while blocked, and on what |
| CPU hot spots inside the hop | Cloud Profiler (https://docs.cloud.google.com/profiler/docs/about-profiler.md.txt) | Whether the hop is slow because of compute or because of waiting |
If the service is not yet traced, apply Phase 4
(`references/phase4-distributed-tracing.md`) first; to query existing traces use
the `cloud-trace-querying` skill.
## 4. Assessment workflow and Phase 1 checklist
1. **Trace the call graph**: list every synchronous hop from the entry
adapter (HTTP handler, file loader, message consumer) through validation,
reference lookups, writes, and outbound notifications. Record owner,
measured latency, and failure behavior per hop (or outline a candidate call
graph and ask the user to confirm missing hops when assessing conceptual
domain boundaries).
2. **Measure lock and connection residency**: using the signals above, flag
every remote call, cross-schema join, or secondary process (for example a
nightly rollup) executed while a transaction is open.
3. **Draw the transaction cut**:
- Move read-only lookups **before** the transaction behind a read port
with caching or batching.
- Keep atomic business writes plus the outbox row or state marker
**inside** the transaction.
- Move notifications, analytics fan-out, and heavy rollups **after**
commit as asynchronous events.
4. **Isolate failure domains (bulkheads)**: give real-time and bulk/batch
flows separate connection budgets, worker pools, or subscriptions so a
batch spike never starves interactive traffic.
5. **Name the events and owners**: for each post-commit step define (or, for
conceptual flow assessments without a slow-endpoint incident, propose
concrete candidate values for) the event name
(`{domain}.{entity}.{past_tense_verb}`, for example
`orders.order.created`), deterministic idempotency key (for example
`order_id`), consumers, and `{owning_team}` placeholder.
6. **Validate → fix → repeat**: verify every item below before proceeding to
Phase 2 (`references/phase2-pubsub-topology-and-sizing.md`):
- [ ] No HTTP, gRPC, or Pub/Sub publish call executes between transaction
begin and commit.
- [ ] Every outbound event is produced through a Transactional Outbox or
an existing-table state marker with an idempotent sweeper.
- [ ] Read-only reference lookups use a bounded cache or a single batched
pre-transaction query, not per-row queries inside the transaction.
- [ ] Domain and use-case packages depend only on interfaces (no
messaging or database SDK imports).
- [ ] Real-time and batch flows have independent concurrency budgets.
- [ ] Each event has a documented name, idempotency key, and owning team.
- [ ] Baseline p99 latency, connection saturation, and lock-wait numbers
are recorded for each hop that will be decoupled.
If prototype topics or subscriptions were created in a sandbox project during
assessment, delete only those sandbox resources after confirmation:
```bash
gcloud pubsub subscriptions delete {sandbox_subscription_id} --project={sandbox_project_id}
gcloud pubsub topics delete {sandbox_topic_id} --project={sandbox_project_id}
```
phase1-outbox-and-bulkheads-go.md 19.5 KB
# Outbox, post-commit, and bulkhead patterns (Go reference)
- [1. Ports that keep the domain SDK-free](#1-ports-that-keep-the-domain-sdk-free): Lines 18-69
- [2. Default: Transactional Outbox in one transaction](#2-default-transactional-outbox-in-one-transaction): Lines 70-162
- [3. Outbox relay (poller)](#3-outbox-relay-poller): Lines 163-344
- [4. Escape hatch: post-commit publish with state marker](#4-escape-hatch-post-commit-publish-with-state-marker): Lines 345-427
- [5. Reference-data pre-fetch and bulkheads](#5-reference-data-pre-fetch-and-bulkheads): Lines 428-494
- [6. Schema and sweeper SQL](#6-schema-and-sweeper-sql): Lines 495-539
The Go blocks headed `// file:` are compiled and unit-tested by the authors
(`database/sql` + sqlmock, `go test -race`). The SQL is PostgreSQL 13+
(`ON CONFLICT`, `UPDATE ... RETURNING`, `FOR UPDATE SKIP LOCKED`, `JSONB`,
`make_interval`). For MySQL 8+ use `INSERT IGNORE`, split the claim into
`SELECT ... FOR UPDATE SKIP LOCKED` + `UPDATE`, and use `JSON`/`BLOB`/`?`
placeholders; other engines need their own `SKIP LOCKED` equivalent. Event
names follow `{domain}.{entity}.{past_tense_verb}`, for example
`orders.order.created`. Replace `LedgerEntry` with the real aggregate.
## 1. Ports that keep the domain SDK-free
Keep domain and use-case packages free of `cloud.google.com/go/pubsub/v2` and
database drivers. Only adapters import SDKs; pin them in `go.mod`
(`go get cloud.google.com/go/pubsub/v2@v2.8.0` or later).
The Pub/Sub adapter behind `EventPublisher` must block on the publish result:
```go
res := publisher.Publish(ctx, &pubsub.Message{Data: ev.Payload, Attributes: ev.Attributes, OrderingKey: orderingKey})
_, err := res.Get(ctx) // the client publishes asynchronously; return only after the broker acked
return err
```
```go
// file: outbox/port.go
package outbox
import "context"
// OutboundEvent is the integration event persisted next to the business
// write and relayed to Pub/Sub after commit.
type OutboundEvent struct {
ID string // Deterministic idempotency key (for example a UUIDv5 of the aggregate ID + version).
AggregateID string // Business entity the event belongs to.
Type string // Event name, e.g. "orders.order.created".
Payload []byte // Serialized body (JSON, Avro, Protobuf).
Attributes map[string]string // Routing attributes (event_type, schema_version, traceparent).
}
// LedgerEntry is a minimal example aggregate; replace with the real domain type.
type LedgerEntry struct {
ID string
AmountCents int64
Status string
}
// ReferenceDataReader resolves read-only reference data outside the write transaction.
type ReferenceDataReader interface {
Resolve(ctx context.Context, codes []string) (map[string]string, error)
}
// TransactionStore persists the business record and the outbound event atomically.
type TransactionStore interface {
SaveWithOutbox(ctx context.Context, entry *LedgerEntry, ev OutboundEvent) error
}
// EventPublisher emits events from a secondary adapter after commit.
type EventPublisher interface {
Publish(ctx context.Context, ev OutboundEvent) error
}
```
## 2. Default: Transactional Outbox in one transaction
The business row and the outbox row commit or roll back together. The
`ON CONFLICT ... DO NOTHING` guard makes redelivered commands idempotent and
surfaces `ErrDuplicate` so the caller acknowledges the triggering message.
```go
// file: outbox/repository.go
package outbox
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
)
// ErrDuplicate is returned when the natural key already exists; callers ACK
// the triggering message instead of retrying.
var ErrDuplicate = errors.New("outbox: duplicate aggregate")
// Repository implements TransactionStore with the Transactional Outbox pattern.
// SQL is PostgreSQL (placeholders $1, ON CONFLICT, ::jsonb); see the reference for
// the MySQL adaptations.
type Repository struct {
db *sql.DB
}
func NewRepository(db *sql.DB) *Repository { return &Repository{db: db} }
// aggregateID prefers the event's explicit AggregateID and falls back to the
// entry ID so there is a single source of truth for the business key.
func aggregateID(ev OutboundEvent, entry *LedgerEntry) string {
if ev.AggregateID != "" {
return ev.AggregateID
}
return entry.ID
}
// SaveWithOutbox writes the business row and the outbox row in ONE transaction.
// No network call happens between BeginTx and Commit.
func (r *Repository) SaveWithOutbox(ctx context.Context, entry *LedgerEntry, ev OutboundEvent) (err error) {
tx, err := r.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() {
if err != nil {
_ = tx.Rollback()
}
}()
res, err := tx.ExecContext(ctx,
`INSERT INTO ledger_entries (entry_id, amount_cents, status)
VALUES ($1, $2, $3)
ON CONFLICT (entry_id) DO NOTHING`,
entry.ID, entry.AmountCents, entry.Status,
)
if err != nil {
return fmt.Errorf("insert ledger entry: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if n == 0 {
// Idempotent redelivery: the aggregate (and its outbox row) already exist.
err = ErrDuplicate
return err
}
// Attributes (event_type, schema_version, traceparent) travel with the row so
// the relay can set them on the Pub/Sub message: subscription filters and
// trace propagation only work through attributes.
attrs, err := json.Marshal(ev.Attributes)
if err != nil {
return fmt.Errorf("encode attributes: %w", err)
}
if _, err = tx.ExecContext(ctx,
`INSERT INTO outbox_events (event_id, aggregate_id, event_type, payload, attributes, status)
VALUES ($1, $2, $3, $4, $5::jsonb, 'PENDING')`,
ev.ID, aggregateID(ev, entry), ev.Type, ev.Payload, string(attrs),
); err != nil {
return fmt.Errorf("insert outbox event: %w", err)
}
if err = tx.Commit(); err != nil {
return fmt.Errorf("commit write+outbox: %w", err)
}
return nil
}
```
## 3. Outbox relay (poller)
A background relay (goroutine, sidecar, or Cloud Run job) **claims** a batch
in a short transaction (`PENDING` → `CLAIMED`, `FOR UPDATE SKIP LOCKED` so
replicas do not collide), commits, publishes each event with a bounded
timeout **outside** any transaction, and marks rows `PUBLISHED`. No row lock
is ever held across a network call. Rows left `CLAIMED` by a crash or
timeout are requeued by `ResetStaleClaims`; consumers deduplicate on
`event_id` because a republish is possible. Attributes persisted with the
row (`event_type`, `schema_version`, `traceparent`) are restored onto the
message so subscription filters and trace propagation keep working. Rows
that fail `maxAttempts` times are parked as `FAILED` so a poison event never
blocks its batch forever, and `PurgePublished` keeps the table bounded.
Ordering: with several relay replicas and `SKIP LOCKED`, two events of one
aggregate can be published out of order. If consumers need per-aggregate
order, set `OrderingKey = AggregateID` and run one relay replica (or claim
with `DISTINCT ON (aggregate_id)`); otherwise document that consumers must
tolerate reordering.
```go
// file: outbox/relay.go
package outbox
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
)
// Relay publishes outbox rows with a claim-then-publish protocol so no row
// lock is ever held across a network call:
//
// 1. short transaction: claim up to batchSize PENDING rows (status=CLAIMED,
// FOR UPDATE SKIP LOCKED so replicas do not fight) and commit;
// 2. publish each claimed event with a bounded timeout, outside any
// transaction;
// 3. mark each successfully published row PUBLISHED (autocommit).
//
// A crash or publish failure leaves rows CLAIMED; ResetStaleClaims returns them
// to PENDING (or parks them as FAILED after maxAttempts) so the next drain
// republishes them. Consumers therefore MAY see a duplicate and must
// deduplicate on event_id (at-least-once end to end). The outbox is a queue, not
// a ledger: PurgePublished deletes old PUBLISHED rows.
type Relay struct {
db *sql.DB
publisher EventPublisher
batchSize int
publishTimeout time.Duration
maxAttempts int
}
// NewRelay builds a relay. batchSize defaults to 100, publishTimeout to 10s and
// maxAttempts to 10; rows that exceed maxAttempts are parked as FAILED so a
// poison event cannot block its batch forever.
func NewRelay(db *sql.DB, p EventPublisher, batchSize int, publishTimeout time.Duration) *Relay {
if batchSize <= 0 {
batchSize = 100
}
if publishTimeout <= 0 {
publishTimeout = 10 * time.Second
}
return &Relay{db: db, publisher: p, batchSize: batchSize, publishTimeout: publishTimeout, maxAttempts: 10}
}
// WithMaxAttempts overrides the poison threshold (must be >= 1).
func (r *Relay) WithMaxAttempts(n int) *Relay {
if n >= 1 {
r.maxAttempts = n
}
return r
}
// DrainOnce claims and publishes one batch. It returns how many events were
// durably marked PUBLISHED, even when a later event in the batch failed.
func (r *Relay) DrainOnce(ctx context.Context) (published int, err error) {
batch, err := r.claim(ctx)
if err != nil {
return 0, err
}
for _, ev := range batch {
pubCtx, cancel := context.WithTimeout(ctx, r.publishTimeout)
pubErr := r.publisher.Publish(pubCtx, ev)
cancel()
if pubErr != nil {
// Row stays CLAIMED; ResetStaleClaims will requeue it.
return published, fmt.Errorf("publish %s: %w", ev.ID, pubErr)
}
if _, err = r.db.ExecContext(ctx,
`UPDATE outbox_events SET status = 'PUBLISHED', published_at = NOW() WHERE event_id = $1`,
ev.ID); err != nil {
return published, fmt.Errorf("mark published %s: %w", ev.ID, err)
}
published++
}
return published, nil
}
func (r *Relay) claim(ctx context.Context) (batch []OutboundEvent, err error) {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin claim tx: %w", err)
}
defer func() {
if err != nil {
_ = tx.Rollback()
}
}()
rows, err := tx.QueryContext(ctx,
`UPDATE outbox_events
SET status = 'CLAIMED', claimed_at = NOW(), attempts = attempts + 1
WHERE event_id IN (
SELECT event_id FROM outbox_events
WHERE status = 'PENDING' AND attempts < $2
ORDER BY created_at
LIMIT $1
FOR UPDATE SKIP LOCKED)
RETURNING event_id, aggregate_id, event_type, payload, attributes`, r.batchSize, r.maxAttempts)
if err != nil {
return nil, fmt.Errorf("claim pending rows: %w", err)
}
defer rows.Close()
for rows.Next() {
var ev OutboundEvent
var attrs []byte
if err = rows.Scan(&ev.ID, &ev.AggregateID, &ev.Type, &ev.Payload, &attrs); err != nil {
return nil, fmt.Errorf("scan outbox row: %w", err)
}
if len(attrs) > 0 {
if err = json.Unmarshal(attrs, &ev.Attributes); err != nil {
return nil, fmt.Errorf("decode attributes for %s: %w", ev.ID, err)
}
}
if ev.Attributes == nil {
ev.Attributes = map[string]string{}
}
// Subscription filters only see attributes, so the event type MUST be
// an attribute even if it is also inside the payload.
ev.Attributes["event_type"] = ev.Type
batch = append(batch, ev)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("iterate claimed rows: %w", err)
}
if err = tx.Commit(); err != nil {
return nil, fmt.Errorf("commit claim: %w", err)
}
return batch, nil
}
// ResetStaleClaims requeues rows claimed longer than olderThan ago (a relay
// crashed or a publish timed out) and parks rows that already reached
// maxAttempts as FAILED for manual inspection. Run it periodically alongside
// DrainOnce with olderThan > batchSize * publishTimeout.
func (r *Relay) ResetStaleClaims(ctx context.Context, olderThan time.Duration) (int64, error) {
res, err := r.db.ExecContext(ctx,
`UPDATE outbox_events
SET status = CASE WHEN attempts >= $2 THEN 'FAILED' ELSE 'PENDING' END,
claimed_at = NULL
WHERE status = 'CLAIMED' AND claimed_at < NOW() - make_interval(secs => $1)`,
olderThan.Seconds(), r.maxAttempts)
if err != nil {
return 0, fmt.Errorf("reset stale claims: %w", err)
}
return res.RowsAffected()
}
// PurgePublished deletes PUBLISHED rows older than retention. Schedule it daily
// so the outbox table does not grow without bound.
func (r *Relay) PurgePublished(ctx context.Context, retention time.Duration) (int64, error) {
res, err := r.db.ExecContext(ctx,
`DELETE FROM outbox_events
WHERE status = 'PUBLISHED' AND published_at < NOW() - make_interval(secs => $1)`,
retention.Seconds())
if err != nil {
return 0, fmt.Errorf("purge published: %w", err)
}
return res.RowsAffected()
}
```
## 4. Escape hatch: post-commit publish with state marker
When database governance forbids a new table, mark the existing header row
`publish_status = 'PENDING'` inside the transaction, publish right after
commit, and let a sweeper republish stale rows. The publish context is
detached from the caller's cancellation (`context.WithoutCancel`, Go 1.21+)
but bounded by `PublishTimeout`.
```go
// file: outbox/postcommit.go
package outbox
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
)
// AtomicStore is the escape-hatch port: the write marks the row
// publish_status = 'PENDING' inside the transaction and returns the event to
// publish. On a duplicate natural key it must return the SAME deterministic
// event with ErrDuplicate so the caller can still publish idempotently.
type AtomicStore interface {
SaveAtomic(ctx context.Context, entry *LedgerEntry, refs map[string]string) (OutboundEvent, error)
// MarkPublished flips publish_status to PUBLISHED after a successful publish so
// the sweeper does not republish the row.
MarkPublished(ctx context.Context, eventID string) error
}
// PostCommitUseCase implements "post-commit publish + reconciler" when adding
// an outbox table is not possible.
type PostCommitUseCase struct {
ReferenceData ReferenceDataReader
Store AtomicStore
Publisher EventPublisher
Logger *slog.Logger
PublishTimeout time.Duration
}
func (uc *PostCommitUseCase) Execute(ctx context.Context, entry *LedgerEntry, refCodes []string) error {
publishTimeout := uc.PublishTimeout
if publishTimeout <= 0 {
publishTimeout = 10 * time.Second // a zero timeout would expire immediately and defer every publish
}
logger := uc.Logger
if logger == nil {
logger = slog.Default()
}
// Step 1: resolve read-only reference data BEFORE any write transaction.
refs, err := uc.ReferenceData.Resolve(ctx, refCodes)
if err != nil {
return fmt.Errorf("resolve reference data: %w", err)
}
// Step 2: atomic write with a PENDING marker; zero network calls inside.
ev, err := uc.Store.SaveAtomic(ctx, entry, refs)
if err != nil && !errors.Is(err, ErrDuplicate) {
return fmt.Errorf("save atomic: %w", err)
}
// Step 3: best-effort publish AFTER commit, detached from caller cancellation
// so a shutdown mid-flight does not abort the publish, but bounded in time.
pubCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), publishTimeout)
defer cancel()
if pubErr := uc.Publisher.Publish(pubCtx, ev); pubErr != nil {
// Do NOT fail the request: the row is committed. The sweeper republishes
// stale PENDING rows; the deterministic event ID keeps consumers idempotent.
logger.WarnContext(ctx, "post-commit publish deferred to sweeper",
"event_id", ev.ID, "error", pubErr)
return nil
}
// Step 4: mark the row PUBLISHED. If this fails the row stays PENDING and the
// sweeper republishes the same deterministic event; consumers deduplicate.
if markErr := uc.Store.MarkPublished(pubCtx, ev.ID); markErr != nil {
logger.WarnContext(ctx, "mark published failed; sweeper will reconcile",
"event_id", ev.ID, "error", markErr)
}
return nil
}
```
## 5. Reference-data pre-fetch and bulkheads
1. **Hybrid cache plus batch fallback**:
- Small, slow-changing tables (under ~10,000 rows: tax codes, regions,
currencies) live in an in-memory snapshot refreshed by a background
ticker (`atomic.Pointer[Snapshot]`).
- High-cardinality reference sets (millions of entity or account IDs)
are resolved with one parameterized `WHERE id IN (...)` query per
request, deduplicated, executed **before** the write transaction with a
short read timeout.
2. **Workload bulkheads**: give real-time and batch flows separate concurrency
budgets whose sum stays below `db.SetMaxOpenConns`, so a burst of large
batch files cannot starve interactive traffic or cause ack-deadline
expirations.
```go
// file: outbox/bulkhead.go
package outbox
import "context"
// Bulkhead bounds concurrency for one workload class. Create one per class
// (for example realtime and batch) so a batch burst cannot consume the whole
// database pool. Size them so the sum stays below db.SetMaxOpenConns.
type Bulkhead struct{ slots chan struct{} }
func NewBulkhead(size int) *Bulkhead {
if size < 1 {
size = 1
}
return &Bulkhead{slots: make(chan struct{}, size)}
}
// Acquire blocks until a slot is free or ctx is done. Call the returned
// release function exactly once.
func (b *Bulkhead) Acquire(ctx context.Context) (release func(), err error) {
select {
case b.slots <- struct{}{}:
return func() { <-b.slots }, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// SplitPool returns realtime and batch sizes for a pool of maxOpenConns,
// reserving realtimeShare (0..1) for interactive traffic. This split is a
// different knob from the "max outstanding messages <= 80% of the pool"
// flow-control rule; tune them independently.
func SplitPool(maxOpenConns int, realtimeShare float64) (realtime, batch int) {
if maxOpenConns < 2 {
return 1, 1
}
if realtimeShare <= 0 || realtimeShare >= 1 {
realtimeShare = 0.8
}
realtime = int(float64(maxOpenConns) * realtimeShare)
if realtime < 1 {
realtime = 1
}
batch = maxOpenConns - realtime
if batch < 1 {
batch = 1
realtime = maxOpenConns - 1
}
return realtime, batch
}
```
## 6. Schema and sweeper SQL
```sql
CREATE TABLE outbox_events (
event_id TEXT PRIMARY KEY, -- deterministic idempotency key
aggregate_id TEXT NOT NULL,
event_type TEXT NOT NULL, -- e.g. orders.order.created
payload BYTEA NOT NULL,
attributes JSONB NOT NULL DEFAULT '{}'::jsonb, -- event_type, schema_version, traceparent
status TEXT NOT NULL DEFAULT 'PENDING', -- PENDING | CLAIMED | PUBLISHED | FAILED
attempts INT NOT NULL DEFAULT 0, -- poison guard, see Relay.maxAttempts
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
claimed_at TIMESTAMPTZ,
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_events_pending_idx
ON outbox_events (created_at) WHERE status = 'PENDING';
CREATE INDEX outbox_events_claimed_idx
ON outbox_events (claimed_at) WHERE status = 'CLAIMED';
```
Schedule `ResetStaleClaims(ctx, window)` next to `DrainOnce` with
`window > batchSize * publishTimeout` (default 100 × 10 s, so lower
`batchSize` or raise the window) so an in-progress batch is never requeued by
a peer, and `PurgePublished(ctx, 7*24*time.Hour)` daily. Alert on rows in
`FAILED` and on `PENDING` rows older than the window.
Sweeper for the escape hatch (run every 1-5 minutes; claim, republish, mark):
```sql
SELECT aggregate_id, event_id
FROM {aggregate_table}
WHERE publish_status = 'PENDING'
AND updated_at < NOW() - INTERVAL '2 minutes'
ORDER BY updated_at
LIMIT 500
FOR UPDATE SKIP LOCKED;
-- after each successful publish:
UPDATE {aggregate_table} SET publish_status = 'PUBLISHED' WHERE aggregate_id = $1;
```
Keep `event_id` deterministic (for example
`uuid5(namespace, aggregate_id || version)`) so a sweeper republish after a
crash produces the same message the consumer already deduplicated.
phase2-pubsub-topology-and-sizing.md 18.2 KB
# Phase 2: Pub/Sub topic and subscription design
- [1. Client SDKs, DLQ, and claim-check IAM](#1-client-sdks-dlq-and-claim-check-iam): Lines 27-53
- [2. Topology and 10 MB payload decision matrix](#2-topology-and-10-mb-payload-decision-matrix): Lines 54-66
- [3. Subscription and flow-control sizing rules](#3-subscription-and-flow-control-sizing-rules): Lines 67-96
- [4. Go `ReceiveSettings` derived from the database pool](#4-go-receivesettings-derived-from-the-database-pool): Lines 97-232
- [5. Provisioning: dead-letter topic, filtered subscription, backoff, IAM](#5-provisioning-dead-letter-topic-filtered-subscription-backoff-iam): Lines 233-284
- [6. Cloud Storage claim-check for large payloads](#6-cloud-storage-claim-check-for-large-payloads): Lines 285-311
- [7. Monitoring metrics, Phase 2 checklist, and test cleanup](#7-monitoring-metrics-phase-2-checklist-and-test-cleanup): Lines 312-342
Grounding documentation:
- Overview: https://docs.cloud.google.com/pubsub/docs/overview.md.txt
- Pull subscriptions and flow control: https://docs.cloud.google.com/pubsub/docs/pull.md.txt
- Dead-letter topics: https://docs.cloud.google.com/pubsub/docs/dead-letter-topics.md.txt
- Subscription filters: https://docs.cloud.google.com/pubsub/docs/subscription-message-filter.md.txt
- Pub/Sub quotas and limits (10 MB message size): https://docs.cloud.google.com/pubsub/quotas.md.txt
Architect topic topology, dead-letter handling, retry backoff, and consumer
flow control so bursts never starve the downstream database and poison
messages are never dropped silently. If the user claims an assessment is done
and asks for `gcloud` creation commands while only naming events, enforce the
Phase 1 gate first (idempotency key, owner, outbox or state-marker decision,
and measured baseline) and withhold topic or subscription creation commands
until that gate is met.
## 1. Client SDKs, DLQ, and claim-check IAM
Pin the client library: Go `go get cloud.google.com/go/pubsub/v2@latest`
(v2.x), Python `pip install "google-cloud-pubsub>=2,<3"`, Java
`com.google.cloud:google-cloud-pubsub` managed by
`com.google.cloud:libraries-bom:{bom_version}`, Node.js
`npm install @google-cloud/pubsub@latest`. Pub/Sub topics are global; region
matters only for locational endpoints (ordering, exactly-once). Enable
`pubsub.googleapis.com` (and `storage.googleapis.com` for claim-check). Flag
every IAM binding for human approval:
| Principal | Role | Scope |
| --- | --- | --- |
| Producer service account | `roles/pubsub.publisher` | `{topic_id}` |
| Producer service account (claim-check) | `roles/storage.objectCreator` | `{claim_check_bucket}` |
| Consumer service account | `roles/pubsub.subscriber` | `{subscription_id}` |
| Consumer service account (claim-check) | `roles/storage.objectViewer` | `{claim_check_bucket}` |
| Pub/Sub service agent `service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com` | `roles/pubsub.publisher` | `{dlq_topic_id}` |
| Pub/Sub service agent `service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com` | `roles/pubsub.subscriber` | `{subscription_id}` |
| Cloud Storage service agent `service-{project_number}@gs-project-accounts.iam.gserviceaccount.com` (claim-check) | `roles/pubsub.publisher` | `{batch_topic_id}` |
*Why the Pub/Sub service agent needs both roles:* without
`roles/pubsub.publisher` on `{dlq_topic_id}` **and** `roles/pubsub.subscriber`
on `{subscription_id}`, Pub/Sub cannot forward exhausted messages to the
dead-letter topic and keeps redelivering them forever until message retention
(default 7 days) expires and the message is lost.
## 2. Topology and 10 MB payload decision matrix
Pub/Sub enforces a **10 MB maximum message data size** (and 10 MB per publish
request; attributes are capped separately at 100 per message). Pick one
default per workload shape:
| Workload shape | Default | Escape hatch | Rationale |
| --- | --- | --- | --- |
| Related lifecycle events of one domain (`orders.order.created`, `orders.order.cancelled`) | One domain topic plus **subscription filters** (`--message-filter='attributes.event_type="orders.order.created"'`, or `hasPrefix(attributes.event_type, "orders.")`) | Dedicated topic per event when schemas, retention, or owning teams diverge, or when filters are expected to change (a filter is immutable after creation and limited to 256 bytes; changing it means recreating the subscription) | Filtering avoids delivering and nacking events a consumer never wanted; non-matching messages are acknowledged automatically. |
| Large files or documents (over ~1 MB, or variable 1:N batches) | **Claim-check**: upload to Cloud Storage, publish an `OBJECT_FINALIZE` notification or a small pointer message (bucket, object, generation) | Compressed or chunked direct messages only when well under the 10 MB limit (headroom for attributes and growth) and object storage is prohibited | Multi-megabyte messages exhaust the byte flow-control budget, cause out-of-memory kills, and fail above 10 MB. |
| Per-entity sequencing | **Idempotent consumer** tolerant of out-of-order delivery (version or natural-key check in the database); after the check, ack duplicates, since nacking them only causes more redelivery | **Ordering keys** (`ordering_key = "{entity_id}"`) with a regional endpoint; `--enable-message-ordering` cannot be changed after creation | Ordering serializes delivery per key, so one nacked or expired message redelivers every later outstanding message of that key until it is dead-lettered. |
| Exactly-once semantics required by the business | Idempotency key in the consumer's database (unique constraint) | Subscription `--enable-exactly-once-delivery` (pull/streaming pull only, same region; not available on push, BigQuery, or Cloud Storage subscriptions) | Database-level idempotency works for push, pull, and replays; exactly-once delivery still requires idempotent side effects. |
## 3. Subscription and flow-control sizing rules
Never leave client flow control at library defaults (Go: 1000 messages and
1 GB / `1e9` bytes; Python/Java/Node.js have similar large defaults) when the
consumer writes to a relational database:
| Parameter | Formula or default | Rationale |
| --- | --- | --- |
| Per-replica DB pool | `pool_max_open_conns = floor(total_db_connection_budget / max_replicas)` | Enforces `per_replica_pool * max_replicas <= database_connection_budget`. |
| Max outstanding messages (per replica) | `floor(pool_max_open_conns * 0.8)` (e.g. 25 for a pool of 32) | More in-flight callbacks than connections only queue inside the process, extend leases, and trigger duplicate redeliveries. |
| Max outstanding bytes (per replica) | `floor(container_memory_limit * 0.15)` (e.g. ~76 MiB on 512 MiB) | Prevents out-of-memory kills while draining a backlog of large payloads. |
| Client max lease extension (streaming pull) | `2 * per_message_timeout` (library defaults: 60 min) | Streaming-pull clients extend the lease automatically up to this cap; it, not the subscription ack deadline, is what must exceed the slowest legitimate commit. |
| Ack deadline (subscription) | `max(30s, ceil(2.5 * per_message_timeout))`, at most 600s (e.g. ~100s for a 40s timeout); set `per_message_timeout` at or above p99 processing time | Governs push and unary pull; slow commits beyond it are redelivered mid-flight. |
| Retry policy | `--min-retry-delay=10s --max-retry-delay=600s` (never use non-existent flags such as `--enable-delivery-ordering`) | Immediate retry (the default) creates thundering herds against a recovering database. |
| Dead-letter policy | `--max-delivery-attempts=5` (range 5–100) plus a pull subscription on `{dlq_topic_id}` with 7–31 days retention | Bounds poison amplification and keeps failed payloads inspectable. A dead-letter topic **without a subscription discards messages**. |
Client-library field names per language:
| Language | Max outstanding messages | Max outstanding bytes | Max lease extension |
| --- | --- | --- | --- |
| Go (`pubsub/v2`) | `sub.ReceiveSettings.MaxOutstandingMessages` | `sub.ReceiveSettings.MaxOutstandingBytes` | `ReceiveSettings.MaxExtension` |
| Python | `pubsub_v1.types.FlowControl(max_messages=...)` | `FlowControl(max_bytes=...)` | `FlowControl(max_lease_duration=...)` |
| Java | `FlowControlSettings.setMaxOutstandingElementCount` | `setMaxOutstandingRequestBytes` | `Subscriber.Builder.setMaxAckExtensionPeriod` |
| Node.js | `subscription.setOptions({flowControl: {maxMessages}})` | `flowControl: {maxBytes}` | `flowControl: {maxExtensionMinutes}` |
In Python and Java, flow control bounds leased messages only; size the
callback executor to the same budget (Python
`ThreadScheduler(ThreadPoolExecutor(max_workers={budget}))`, Java
`setExecutorProvider(FixedExecutorProvider.create(...))`).
## 4. Go `ReceiveSettings` derived from the database pool
The block headed `// file:` is compiled and unit-tested by the authors against
`cloud.google.com/go/pubsub/v2` v2.8.0 (`client.Subscriber(id)`; the v1
`client.Subscription(id)` API carries the same `ReceiveSettings` fields).
```go
// file: flowcontrol/receiver.go
package flowcontrol
import (
"context"
"fmt"
"time"
"cloud.google.com/go/pubsub/v2"
"google.golang.org/api/option"
)
// ReceiverConfig derives Pub/Sub flow-control limits from the resources the
// consumer actually has: database connections and memory. Leaving the SDK
// defaults (1000 messages / 1 GB) in place while writing to a relational
// database lets 1000 callbacks compete for a few dozen connections.
type ReceiverConfig struct {
ProjectID string
SubscriptionID string
DBMaxOpenConns int // Per-replica database pool size (db.SetMaxOpenConns).
MemoryLimitBytes int64 // Per-replica container memory limit.
PerMessageTimeout time.Duration
// Optional explicit overrides; zero means "derive".
MaxOutstandingMessages int
MaxOutstandingBytes int
MaxExtension time.Duration
NumGoroutines int
}
const (
dbShareNumerator = 4 // MaxOutstandingMessages <= 80% of the DB pool.
dbShareDenominator = 5
memorySharePercent = 15 // MaxOutstandingBytes <= 15% of container memory.
fallbackMessages = 20
fallbackBytes = 64 << 20
)
// Normalized returns a copy with every limit resolved and clamped.
func (c ReceiverConfig) Normalized() ReceiverConfig {
out := c
msgBudget := fallbackMessages
if out.DBMaxOpenConns > 0 {
if b := out.DBMaxOpenConns * dbShareNumerator / dbShareDenominator; b >= 1 {
msgBudget = b
} else {
msgBudget = 1
}
}
if out.MaxOutstandingMessages <= 0 || (out.DBMaxOpenConns > 0 && out.MaxOutstandingMessages > msgBudget) {
out.MaxOutstandingMessages = msgBudget
}
byteBudget := fallbackBytes
if out.MemoryLimitBytes > 0 {
if b := int(out.MemoryLimitBytes * memorySharePercent / 100); b >= 1<<20 {
byteBudget = b
}
}
if out.MaxOutstandingBytes <= 0 || (out.MemoryLimitBytes > 0 && out.MaxOutstandingBytes > byteBudget) {
out.MaxOutstandingBytes = byteBudget
}
if out.MaxExtension <= 0 {
// Keep extending the ack deadline for as long as a message may legitimately
// take, plus headroom, but never beyond the service maximum (600s is the
// longest single ack deadline; MaxExtension caps total lease time).
out.MaxExtension = 2 * time.Minute
if out.PerMessageTimeout > 0 {
out.MaxExtension = out.PerMessageTimeout * 2
}
}
if out.NumGoroutines <= 0 {
out.NumGoroutines = 4
}
return out
}
// NewTunedSubscriber builds a pubsub/v2 Subscriber with explicit flow control.
func NewTunedSubscriber(ctx context.Context, cfg ReceiverConfig, opts ...option.ClientOption) (*pubsub.Client, *pubsub.Subscriber, error) {
n := cfg.Normalized()
client, err := pubsub.NewClient(ctx, n.ProjectID, opts...)
if err != nil {
return nil, nil, fmt.Errorf("create pubsub client for project %q: %w", n.ProjectID, err)
}
sub := client.Subscriber(n.SubscriptionID)
sub.ReceiveSettings.MaxOutstandingMessages = n.MaxOutstandingMessages
sub.ReceiveSettings.MaxOutstandingBytes = n.MaxOutstandingBytes
sub.ReceiveSettings.MaxExtension = n.MaxExtension
sub.ReceiveSettings.NumGoroutines = n.NumGoroutines
return client, sub, nil
}
// AckDeadlineFor returns the subscription ack deadline (seconds) to provision
// for a given per-message processing timeout: at least 30s, roughly 2.5x the
// timeout, capped at the Pub/Sub maximum of 600s.
func AckDeadlineFor(perMessageTimeout time.Duration) int {
secs := int(perMessageTimeout.Seconds()*2.5 + 0.999)
if secs < 30 {
secs = 30
}
if secs > 600 {
secs = 600
}
return secs
}
```
Wire it in `main`:
```go
client, sub, err := flowcontrol.NewTunedSubscriber(ctx, flowcontrol.ReceiverConfig{
ProjectID: projectID,
SubscriptionID: subscriptionID,
DBMaxOpenConns: 32, // same value passed to db.SetMaxOpenConns
MemoryLimitBytes: 512 << 20, // container limit
PerMessageTimeout: 45 * time.Second,
})
if err != nil {
return err
}
defer client.Close()
err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) { /* dispatcher.Handle */ })
```
Provision the subscription ack deadline with `AckDeadlineFor(PerMessageTimeout)`
(45s → 113s, rounded up to 120s below; the service maximum is 600s).
## 5. Provisioning: dead-letter topic, filtered subscription, backoff, IAM
Run only after confirming `{project_id}` and obtaining approval for IAM
bindings. Order matters: the dead-letter topic and its pull subscription must
exist before the main subscription references them.
```bash
PROJECT_NUMBER="$(gcloud projects describe "{project_id}" --format='value(projectNumber)')"
PUBSUB_SA="service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com"
# 1. Dead-letter topic + durable pull subscription FIRST (a DLQ topic with no
# subscription silently discards every dead-lettered message).
gcloud pubsub topics create "{dlq_topic_id}" --project="{project_id}"
gcloud pubsub subscriptions create "{dlq_subscription_id}" \
--topic="{dlq_topic_id}" \
--message-retention-duration=14d \
--ack-deadline=60 \
--project="{project_id}"
# 2. Main topic + subscription with backoff, dead-letter policy and attribute filter.
gcloud pubsub topics create "{topic_id}" --project="{project_id}"
gcloud pubsub subscriptions create "{subscription_id}" \
--topic="{topic_id}" \
--ack-deadline=120 \
--min-retry-delay=10s \
--max-retry-delay=600s \
--dead-letter-topic="{dlq_topic_id}" \
--max-delivery-attempts=5 \
--message-filter='attributes.event_type="orders.order.created"' \
--project="{project_id}"
# Add --enable-message-ordering only when the escape hatch (ordering keys) is chosen.
# 3. Grant the Pub/Sub service agent the two roles that make dead-lettering work.
gcloud pubsub topics add-iam-policy-binding "{dlq_topic_id}" \
--member="serviceAccount:${PUBSUB_SA}" \
--role="roles/pubsub.publisher" \
--project="{project_id}"
gcloud pubsub subscriptions add-iam-policy-binding "{subscription_id}" \
--member="serviceAccount:${PUBSUB_SA}" \
--role="roles/pubsub.subscriber" \
--project="{project_id}"
# 4. Verify the policy took effect.
gcloud pubsub subscriptions describe "{subscription_id}" \
--project="{project_id}" \
--format='yaml(deadLetterPolicy,retryPolicy,ackDeadlineSeconds,filter)'
```
Equivalent Terraform resource names: `google_pubsub_topic`,
`google_pubsub_subscription` (`dead_letter_policy`, `retry_policy`, `filter`),
`google_pubsub_topic_iam_member`, `google_pubsub_subscription_iam_member`.
## 6. Cloud Storage claim-check for large payloads
For files or documents whose size can exceed ~1 MB (or approaches the **10 MB
Pub/Sub hard limit**):
1. **Upload the payload** to `gs://{claim_check_bucket}/incoming/{date}/{batch_id}`.
2. **Publish a notification** automatically from the bucket (without
`--skip-topic-setup` this also creates the topic if missing and grants
`roles/pubsub.publisher` to the Cloud Storage service agent; obtain
approval first or pass `--skip-topic-setup`):
```bash
gcloud storage buckets notifications create "gs://{claim_check_bucket}" \
--topic="projects/{project_id}/topics/{batch_topic_id}" \
--event-types=OBJECT_FINALIZE \
--object-prefix="incoming/" \
--payload-format=json
```
3. **Stream in the consumer**: read `bucketId` and `objectId` from the
message attributes, open the object with the Cloud Storage client, and
parse it as a stream (`json.Decoder`, `xml.Decoder`, CSV reader) instead
of loading the entire object into memory. Grant the consumer identity
`roles/storage.objectViewer` on the bucket.
4. **Lifecycle**: add an object lifecycle rule (for example delete after 30
days) so `{claim_check_bucket}` does not grow unbounded.
## 7. Monitoring metrics, Phase 2 checklist, and test cleanup
| Metric (`pubsub.googleapis.com/`) | Alert when | Meaning |
| --- | --- | --- |
| `subscription/num_undelivered_messages` | sustained growth over 10 min | Consumers cannot keep up; scale out or fix downstream. |
| `subscription/oldest_unacked_message_age` | > ack deadline × 3 | Messages are being redelivered or stuck. |
| `subscription/dead_letter_message_count` | > 0 | Poison messages reached the DLQ; inspect `{dlq_subscription_id}`. |
| `subscription/expired_ack_deadlines_count` | > 0 sustained for 5 min | Processing time exceeds the lease or ack deadline, or flow control is too high. |
Phase 2 checklist:
- [ ] Flow control is set explicitly in code (never the library default).
- [ ] `max_outstanding_messages * max_replicas <= database_connection_budget`.
- [ ] Per-message processing timeout < client max lease extension
(streaming pull) and < subscription ack deadline (push).
- [ ] Dead-letter topic has a pull subscription **and** the Pub/Sub service
agent holds `roles/pubsub.publisher` on `{dlq_topic_id}` and
`roles/pubsub.subscriber` on `{subscription_id}`.
- [ ] Payloads that can exceed 1 MB use Cloud Storage claim-check pointers.
- [ ] Every `gcloud` flag used exists in the current CLI (verify with
`gcloud pubsub subscriptions create --help`).
Test-only cleanup (non-production projects only, after user confirmation; list
any claim-check test prefix before deleting):
```bash
gcloud pubsub subscriptions delete {test_subscription_id} {test_dlq_subscription_id} --project={test_project_id}
gcloud pubsub topics delete {test_topic_id} {test_dlq_topic_id} --project={test_project_id}
gcloud storage ls "gs://{claim_check_bucket}/incoming/{test_prefix}/**"
gcloud storage rm --recursive "gs://{claim_check_bucket}/incoming/{test_prefix}/**"
```
phase3-consumer-and-autoscaling.md 23.2 KB
# Phase 3: Event-driven workflow triggering, SIGTERM drain, and autoscaling
- [1. Runtime selection and IAM](#1-runtime-selection-and-iam): Lines 27-47
- [2. Deterministic ack, nack, and quarantine matrix and shutdown rules](#2-deterministic-ack-nack-and-quarantine-matrix-and-shutdown-rules): Lines 48-88
- [3. Go dispatcher with the ack/nack/quarantine matrix](#3-go-dispatcher-with-the-acknackquarantine-matrix): Lines 89-235
- [4. Ordered startup and SIGTERM drain](#4-ordered-startup-and-sigterm-drain): Lines 236-337
- [5. Pub/Sub adapter wiring](#5-pubsub-adapter-wiring): Lines 338-383
- [6. GKE HorizontalPodAutoscaler on Pub/Sub backlog](#6-gke-horizontalpodautoscaler-on-pubsub-backlog): Lines 384-453
- [7. Escape hatch: Cloud Run push, Eventarc, and Cloud Run functions](#7-escape-hatch-cloud-run-push-eventarc-and-cloud-run-functions): Lines 454-523
- [8. Phase 3 checklist and test cleanup](#8-phase-3-checklist-and-test-cleanup): Lines 524-549
Grounding documentation:
- Autoscaling on Pub/Sub metrics (GKE): https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/autoscaling-metrics.md.txt
- Scale to zero on GKE using KEDA: https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/scale-to-zero-using-keda.md.txt
- Pub/Sub push subscriptions: https://docs.cloud.google.com/pubsub/docs/push.md.txt
- Eventarc overview: https://docs.cloud.google.com/eventarc/docs/overview.md.txt
- Cloud Run + Pub/Sub tutorial: https://docs.cloud.google.com/run/docs/tutorials/pubsub.md.txt
- Cloud Run functions retry semantics: https://docs.cloud.google.com/functions/docs/bestpractices/retries.md.txt
Trigger domain workflows from asynchronous events reliably: every delivery ends
in a deterministic ack, nack, or quarantine; a rollout never aborts an
in-flight transaction; and replicas scale with backlog within the database
connection budget. The Go blocks headed `// file:` in sections 3–4 are compiled
and unit-tested (`go test -race`, standard library Go 1.21+).
## 1. Runtime selection and IAM
Enable `pubsub.googleapis.com` and `monitoring.googleapis.com` plus
`container.googleapis.com` (GKE) or `run.googleapis.com` and
`eventarc.googleapis.com` (and `cloudfunctions.googleapis.com`,
`cloudbuild.googleapis.com`, and `artifactregistry.googleapis.com` for Cloud Run
functions). Request approval before granting IAM bindings:
| Principal | Role | Purpose |
| --- | --- | --- |
| GKE consumer (Workload Identity Federation for GKE) | `roles/pubsub.subscriber` on `{subscription_id}` | Streaming pull |
| Consumer that republishes downstream events | `roles/pubsub.publisher` on the outbound topic | Outbound events |
| Metrics adapter service account (`custom-metrics-stackdriver-adapter`) | `roles/monitoring.viewer` on `{project_id}` | HPA external metrics |
| Cloud Run push / Eventarc trigger service account | `roles/run.invoker` on the service; `roles/eventarc.eventReceiver` for Eventarc | Authenticated push |
| Pub/Sub service agent (projects created before 2021-04-08 only) | `roles/iam.serviceAccountTokenCreator` | Mint push auth tokens |
| Option | Choose when | Delivery and scaling |
| --- | --- | --- |
| **Default: GKE + streaming pull** | Sustained throughput, long-lived database pools, processing longer than the 600 s push ack deadline, strict drain control | Long-lived gRPC stream; HPA `autoscaling/v2` on `pubsub.googleapis.com\|subscription\|num_undelivered_messages` |
| **Escape hatch: Cloud Run** (service via push/Eventarc, or a Cloud Run function for a single short handler) | Bursty or sporadic traffic, scale-to-zero, stateless work under the 600 s push ack deadline; teams already on Cloud Run start here | Authenticated HTTPS POST; `2xx` (`102/200/201/202/204`) = ack, anything else = nack with backoff; Cloud Run scales on request concurrency. A Cloud Run function **must** be deployed with `--retry`: by default a failed invocation is acked and the event is **dropped**. |
## 2. Deterministic ack, nack, and quarantine matrix and shutdown rules
Pub/Sub guarantees **at-least-once** delivery: duplicates and reordering are
normal. Classify every outcome with sentinel errors and `errors.Is` (or the
language equivalent), never by matching error strings. Note that the
subscription ack deadline (configured in Phase 2,
`references/phase2-pubsub-topology-and-sizing.md`) must exceed the handler's
`PerMessageTimeout`.
| Outcome | Pull action | Push HTTP status | Rationale |
| --- | --- | --- | --- |
| Success | `Ack` | `204` (any of `102/200/201/202/204`) | State committed. |
| Idempotent duplicate (natural key already processed) | **`Ack`** | `204` | Nacking a duplicate loops to the dead-letter topic with valid data and pollutes the DLQ. |
| Permanent error (malformed payload, contract violation, unroutable type) | **Default:** `Nack` when the subscription has a dead-letter policy, so the message reaches the DLQ after `max-delivery-attempts`. **Escape hatch:** persist to a quarantine store then `Ack` when the business needs an audit trail. **No DLQ:** `Ack` and alert. | `503` with a DLQ; `204` + alert without | Without `max-delivery-attempts` a poison message retries until retention expires and starves the backlog. |
| Transient error (database timeout, deadlock, connection reset, dependency 5xx) | `Nack` | `503` (or `429`) | Triggers the subscription's exponential backoff until the dependency recovers. |
Routing and graceful shutdown rules:
1. **Attribute-first routing**: dispatch on `attributes["event_type"]` (fall
back to an envelope header) to a typed use case per event, so one
subscription can serve several workflows without parsing every payload.
2. **Idempotency at the persistence boundary**: deduplicate on the event ID
or business natural key with a unique constraint or atomic upsert before
side effects.
3. **Shutdown sequence on SIGTERM** (GKE streaming pull; Cloud Run push
instances get a fixed 10 s before SIGKILL, so keep push cleanup under 10 s
and rely on the request timeout for in-flight work):
1. Cancel **only** the receive context; streaming pull stops fetching and
waits for in-flight callbacks.
2. Give in-flight work a detached, bounded context
(`context.WithoutCancel` + timeout) so commits finish without
`context canceled` errors.
3. Wait for `Receive` to return (every callback acked or nacked).
4. Stop publishers, flush telemetry, then close the database **strictly
last**. *Why:* closing the pool before `Receive` returns forces
mid-transaction rollbacks and duplicate redeliveries on every rollout.
5. Order the budgets as a chain:
`PerMessageTimeout <= DrainTimeout < terminationGracePeriodSeconds`
(specifically `terminationGracePeriodSeconds >= DrainTimeout + 5s`),
sharing one single `DrainTimeout` deadline across steps 1–4.
## 3. Go dispatcher with the ack/nack/quarantine matrix
```go
// file: dispatcher/dispatcher.go
package dispatcher
import (
"context"
"errors"
"log/slog"
"time"
)
// Sentinel errors returned by workflows so the dispatcher can classify the
// outcome with errors.Is (never by string matching).
var (
ErrDuplicateEvent = errors.New("duplicate event already processed")
ErrInvalidPayload = errors.New("permanent payload or contract error")
)
// Outcome is the decision taken for one message. Tests assert on it; the
// Pub/Sub adapter maps it to msg.Ack() / msg.Nack() or to HTTP status codes.
type Outcome int
const (
OutcomeAck Outcome = iota
OutcomeNack
)
// InboundMessage abstracts *pubsub.Message so the dispatcher is unit-testable.
type InboundMessage interface {
ID() string
Data() []byte
Attributes() map[string]string
Ack()
Nack()
}
// WorkflowFunc executes one business workflow for an event.
type WorkflowFunc func(ctx context.Context, data []byte, attrs map[string]string) error
// Dispatcher routes events by the "event_type" attribute and applies the
// deterministic ACK/NACK matrix.
type Dispatcher struct {
Routes map[string]WorkflowFunc
DefaultRoute WorkflowFunc // optional catch-all
PerMessageTimeout time.Duration
HasDeadLetter bool // subscription has a dead-letter policy
Quarantine func(ctx context.Context, msg InboundMessage, cause error) error
Logger *slog.Logger
EventTypeAttr string // defaults to "event_type"
}
const defaultPerMessageTimeout = 30 * time.Second
// Handle processes one message and returns the decision for observability.
func (d *Dispatcher) Handle(receiveCtx context.Context, msg InboundMessage) Outcome {
if msg == nil {
return OutcomeAck
}
// Handle runs concurrently from Receive callbacks, so it never writes to d:
// defaults are resolved into locals.
attrKey, timeout, logger := d.effective()
// Detach from receiveCtx so an in-flight commit finishes during SIGTERM
// drain, while enforcing a per-message deadline shorter than the lease cap.
workCtx, cancel := context.WithTimeout(context.WithoutCancel(receiveCtx), timeout)
defer cancel()
attrs := msg.Attributes()
eventType := attrs[attrKey]
route, ok := d.Routes[eventType]
if !ok {
route = d.DefaultRoute
}
if route == nil {
return d.permanentFailure(workCtx, logger, msg, eventType, errors.New("unroutable event type"))
}
err := route(workCtx, msg.Data(), attrs)
switch {
case err == nil:
msg.Ack()
return OutcomeAck
case errors.Is(err, ErrDuplicateEvent):
// Never Nack an already-processed key: it loops to the DLQ with valid data.
logger.InfoContext(workCtx, "duplicate event acknowledged", "msg_id", msg.ID(), "event_type", eventType)
msg.Ack()
return OutcomeAck
case errors.Is(err, ErrInvalidPayload):
return d.permanentFailure(workCtx, logger, msg, eventType, err)
default:
// Transient: database timeout, deadlock, connection reset -> retry with backoff.
logger.ErrorContext(workCtx, "transient workflow error, nacking", "msg_id", msg.ID(), "event_type", eventType, "error", err)
msg.Nack()
return OutcomeNack
}
}
// effective returns the configuration with defaults applied, without mutating d.
func (d *Dispatcher) effective() (attrKey string, timeout time.Duration, logger *slog.Logger) {
attrKey, timeout, logger = d.EventTypeAttr, d.PerMessageTimeout, d.Logger
if attrKey == "" {
attrKey = "event_type"
}
if timeout <= 0 {
timeout = defaultPerMessageTimeout // zero would expire every message instantly
}
if logger == nil {
logger = slog.Default()
}
return attrKey, timeout, logger
}
// permanentFailure implements the permanent-error rule. Default: Nack so the
// dead-letter policy moves the message to the DLQ after max-delivery-attempts.
// Escape hatch: when a Quarantine store is configured (business needs an audit
// trail), persist there and Ack. Without a dead-letter policy, Ack and alert:
// a Nack would retry forever and starve the backlog.
func (d *Dispatcher) permanentFailure(ctx context.Context, logger *slog.Logger, msg InboundMessage, eventType string, cause error) Outcome {
if d.Quarantine != nil {
if qErr := d.Quarantine(ctx, msg, cause); qErr == nil {
logger.WarnContext(ctx, "permanent error quarantined", "msg_id", msg.ID(), "event_type", eventType, "error", cause)
msg.Ack()
return OutcomeAck
}
// Quarantine store unavailable: fall through to the DLQ decision.
}
if d.HasDeadLetter {
logger.WarnContext(ctx, "permanent error, nacking toward dead-letter topic", "msg_id", msg.ID(), "event_type", eventType, "error", cause)
msg.Nack()
return OutcomeNack
}
logger.ErrorContext(ctx, "permanent error on subscription WITHOUT dead-letter policy; acking to avoid poison loop", "msg_id", msg.ID(), "event_type", eventType, "error", cause)
msg.Ack()
return OutcomeAck
}
// HTTPStatusFor maps an outcome to the status a Pub/Sub push or Eventarc
// handler must return (2xx = ack, 429/5xx = nack with backoff).
func HTTPStatusFor(o Outcome) int {
if o == OutcomeAck {
return 204
}
return 503
}
```
## 4. Ordered startup and SIGTERM drain
```go
// file: dispatcher/shutdown.go
package dispatcher
import (
"context"
"errors"
"fmt"
"time"
)
// Receiver is the subset of *pubsub.Subscriber the lifecycle needs.
type Receiver interface {
Receive(ctx context.Context, f func(context.Context, InboundMessage)) error
}
// Lifecycle orders startup and shutdown so no in-flight transaction is cut.
// Shutdown sequence (SIGTERM):
// 1. cancel receiveCtx -> Receive stops pulling, waits for in-flight callbacks
// 2. <-receiveDone -> every callback has called Ack or Nack
// 3. StopPublishers() -> flush outbound events
// 4. FlushTelemetry() -> export remaining spans
// 5. CloseDB() -> strictly last
//
// Steps 1-4 share ONE deadline of DrainTimeout measured from SIGTERM, so set
// DrainTimeout >= per-message timeout and terminationGracePeriodSeconds >=
// DrainTimeout + 5s.
type Lifecycle struct {
Receiver Receiver
Handler func(ctx context.Context, msg InboundMessage)
StopPublishers func(ctx context.Context) error
FlushTelemetry func(ctx context.Context) error
CloseDB func() error
DrainTimeout time.Duration // < terminationGracePeriodSeconds - 5s
// Trace records the order of shutdown steps; tests assert on it.
Trace []string
}
const defaultDrainTimeout = 25 * time.Second
// Run blocks until sigCtx is cancelled (SIGTERM/SIGINT) or Receive fails.
func (l *Lifecycle) Run(sigCtx context.Context) error {
if l.DrainTimeout <= 0 {
l.DrainTimeout = defaultDrainTimeout
}
receiveCtx, cancelReceive := context.WithCancel(context.Background())
defer cancelReceive()
receiveDone := make(chan error, 1)
go func() { receiveDone <- l.Receiver.Receive(receiveCtx, l.Handler) }()
// One deadline for the WHOLE shutdown (drain + publishers + telemetry + DB):
// two consecutive DrainTimeout windows would exceed terminationGracePeriodSeconds.
var deadline time.Time
var receiveErr error
select {
case <-sigCtx.Done():
l.Trace = append(l.Trace, "cancel_receive")
deadline = time.Now().Add(l.DrainTimeout)
cancelReceive()
drainCtx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
select {
case receiveErr = <-receiveDone:
l.Trace = append(l.Trace, "receive_returned")
case <-drainCtx.Done():
// Last resort: callbacks are still running and the DB will be closed
// underneath them. Size DrainTimeout so this only happens when the
// orchestrator is about to SIGKILL the process anyway.
l.Trace = append(l.Trace, "drain_timeout")
receiveErr = fmt.Errorf("drain timeout after %s: %w", l.DrainTimeout, drainCtx.Err())
}
case receiveErr = <-receiveDone:
l.Trace = append(l.Trace, "receive_returned")
deadline = time.Now().Add(l.DrainTimeout)
}
shutdownCtx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
var errs []error
if l.StopPublishers != nil {
l.Trace = append(l.Trace, "stop_publishers")
errs = append(errs, l.StopPublishers(shutdownCtx))
}
if l.FlushTelemetry != nil {
l.Trace = append(l.Trace, "flush_telemetry")
errs = append(errs, l.FlushTelemetry(shutdownCtx))
}
if l.CloseDB != nil {
l.Trace = append(l.Trace, "close_db")
errs = append(errs, l.CloseDB())
}
if receiveErr != nil && !errors.Is(receiveErr, context.Canceled) {
errs = append(errs, receiveErr)
}
return errors.Join(errs...)
}
```
## 5. Pub/Sub adapter wiring
Adapt `*pubsub.Message` (from `cloud.google.com/go/pubsub/v2`, `go get
cloud.google.com/go/pubsub/v2@v2.8.0` or later) to `InboundMessage` and run the
lifecycle from `main`:
```go
type pubsubMessage struct{ m *pubsub.Message }
func (p pubsubMessage) ID() string { return p.m.ID }
func (p pubsubMessage) Data() []byte { return p.m.Data }
func (p pubsubMessage) Attributes() map[string]string { return p.m.Attributes }
func (p pubsubMessage) Ack() { p.m.Ack() }
func (p pubsubMessage) Nack() { p.m.Nack() }
type subscriberReceiver struct{ sub *pubsub.Subscriber }
func (r subscriberReceiver) Receive(ctx context.Context, f func(context.Context, dispatcher.InboundMessage)) error {
return r.sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) { f(ctx, pubsubMessage{m}) })
}
func main() {
sigCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
d := &dispatcher.Dispatcher{
Routes: map[string]dispatcher.WorkflowFunc{"orders.order.created": orderCreated.Handle},
PerMessageTimeout: 45 * time.Second, // < ReceiveSettings.MaxExtension and <= DrainTimeout; for push, < ack deadline (max 600 s)
HasDeadLetter: true,
Logger: logger,
}
lc := &dispatcher.Lifecycle{
Receiver: subscriberReceiver{sub},
Handler: func(ctx context.Context, m dispatcher.InboundMessage) { d.Handle(ctx, m) },
StopPublishers: func(ctx context.Context) error { publisher.Stop(); return nil },
FlushTelemetry: tracerShutdown,
CloseDB: db.Close,
DrainTimeout: 50 * time.Second, // >= PerMessageTimeout; terminationGracePeriodSeconds: 55
}
if err := lc.Run(sigCtx); err != nil {
logger.Error("consumer exited", "error", err)
os.Exit(1)
}
}
```
## 6. GKE HorizontalPodAutoscaler on Pub/Sub backlog
Install the metrics adapter (`custom-metrics-stackdriver-adapter`,
https://github.com/GoogleCloudPlatform/k8s-stackdriver; pin the manifest to a
release tag rather than `master`) and bind its Kubernetes service account to
`roles/monitoring.viewer` through Workload Identity Federation for GKE:
```bash
gcloud projects add-iam-policy-binding "{project_id}" \
--role="roles/monitoring.viewer" \
--member="principal://iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{project_id}.svc.id.goog/subject/ns/custom-metrics/sa/custom-metrics-stackdriver-adapter"
```
If the consumer must scale to zero, use the KEDA `gcp-pubsub` scaler (`mode:
SubscriptionSize`) as the escape hatch instead of HPA plus adapter
(https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/scale-to-zero-using-keda.md.txt).
`AverageValue` divides the backlog across replicas; set it to 1–2× the
per-replica `MaxOutstandingMessages`. Cap `maxReplicas` so
`maxReplicas * pool_max_open_conns <= database_connection_budget`:
```yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: "{deployment_name}-hpa"
namespace: "{namespace}"
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: "{deployment_name}"
minReplicas: 2
maxReplicas: 10
behavior:
scaleUp:
stabilizationWindowSeconds: 30
policies:
- type: Pods
value: 4
periodSeconds: 60
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Pods
value: 1
periodSeconds: 60
metrics:
- type: External
external:
metric:
name: pubsub.googleapis.com|subscription|num_undelivered_messages
selector:
matchLabels:
resource.labels.subscription_id: "{subscription_id}"
target:
type: AverageValue
averageValue: "50"
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 75
```
Pod spec requirements: `terminationGracePeriodSeconds: 55` (drain timeout 50 s
plus 5 s, with drain ≥ per-message timeout 45 s), readiness probe independent of
Pub/Sub connectivity, and `resources.limits.memory` matching the value used to
derive `MaxOutstandingBytes`.
## 7. Escape hatch: Cloud Run push, Eventarc, and Cloud Run functions
```bash
gcloud eventarc triggers create "{trigger_name}" \
--location="{region}" \
--destination-run-service="{service_name}" \
--destination-run-region="{region}" \
--destination-run-path="/events" \
--event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \
--transport-topic="projects/{project_id}/topics/{topic_id}" \
--service-account="{trigger_sa}@{project_id}.iam.gserviceaccount.com" \
--project="{project_id}"
```
Eventarc creates the subscription without a dead-letter policy; add one before
setting `HasDeadLetter: true` in the dispatcher:
```bash
gcloud pubsub subscriptions update "{eventarc_subscription_id}" \
--dead-letter-topic="{dlq_topic_id}" \
--max-delivery-attempts=5 \
--project="{project_id}"
```
For a single short handler, deploy a Cloud Run function bound to the topic.
**Always deploy with `--retry`**: by default an event-driven Cloud Run function
does **not** retry and a returned error acknowledges and **drops** the event!
With `--retry`, returning an error is a nack (retried with backoff for up to 7
days), so either attach a dead-letter policy to the subscription or return
`nil` (success) and alert on permanent payload errors so poison events do not
loop for days:
```bash
gcloud functions deploy "{function_name}" \
--gen2 \
--region="{region}" \
--runtime="{runtime}" \
--source="{source_dir}" \
--entry-point="{entry_point}" \
--trigger-topic="{topic_id}" \
--retry \
--service-account="{function_sa}@{project_id}.iam.gserviceaccount.com" \
--project="{project_id}"
```
Equivalent `gcloud run deploy` form (paired with the Eventarc trigger above):
```bash
gcloud run deploy "{function_name}" \
--function="{entry_point}" \
--source="{source_dir}" \
--base-image="{runtime}" \
--region="{region}" \
--project="{project_id}"
```
HTTP handler status contract (`dispatcher.HTTPStatusFor`):
| Outcome | Status | Notes |
| --- | --- | --- |
| Success or idempotent duplicate | `204` (ack set is strictly `102/200/201/202/204`; other `2xx` codes are **not** acks) | Ack |
| Permanent error, subscription has a dead-letter topic | `503` | Counts toward `max-delivery-attempts` |
| Permanent error, no dead-letter topic | `204` + log/quarantine + alert | Never let a poison message retry until retention expires |
| Transient error | `503` (or `429`) | Nack with exponential backoff |
Cloud Run settings: per-message timeout ≤ request timeout ≤ subscription ack
deadline (≤ 600 s); `--concurrency` ≤ per-instance `pool_max_open_conns`;
`--no-cpu-throttling` when background publishing happens after the response;
SIGTERM cleanup must finish within Cloud Run's fixed 10 s grace period.
## 8. Phase 3 checklist and test cleanup
- [ ] Tests cover success (ack), duplicate (ack), permanent with DLQ (nack),
permanent without DLQ (ack + alert), quarantine escape hatch (ack),
transient (nack), and zero-value configuration defaults.
- [ ] Database close and publisher stop run strictly **after** `Receive`
returns.
- [ ] In-flight work uses a context detached from the receive context with a
deadline below `MaxExtension` and `<= DrainTimeout`.
- [ ] Cloud Run functions are deployed with `--retry`; Eventarc-created
subscriptions get a dead-letter policy before `HasDeadLetter` is set.
- [ ] HPA uses `autoscaling/v2`, scales on `num_undelivered_messages` with a
scale-down stabilization window, and `maxReplicas` respects the database
connection budget.
- [ ] Push handlers return `102/200/201/202/204` for acks and `503`/`429` for
nacks.
Test-only cleanup (non-production clusters/projects only, after user
confirmation):
```bash
kubectl delete hpa {test_hpa_name} -n {test_namespace}
gcloud eventarc triggers delete {test_trigger_name} --location={region} --project={test_project_id}
gcloud run services delete {test_service_name} --region={region} --project={test_project_id}
gcloud functions delete {test_function_name} --region={region} --project={test_project_id}
```
phase4-distributed-tracing.md 22.7 KB
# Phase 4: Distributed trace instrumentation and Cloud Logging correlation
- [1. Architecture layers, propagation contract, and workflow](#1-architecture-layers-propagation-contract-and-workflow): Lines 26-89
- [2. HTTP and gRPC wrapping](#2-http-and-grpc-wrapping): Lines 90-138
- [3. W3C carrier over Pub/Sub message attributes](#3-w3c-carrier-over-pubsub-message-attributes): Lines 139-238
- [4. Cloud Logging trace-correlated slog handler](#4-cloud-logging-trace-correlated-slog-handler): Lines 239-355
- [5. Generic port decorator for stage spans](#5-generic-port-decorator-for-stage-spans): Lines 356-417
- [6. TracerProvider: OTLP export, sampler, shutdown](#6-tracerprovider-otlp-export-sampler-shutdown): Lines 418-511
- [7. Deterministic unit tests with the in-memory exporter](#7-deterministic-unit-tests-with-the-in-memory-exporter): Lines 512-546
Grounding documentation:
- Cloud Trace with OpenTelemetry in Go: https://docs.cloud.google.com/trace/docs/setup/go-ot.md.txt
- Migrate from the Trace exporter to OTLP: https://docs.cloud.google.com/trace/docs/migrate-to-otlp-endpoints.md.txt
- Cloud Run trace sampling behaviour: https://docs.cloud.google.com/run/docs/trace.md.txt
- Pub/Sub client-library tracing (`googclient_traceparent`): https://docs.cloud.google.com/pubsub/docs/open-telemetry-tracing.md.txt
- Cloud Logging structured logging special fields: https://docs.cloud.google.com/logging/docs/structured-logging.md.txt
Instrument services end to end so inbound HTTP/gRPC requests start a server
span, outbound calls and Pub/Sub publishes carry W3C Trace Context forward,
consumers continue the same trace, database stages emit child spans, and every
log line carries `logging.googleapis.com/trace`. Every Go block headed
`// file:` is compiled and unit-tested (`go test -race`, `otel` v1.47.0,
`semconv` v1.37.0).
## 1. Architecture layers, propagation contract, and workflow
Install OpenTelemetry packages (Go example; Python uses
`opentelemetry-instrument` + `opentelemetry-exporter-otlp`, Java the
`-javaagent` OpenTelemetry agent, Node.js
`@opentelemetry/auto-instrumentations-node`):
```bash
go get go.opentelemetry.io/otel@latest \
go.opentelemetry.io/otel/sdk@latest \
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc@latest \
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@latest \
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc@latest
```
Export spans over OTLP to `telemetry.googleapis.com:443` with
`roles/telemetry.tracesWriter` (`telemetry.googleapis.com` API) and
`roles/logging.logWriter` (`logging.googleapis.com` API). The legacy
`opentelemetry-operations-go/exporter/trace` package (`roles/cloudtrace.agent`)
is deprecated (archived after 2027-01-01) and is an escape hatch only for code
that already depends on it.
Where instrumentation lives:
| Layer | Rule | Rationale |
| --- | --- | --- |
| Domain and use cases | **Default:** no OpenTelemetry imports; pass `ctx` through every port. | Keeps business logic testable without SDKs and insulated from SDK upgrades. |
| Primary adapters (Pub/Sub consumer, HTTP, gRPC) | Start the root or consumer span; extract upstream context. | The adapter is the first code that sees the carrier. |
| Secondary adapters (repository, publisher, external clients) | Wrap port calls with a tracing decorator producing child spans per stage. | Per-stage latency (`db.stage`, `db.validate`, `db.commit`) pinpoints bottlenecks. |
| Application layer (escape hatch) | Call `otel.Tracer(...)` directly only where the codebase permits SDK imports in services. | Simpler when no clean-architecture constraint exists. |
Propagation and correlation contract:
| Boundary | Operation | Keys and format | Rationale |
| --- | --- | --- | --- |
| Inbound HTTP / gRPC | Wrap handlers per route (`otelhttp.NewHandler`, `otelgrpc.NewServerHandler` stats handler) so a `SpanKindServer` span starts from incoming `traceparent`. | `traceparent`, `tracestate` headers; `http.route` (per-route wrapping on Go 1.22+ `ServeMux`), `rpc.service` | Works with no Pub/Sub at all. |
| Outbound HTTP / gRPC | Use instrumented clients (`otelhttp.NewTransport`, `otelgrpc.NewClientHandler`) so downstream calls become `SpanKindClient` children. | same headers | Makes the critical path visible hop by hop (input to Phase 1). |
| Pub/Sub hop, **default** | Enable the client library's built-in tracing on **both** sides (`pubsub.ClientConfig{EnableOpenTelemetryTracing: true}`); in the `Receive` callback start child spans from the callback `ctx` and **do not re-extract** from attributes (never pass trace IDs in the message payload). | library writes `googclient_traceparent` / `googclient_tracestate` | Publisher, queue dwell, and consumer spans are emitted in one trace; manual re-extraction would detach them. |
| Pub/Sub hop, **escape hatch** | Inject `traceparent` into message attributes on publish and extract it (falling back to `googclient_*` keys) to start a `SpanKindConsumer` span, **only** when one side is not a Google client library with tracing enabled (push subscriptions, Eventarc, Cloud Run functions, or a foreign producer). | `traceparent`, `messaging.system=gcp_pubsub`, `messaging.destination.subscription.name`, `messaging.operation.name=process` | Preserves continuity where the client library cannot do it automatically. |
| Database and stage operations | Child spans (`SpanKindClient`/`Internal`); `RecordError` + `SetStatus(codes.Error, ...)` on failure; leave status `Unset` on success. | `db.system`, low-cardinality `{operation} {target}` name (never open spans per loop iteration or put IDs/payloads in span names) | Attributes failures to the exact stage without blowing up trace cardinality. |
| Structured logs | Log with context-aware calls (`InfoContext`, `ErrorContext`) through a handler that emits Cloud Logging fields at the top level even inside `WithGroup`. | `logging.googleapis.com/trace` = `projects/{project_id}/traces/{trace_id}`, `logging.googleapis.com/spanId`, `logging.googleapis.com/trace_sampled`, top-level `severity` (`WARN` → `WARNING`) and `message` | Enables one-click log-to-trace navigation; context-free log calls lose correlation. |
Scope rules for Phase 4:
- **Synchronous HTTP/gRPC-only services (no Pub/Sub)**: use sections 2 and
4–7 only (`TracerProvider` with the Cloud Run
`WithRemoteParentNotSampled` sampler rule, `otelhttp`, `otelgrpc` stats
handlers, DB stage decorator, `slog` correlation); **never** introduce
Pub/Sub topics or attribute carriers.
- **Cloud Run missing-traces trap**: Cloud Run injects a `traceparent` header
on every request with the `sampled` flag cleared (`00`) for all but ~0.1
req/s/instance. A plain `ParentBased(TraceIDRatioBased(ratio))` sampler
obeys that cleared remote parent flag and drops almost every trace! Fix
the sampler first using
`ParentBased(TraceIDRatioBased(ratio), WithRemoteParentNotSampled(TraceIDRatioBased(ratio)))`
(never recommend `AlwaysSample` in production without warning about cost,
and do not blame the exporter or IAM before fixing the sampler).
- **Querying existing traces**: if the user asks how to find slow traces
(e.g. *"all traces slower than 2s"*), answer with the Cloud Trace console
or API (https://docs.cloud.google.com/trace/docs/finding-traces.md.txt) or
the `cloud-trace-querying` skill — never answer with OpenTelemetry setup
code, never require re-instrumenting first, and never invent a trace query
language.
## 2. HTTP and gRPC wrapping
```go
// file: telemetry/httpgrpc.go
package telemetry
import (
"net/http"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"google.golang.org/grpc"
)
// WrapHandler instruments one inbound HTTP route with a SpanKindServer span
// that continues the incoming traceparent. Wrap per route (not the whole mux)
// so http.route is populated from the Go 1.22+ ServeMux pattern.
func WrapHandler(pattern string, h http.Handler) http.Handler {
return otelhttp.NewHandler(h, pattern)
}
// NewHTTPClient returns an outbound client whose requests become
// SpanKindClient children and carry traceparent downstream.
func NewHTTPClient(base http.RoundTripper) *http.Client {
if base == nil {
base = http.DefaultTransport
}
return &http.Client{Transport: otelhttp.NewTransport(base)}
}
// GRPCServerOption instruments all inbound gRPC calls (stats handler API;
// the older interceptor API is deprecated).
func GRPCServerOption() grpc.ServerOption {
return grpc.StatsHandler(otelgrpc.NewServerHandler())
}
// GRPCDialOption instruments all outbound gRPC calls.
func GRPCDialOption() grpc.DialOption {
return grpc.WithStatsHandler(otelgrpc.NewClientHandler())
}
```
```go
mux := http.NewServeMux()
mux.Handle("GET /orders/{id}", telemetry.WrapHandler("GET /orders/{id}", getOrder))
client := telemetry.NewHTTPClient(nil)
srv := grpc.NewServer(telemetry.GRPCServerOption())
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()), telemetry.GRPCDialOption())
```
## 3. W3C carrier over Pub/Sub message attributes
Default for the Pub/Sub hop is the client library's built-in tracing (pass
`&pubsub.ClientConfig{EnableOpenTelemetryTracing: true}` to
`pubsub.NewClientWithConfig` on both publisher and subscriber; start child spans
from the `Receive` callback `ctx`). Use the carrier below only as the escape
hatch for push, Eventarc, Cloud Run functions, or foreign producers:
```go
// file: telemetry/carrier.go
package telemetry
import (
"context"
"go.opentelemetry.io/otel"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"go.opentelemetry.io/otel/trace"
)
// AttributeCarrier adapts Pub/Sub message attributes to the OpenTelemetry
// propagation.TextMapCarrier interface. It reads the W3C "traceparent" and falls back
// to "googclient_traceparent" / "googclient_tracestate", the keys written by
// Pub/Sub client libraries that have built-in OpenTelemetry tracing enabled.
type AttributeCarrier map[string]string
// Client libraries with built-in tracing prefix the W3C keys with "googclient_".
const googClientPrefix = "googclient_"
func (c AttributeCarrier) Get(key string) string {
if c == nil {
return ""
}
if v, ok := c[key]; ok && v != "" {
return v
}
if key == "traceparent" || key == "tracestate" {
return c[googClientPrefix+key]
}
return ""
}
func (c AttributeCarrier) Set(key, val string) {
if c != nil {
c[key] = val
}
}
func (c AttributeCarrier) Keys() []string {
keys := make([]string, 0, len(c))
for k := range c {
keys = append(keys, k)
}
return keys
}
// StartConsumerSpan extracts the upstream context from message attributes and
// starts a SpanKindConsumer span named "process {subscription}" per the
// OpenTelemetry messaging semantic conventions (v1.27+).
//
// Use it only when the client library's built-in tracing is NOT active on this
// side (push subscriptions, Eventarc, Cloud Run functions, or a producer you do
// not control). With pubsub.ClientConfig{EnableOpenTelemetryTracing: true} the
// Receive callback already runs inside a library-created consumer span: start
// child spans from that ctx and do not re-extract from attributes.
func StartConsumerSpan(ctx context.Context, tracer trace.Tracer, subscriptionID, msgID string, attrs map[string]string) (context.Context, trace.Span) {
parent := otel.GetTextMapPropagator().Extract(ctx, AttributeCarrier(attrs))
return tracer.Start(parent, "process "+subscriptionID,
trace.WithSpanKind(trace.SpanKindConsumer),
trace.WithAttributes(
semconv.MessagingSystemGCPPubSub,
semconv.MessagingDestinationSubscriptionName(subscriptionID),
semconv.MessagingMessageID(msgID),
semconv.MessagingOperationTypeProcess,
semconv.MessagingOperationName("process"),
),
)
}
// InjectOutboundAttributes writes traceparent/tracestate from ctx into the
// attribute map that will be attached to the outgoing Pub/Sub message.
func InjectOutboundAttributes(ctx context.Context, attrs map[string]string) map[string]string {
if attrs == nil {
attrs = make(map[string]string, 2)
}
otel.GetTextMapPropagator().Inject(ctx, AttributeCarrier(attrs))
return attrs
}
```
Producer side (escape hatch), right before publishing with
`cloud.google.com/go/pubsub/v2`:
```go
attrs := telemetry.InjectOutboundAttributes(ctx, map[string]string{
"event_type": ev.Type,
"schema_version": "1",
})
res := publisher.Publish(ctx, &pubsub.Message{Data: ev.Payload, Attributes: attrs})
```
## 4. Cloud Logging trace-correlated slog handler
```go
// file: telemetry/slog_handler.go
package telemetry
import (
"context"
"fmt"
"io"
"log/slog"
"go.opentelemetry.io/otel/trace"
)
// cloudLoggingHandler decorates a slog.Handler with the Cloud Logging special
// fields that link a log line to its trace and span. It records WithAttrs /
// WithGroup as operations replayed on top of the base handler at Handle time,
// so the trace fields always land at the TOP level of the JSON object even when
// the logger is inside a group (Cloud Logging ignores nested keys).
type cloudLoggingHandler struct {
base slog.Handler
ops []func(slog.Handler) slog.Handler
projectID string
}
// WrapHandlerWithCloudTrace adds trace correlation to any handler (idempotent).
func WrapHandlerWithCloudTrace(inner slog.Handler, projectID string) slog.Handler {
if _, already := inner.(*cloudLoggingHandler); already {
return inner
}
return &cloudLoggingHandler{base: inner, projectID: projectID}
}
// NewCloudLoggingJSONLogger emits structured JSON that Cloud Logging parses:
// "severity" and "message" top-level keys plus trace correlation fields.
func NewCloudLoggingJSONLogger(w io.Writer, projectID string, level slog.Level) *slog.Logger {
base := slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: level,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if len(groups) > 0 {
return a // only rewrite the built-in top-level keys, never user attributes
}
switch a.Key {
case slog.LevelKey:
if lvl, ok := a.Value.Any().(slog.Level); ok {
return slog.String("severity", severityFor(lvl))
}
return a
case slog.MessageKey:
if a.Value.Kind() == slog.KindString {
return slog.String("message", a.Value.String())
}
return a
default:
return a
}
},
})
return slog.New(WrapHandlerWithCloudTrace(base, projectID))
}
// severityFor maps slog levels to Cloud Logging LogSeverity names
// (slog says "WARN", Cloud Logging expects "WARNING").
func severityFor(l slog.Level) string {
switch {
case l >= slog.LevelError+4:
return "CRITICAL"
case l >= slog.LevelError:
return "ERROR"
case l >= slog.LevelWarn:
return "WARNING"
case l >= slog.LevelInfo:
return "INFO"
default:
return "DEBUG"
}
}
func (h *cloudLoggingHandler) Enabled(ctx context.Context, l slog.Level) bool {
return h.base.Enabled(ctx, l)
}
func (h *cloudLoggingHandler) Handle(ctx context.Context, r slog.Record) error {
target := h.base
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && h.projectID != "" {
target = target.WithAttrs([]slog.Attr{
slog.String("logging.googleapis.com/trace", fmt.Sprintf("projects/%s/traces/%s", h.projectID, sc.TraceID().String())),
slog.String("logging.googleapis.com/spanId", sc.SpanID().String()),
slog.Bool("logging.googleapis.com/trace_sampled", sc.IsSampled()),
})
}
for _, op := range h.ops {
target = op(target)
}
return target.Handle(ctx, r)
}
func (h *cloudLoggingHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return h.withOp(func(inner slog.Handler) slog.Handler { return inner.WithAttrs(attrs) })
}
func (h *cloudLoggingHandler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
return h.withOp(func(inner slog.Handler) slog.Handler { return inner.WithGroup(name) })
}
func (h *cloudLoggingHandler) withOp(op func(slog.Handler) slog.Handler) *cloudLoggingHandler {
ops := make([]func(slog.Handler) slog.Handler, len(h.ops)+1)
copy(ops, h.ops)
ops[len(h.ops)] = op
return &cloudLoggingHandler{base: h.base, ops: ops, projectID: h.projectID}
}
```
## 5. Generic port decorator for stage spans
```go
// file: telemetry/decorator.go
package telemetry
import (
"context"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
// Traced wraps any port call with a child span, keeping the domain package
// free of OpenTelemetry imports. Use one instance per logical stage
// (for example "db.insert", "validate", "db.commit"). Kind defaults to
// SpanKindInternal; set SpanKindClient for calls that leave the process
// (database, HTTP, gRPC).
type Traced[T any, R any] struct {
SpanName string
Tracer trace.Tracer
Kind trace.SpanKind
Attrs []attribute.KeyValue
Next func(ctx context.Context, in T) (R, error)
}
func (d *Traced[T, R]) Execute(ctx context.Context, in T) (R, error) {
kind := d.Kind
if kind == trace.SpanKindUnspecified {
kind = trace.SpanKindInternal
}
ctx, span := d.Tracer.Start(ctx, d.SpanName,
trace.WithSpanKind(kind),
trace.WithAttributes(d.Attrs...),
)
defer span.End()
res, err := d.Next(ctx, in)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return res, err
}
// Leave status Unset on success: the OpenTelemetry spec reserves Ok for an
// explicit application assertion, and Unset keeps the span overridable.
return res, nil
}
```
Example wrapping a repository port without importing OpenTelemetry in the
domain package:
```go
commit := &telemetry.Traced[*domain.Order, struct{}]{
SpanName: "db.insert orders",
Tracer: otel.Tracer("orders/adapters/db"),
Kind: trace.SpanKindClient,
Attrs: []attribute.KeyValue{attribute.String("db.system", "postgresql")},
Next: func(ctx context.Context, o *domain.Order) (struct{}, error) { return struct{}{}, repo.Save(ctx, o) },
}
```
## 6. TracerProvider: OTLP export, sampler, shutdown
```go
// file: telemetry/provider.go
package telemetry
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/oauth"
)
// ProviderConfig controls exporter and sampling for a service.
type ProviderConfig struct {
ProjectID string
ServiceName string
ServiceVersion string
// SampleRatio applies to root spans AND to spans whose remote parent is not
// sampled (for example requests entering through Cloud Run, which sets a
// traceparent with the sampled flag cleared for most requests). 1.0 in test,
// 0.05-0.2 in high-volume production.
SampleRatio float64
}
const telemetryEndpoint = "telemetry.googleapis.com:443"
// InitTracerProvider registers a global TracerProvider that exports spans over
// OTLP/gRPC to the Google Cloud Telemetry API (the supported path; the legacy
// Cloud Trace exporter package is deprecated) and a W3C TraceContext + Baggage
// propagator. Call the returned shutdown function after consumers have
// drained, before closing the database.
func InitTracerProvider(ctx context.Context, cfg ProviderConfig) (shutdown func(context.Context) error, err error) {
creds, err := oauth.NewApplicationDefault(ctx) // ADC: Workload Identity, SA key, or gcloud auth application-default login
if err != nil {
return nil, fmt.Errorf("load application default credentials: %w", err)
}
exporter, err := otlptracegrpc.New(ctx,
otlptracegrpc.WithEndpoint(telemetryEndpoint),
otlptracegrpc.WithTLSCredentials(credentials.NewClientTLSFromCert(nil, "")),
otlptracegrpc.WithDialOption(grpc.WithPerRPCCredentials(creds)),
otlptracegrpc.WithHeaders(map[string]string{"x-goog-user-project": cfg.ProjectID}),
)
if err != nil {
return nil, fmt.Errorf("create OTLP trace exporter: %w", err)
}
res, err := resource.New(ctx,
resource.WithAttributes(
semconv.ServiceName(cfg.ServiceName),
semconv.ServiceVersion(cfg.ServiceVersion),
attribute.String("gcp.project_id", cfg.ProjectID), // required by the Telemetry API
),
)
if err != nil {
return nil, fmt.Errorf("build resource: %w", err)
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exporter),
sdktrace.WithResource(res),
sdktrace.WithSampler(NewSampler(cfg.SampleRatio)),
)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{},
))
return tp.Shutdown, nil
}
// NewSampler returns a ParentBased sampler that honours an upstream *sampled*
// decision but applies ratio when the remote parent is NOT sampled. Without the
// second rule, ParentBased drops almost every request behind Cloud Run, whose
// frontend only marks ~0.1 request/s/instance as sampled.
func NewSampler(ratio float64) sdktrace.Sampler {
if ratio <= 0 || ratio > 1 {
ratio = 1
}
return sdktrace.ParentBased(
sdktrace.TraceIDRatioBased(ratio),
sdktrace.WithRemoteParentNotSampled(sdktrace.TraceIDRatioBased(ratio)),
)
}
```
Call `shutdown(ctx)` in the graceful-shutdown sequence after consumers drain
and before closing the database.
## 7. Deterministic unit tests with the in-memory exporter
Never contact Cloud Trace or require network/credentials in unit tests; assert
propagation and log correlation with `go.opentelemetry.io/otel/sdk/trace/tracetest`:
```go
func setupTestTracer(t *testing.T) (*tracetest.InMemoryExporter, trace.Tracer) {
t.Helper()
exp := tracetest.NewInMemoryExporter()
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp))
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
return exp, tp.Tracer("test-tracer")
}
```
Required unit-test assertions and Phase 4 checklist:
1. Inbound `traceparent`
`00-11111111111111111111111111111111-2222222222222222-01` (or
`googclient_traceparent`) yields a `SpanKindConsumer` span named
`process {subscription}` continuing `TraceID`
`11111111111111111111111111111111` and parent span ID `2222222222222222`.
2. Child stage spans share the trace ID; failing stages set `codes.Error` and
record the error; successful stages leave status `Unset`.
3. Logs emitted with context contain top-level `logging.googleapis.com/trace`
set to `projects/my-project/traces/11111111111111111111111111111111`,
`logging.googleapis.com/spanId`, `logging.googleapis.com/trace_sampled`,
and `severity` (`WARNING`, not `WARN`) even inside `WithGroup`.
4. Nil or empty attributes do not panic and start a root trace.
5. `NewSampler` samples remote-parent-not-sampled spans at `ratio` (Cloud Run)
and honours sampled remote parents.
6. Domain packages contain zero `go.opentelemetry.io` imports when clean
architecture applies.
solution-checklist.md 3.8 KB
# Solution checklist and hand-off template
Copy this table into the project runbook and update it at each phase gate.
| Phase | Owner | Artifacts left behind | Gate status |
| --- | --- | --- | --- |
| 0. Frame | Architect | Acceptance criteria, constraints (runtime, language, schema freeze, residency) | open / passed |
| 1. Assess | Architect + service team | Measured baseline (p99 per hop, pool saturation, lock waits), call graph, transaction cut, event catalog (`name`, `owner`, `idempotency_key`, `payload_owner`), outbox vs state-marker decision, bulkhead plan | open / passed |
| 2. Design messaging | Platform team | Topic and subscription inventory, filters, dead-letter policy, flow-control budgets per replica, claim-check decision, IAM matrix | open / passed |
| 3. Build consumers | Service team | Handler with ack/nack matrix tests, shutdown test (pool closes after `Receive` returns), HPA or Cloud Run settings, load-test evidence | open / passed |
| 4. Observe | Service team + SRE | Trace continuity test, log correlation sample, sampling policy per environment, dashboards for backlog and dead-letter count | open / passed |
| 5. Cut over | Service team | Dual-run comparison report, `{feature_flag}` removal change, `{soak_period}` dead-letter evidence | open / passed |
## Event catalog template (illustrative values)
| Event name | Producer | Consumers | Idempotency key | Payload size p99 | Delivery strategy | Owner |
| --- | --- | --- | --- | --- | --- | --- |
| `orders.order.created` | `{producer_service}` | `{consumer_a}`, `{consumer_b}` | `order_id` + `version` | `{p99_bytes}` | inline, filtered subscription | `{owning_team}` |
| `files.batch.finalized` | `{upload_service}` | `{importer_service}` | `object_generation` | `{p99_bytes}` (over 1 MB) | Cloud Storage claim-check | `{owning_team}` |
## Budget worksheet
Derive every number with Phase 2
(`references/phase2-pubsub-topology-and-sizing.md`, section 3 flow-control
sizing table) and Phase 3 (`references/phase3-consumer-and-autoscaling.md`,
section 6 HPA manifest); record the results as Phase 2 and Phase 3 artifacts.
Invariant at this level:
`per_replica_pool * max_replicas <= database_connection_budget`.
| Input | Value | Derived by |
| --- | --- | --- |
| Database connection budget for consumers | `{total_conns}` | you |
| Max consumer replicas | `{max_replicas}` | you, or derived from the two others |
| Per-replica pool (Go: `SetMaxOpenConns`) | `{pool}` | Phase 2 (`references/phase2-pubsub-topology-and-sizing.md`) |
| Max outstanding messages, bytes, lease cap, ack deadline | | Phase 2 (`references/phase2-pubsub-topology-and-sizing.md`) |
| HPA `averageValue`, `maxReplicas` | | Phase 3 (`references/phase3-consumer-and-autoscaling.md`) |
## How to run each validation check
1. **Independent failure**: stop the consumer during a burst; read producer
p99 from Cloud Trace or `run.googleapis.com/request_latencies`; watch
`pubsub.googleapis.com/subscription/num_undelivered_messages` grow; after
restart, compare row counts between the old and new paths.
2. **No dual writes**: inject a failure in the relay between commit and
publish; the event appears after the relay or sweeper runs; downstream
row counts show no duplicate side effect.
3. **Poison handling**: publish a malformed payload; it reaches the
dead-letter subscription after the configured attempts
(`subscription/dead_letter_message_count` > 0); healthy messages keep
flowing.
4. **Rolling restart under load**: zero cancelled-context errors (Go:
`context canceled`) in commit paths; zero duplicate side effects (duplicate
key rejections logged, no extra rows downstream).
5. **Trace continuity**: pick ten producer requests; each has one trace
through the consumer with correlated log lines
(`logging.googleapis.com/trace`).
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE