1
---
2
name: google-cloud-solution-event-driven-decoupling
3
metadata:
4
version: "1.0.0"
5
category: MultiProductSolutions
6
description: >-
7
Decouples tightly coupled services or monoliths with Google Cloud Pub/Sub so
8
services scale and fail independently, using Go reference implementations
9
adaptable to Java, Python, Node.js, and other stacks. Use when breaking apart
10
synchronous chains, defining transaction boundaries, bulkheads, and
11
Transactional Outbox or post-commit publishing; sizing Pub/Sub topics,
12
subscription filters, dead-letter policies, backoff, 10 MB Cloud Storage
13
claim-check, or database-bounded flow control; building idempotent consumers
14
with ack/nack/quarantine handling, SIGTERM draining, GKE HPA, Cloud Run push,
15
Eventarc, or Cloud Run functions (--retry); or instrumenting OpenTelemetry W3C
16
Trace Context across HTTP, gRPC, and Pub/Sub with Cloud Trace OTLP export and
17
Cloud Logging correlation. Don't use for querying existing traces (use
18
cloud-trace-querying), Kafka or non-Google brokers, or orchestration engines
19
such as Workflows or Managed Service for Apache Airflow.
20
---
21
22
# Event-driven decoupling with Pub/Sub
23
24
Break a distributed monolith or tightly coupled service chain apart with
25
asynchronous messaging on Pub/Sub so services scale and fail independently.
26
This skill uses **progressive disclosure** across **Phases 0–5** (with Phase 0
27
inline below and modular `references/` files for Phases 1–5): run the full
28
end-to-end migration sequence for architecture journeys, or load **only** the
29
single phase reference needed for a focused design, code, or troubleshooting
30
request.
31
32
## Usage Attribution
33
34
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
35
MUST read and follow the instructions in
36
[Usage Attribution](references/attribution.md).
37
38
## Progressive disclosure: load only the phase you need
39
40
| Phase & module | Reference to load | Produces | Load when |
41
| --- | --- | --- | --- |
42
| **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 |
43
| **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 |
44
| **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 |
45
| **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 |
46
| **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 |
47
| **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 |
48
49
**Routing rules**:
50
51
- **End-to-end requests**: run Phases 0–5 sequentially, loading each phase's
52
reference only when that phase begins. Two exceptions apply:
53
- *Greenfield consumers*: run Phases 3 and 4 together so new consumers
54
ship with distributed tracing from day one.
55
- *Missing observability*: if the user's primary problem is missing
56
latency visibility or absent distributed traces, run Phase 4
57
([references/phase4-distributed-tracing.md](references/phase4-distributed-tracing.md))
58
first to establish a trace baseline before proposing Pub/Sub changes,
59
then resume Phases 1–3.
60
- **Focused single-phase requests**: load **only** the matching phase
61
reference, name which phase file applies, and never dump unrelated phases:
62
- *Flow-control / subscription configuration questions*
63
(`MaxOutstandingMessages`, ack deadline, `max-delivery-attempts`,
64
backoff): load **only** Phase 2
65
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md)).
66
Relate flow control to the database connection pool and ack deadline to
67
the per-message processing timeout; do **not** present the Phase 1
68
coupling matrix, Transactional Outbox, or Phase 3 consumer handler code.
69
- *Consumer handler ack/nack questions*: load **only** Phase 3
70
([references/phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md)).
71
Provide the handler logic (never provisioning commands alone) and note
72
that the subscription ack deadline must exceed the handler's processing
73
timeout.
74
- **Non-Go languages and other SQL engines**: Phases 1, 3, and 4 provide
75
compiled Go (`cloud.google.com/go/pubsub/v2`, `database/sql`, OpenTelemetry
76
Go) and PostgreSQL reference code, while Phase 2 maps flow-control fields
77
across Go, Python, Java, and Node.js. When the user's workload uses another
78
language (such as Java, Python, or Node.js) or database (such as MySQL or
79
Oracle), keep every architectural invariant and phase gate unchanged,
80
translate the patterns into idiomatic SDK and SQL constructs for the
81
requested stack, and state explicitly that you are adapting the Go reference
82
patterns.
83
84
## Prerequisites
85
86
Use the Google Cloud CLI (install guide:
87
https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt) and, for GKE,
88
`kubectl`. Never install host tools or grant IAM bindings without explicit user
89
approval: both alter the user's host or production access. If `gcloud` is
90
unavailable, produce design artifacts, code, Kubernetes YAML, or Terraform
91
directly.
92
93
1. **Billing** is attached to `{project_id}`. Pub/Sub, Cloud Trace, and Cloud
94
Logging have free allotments, but an active billing account is still
95
required (https://cloud.google.com/pricing,
96
https://cloud.google.com/pubsub/pricing,
97
https://cloud.google.com/run/pricing,
98
https://cloud.google.com/kubernetes-engine/pricing,
99
https://cloud.google.com/stackdriver/pricing).
100
2. **Project, region, authentication, and APIs** (default `us-central1`,
101
https://cloud.google.com/about/locations):
102
103
```bash
104
gcloud config set project {project_id}
105
gcloud config set compute/region {region}
106
gcloud auth login # Local CLI
107
gcloud auth application-default login # SDK / ADC; workloads use Workload Identity Federation for GKE or GOOGLE_APPLICATION_CREDENTIALS
108
gcloud services enable pubsub.googleapis.com cloudtrace.googleapis.com telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com
109
# Add per workload: cloudprofiler.googleapis.com (Phase 1), storage.googleapis.com (claim-check),
110
# container.googleapis.com (GKE, default), or run.googleapis.com eventarc.googleapis.com cloudfunctions.googleapis.com (Cloud Run)
111
```
112
113
3. **Least-privilege IAM**: one service account per producer and consumer;
114
never `roles/editor` (*why:* basic roles grant project-wide write across
115
every service).
116
117
| Principal | Role | Scope | Phase |
118
| --- | --- | --- | --- |
119
| Assessor identity (read-only) | `roles/cloudtrace.user`, `roles/monitoring.viewer`, `roles/cloudprofiler.user` | `{project_id}` | 1 |
120
| Producer service account | `roles/pubsub.publisher` (`+ roles/storage.objectCreator` on `{claim_check_bucket}` if claim-check) | `{topic_id}` | 2 |
121
| Consumer service account | `roles/pubsub.subscriber` (`+ roles/storage.objectViewer` on `{claim_check_bucket}` if claim-check) | `{subscription_id}` | 2–3 |
122
| 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 |
123
| Metrics adapter (`custom-metrics-stackdriver-adapter`) | `roles/monitoring.viewer` | `{project_id}` | 3 |
124
| Push / Eventarc trigger service account (Cloud Run path) | `roles/run.invoker`, `roles/eventarc.eventReceiver` | service / trigger | 3 |
125
| Producer and consumer service accounts | `roles/telemetry.tracesWriter`, `roles/logging.logWriter` | `{project_id}` | 4 |
126
127
## End-to-end workflow and phase gates
128
129
1. **Phase 0 - Frame the goal**: capture the business outcome (independent
130
scaling, isolated failure, shorter p99, removable batch windows) and
131
constraints (schema freeze, language, runtime GKE vs Cloud Run, data
132
residency) as measurable acceptance criteria before designing.
133
2. **Phase 1 - Assess** ([phase1-coupling-assessment.md](references/phase1-coupling-assessment.md),
134
[phase1-outbox-and-bulkheads-go.md](references/phase1-outbox-and-bulkheads-go.md)).
135
**Gate**: baseline p99 latency, connection saturation, and lock-wait
136
numbers recorded per hop; every outbound event has a name, owning team,
137
idempotency key, and Transactional Outbox vs state-marker decision; zero
138
network calls remain inside a database transaction. **Gate enforcement**:
139
if the user claims assessment is finished and asks for `gcloud` topic or
140
subscription creation commands while only naming events without confirming
141
those Phase 1 gate items, **do not** emit `gcloud pubsub topics create` or
142
`subscriptions create` commands and **do not** invent payload schemas or
143
owners; ask to confirm the missing Phase 1 gate items first and state that
144
Phase 2
145
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md))
146
is the next step once the gate is met.
147
3. **Phase 2 - Design messaging** ([phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md)).
148
**Gate**: per-replica flow control derived from the database pool;
149
dead-letter topic paired with its own pull subscription and both Pub/Sub
150
service-agent IAM bindings; Cloud Storage claim-check decision for any
151
payload that can exceed 1 MB (Pub/Sub hard limit: 10 MB).
152
4. **Phase 3 - Build consumers** ([phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md)).
153
**Gate**: unit tests for every branch of the ack/nack/quarantine matrix;
154
shutdown test proving the database pool closes strictly after `Receive`
155
returns and in-flight commits finish; GKE HPA `maxReplicas` or Cloud Run
156
concurrency capped within the database connection budget.
157
5. **Phase 4 - Observe** ([phase4-distributed-tracing.md](references/phase4-distributed-tracing.md)).
158
**Gate**: one continuous trace ID from producer request through Pub/Sub to
159
consumer database stages, structured logs correlated via
160
`logging.googleapis.com/trace`, explicit sampling policy per environment.
161
6. **Phase 5 - Cut over incrementally**: Strangler pattern per event type.
162
Dual-run (synchronous path plus event) behind `{feature_flag}` so a single
163
flip restores the synchronous call, compare outcomes, and remove the
164
synchronous call only after `{dlq_subscription_id}` stays empty for
165
`{soak_period}` (default: one full business cycle, at least 7 days).
166
7. **Validate → fix → repeat**: re-verify all phase gates post-cut-over using
167
[solution-checklist.md](references/solution-checklist.md).
168
169
## Cross-cutting rules and scope boundaries
170
171
- **One default, one escape hatch per decision**: every phase names one
172
default and one escape hatch; do not add a third option.
173
- **Idempotency is non-negotiable**: Pub/Sub delivers at least once. Every
174
consumer deduplicates on an event ID or natural key before side effects and
175
**acks** duplicates (nacking duplicates loops valid data into the DLQ).
176
- **Budgets flow downstream**: database connection budget → per-replica pool
177
→ `MaxOutstandingMessages` → HPA `maxReplicas`. Enforce the invariant
178
`per_replica_pool * max_replicas <= database_connection_budget` (derive
179
whichever of the three values is unknown, tie HPA `maxReplicas` to that
180
budget, never leave client flow-control defaults of 1000 messages / 1 GiB
181
in place, and derive per-replica flow control with Phase 2
182
([references/phase2-pubsub-topology-and-sizing.md](references/phase2-pubsub-topology-and-sizing.md))
183
and the HPA manifest with Phase 3
184
([references/phase3-consumer-and-autoscaling.md](references/phase3-consumer-and-autoscaling.md))).
185
- **Never leave a dead-letter topic without a subscription**: it silently
186
discards messages; alert on `subscription/dead_letter_message_count`.
187
- **Other brokers (Kafka, RabbitMQ, SQS, self-managed queues)**: state
188
plainly that this skill is specific to Google Cloud Pub/Sub, offer only
189
broker-agnostic principles explicitly labeled as such (or redirect to
190
broker-specific docs), never present Pub/Sub flags, flow-control settings,
191
or fabricated `gcloud` commands as Kafka config, and never suggest
192
migrating to Pub/Sub as the answer to a Kafka tuning question.
193
- **Synchronous HTTP/gRPC-only services (no Pub/Sub)**: load only Phase 4
194
(`TracerProvider` + Cloud Run `WithRemoteParentNotSampled` sampler,
195
`otelhttp`, `otelgrpc` stats handlers, DB stage spans, `slog` correlation);
196
never introduce Pub/Sub topics or message carriers.
197
- **Querying existing traces** (*"find traces slower than 2s"*): state that
198
this is a Cloud Trace query task rather than instrumentation; point to the
199
Cloud Trace console/API
200
(https://docs.cloud.google.com/trace/docs/finding-traces.md.txt) or the
201
`cloud-trace-querying` skill. Never emit OpenTelemetry SDK setup code,
202
never require re-instrumenting first, and never invent a trace query DSL.
203
- **Orchestration engines & sagas**: Workflows, Managed Service for Apache
204
Airflow (`managed-airflow-*`), Application Integration
205
(`application-integration-basics`), and multi-service compensating sagas
206
are out of scope; keep each aggregate's state change in one transaction.
207
208
## Validation checklist
209
210
- [ ] Producer and consumer deploy, scale, and fail independently: with the
211
consumer stopped, producer p99 is unchanged, `num_undelivered_messages`
212
grows, and the backlog drains on restart with matching row counts.
213
- [ ] No dual writes: a fault injected between commit and publish is
214
recovered by the outbox relay or sweeper with zero duplicate side effects.
215
- [ ] A malformed message lands in `{dlq_subscription_id}` after
216
`max-delivery-attempts` (or in quarantine when chosen) while healthy
217
messages keep flowing (`subscription/dead_letter_message_count` > 0).
218
- [ ] Rolling consumer restarts under load produce zero `context canceled`
219
commits and zero duplicate side effects.
220
- [ ] One trace ID links producer request, Pub/Sub hop, consumer processing,
221
and database stages, with `logging.googleapis.com/trace` on log lines.
222
- [ ] Every acceptance criterion names an observable signal (metric, log
223
field, row count, or test assertion), never a qualitative claim like
224
*"services are decoupled"*.
225
226
## Resource cleanup
227
228
Remove **only temporary test or dual-run resources** in a non-production
229
project. Before running or proposing any delete command after a migration,
230
explicitly ask the user to confirm the exact test resource names and
231
`{test_project_id}`, distinguish test/dual-run resources from live production
232
topics and subscriptions, and **never** delete production resources carrying
233
live traffic:
234
235
```bash
236
gcloud pubsub subscriptions delete {test_subscription_id} --project={test_project_id}
237
gcloud pubsub topics delete {test_topic_id} --project={test_project_id}
238
```
239