{"data":{"slug":"github-google-skills-skills-cloud-google-cloud-solution-event-driven-decoupling-1cd9cab1429b","title":"Decouple Services with Google Cloud Pub\/Sub","summary":"Decouples tightly coupled services or monoliths using Google Cloud Pub\/Sub for scalable, independent service operation, with a focus on transactional boundaries, bulkheads, and idempotent consumers.","url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-google-cloud-solution-event-driven-decoupling-1cd9cab1429b","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-google-skills-skills-cloud-google-cloud-solution-event-driven-decoupling-1cd9cab1429b","markdown_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-google-cloud-solution-event-driven-decoupling-1cd9cab1429b.md","download_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-google-cloud-solution-event-driven-decoupling-1cd9cab1429b\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before executing any `gcloud`, REST API, or MCP command, you must read and follow the instructions in [Usage Attribution](references\/attribution.md). Use the Google Cloud CLI and, for GKE, `kubectl`. Never install host tools or grant IAM bindings without explicit user approval. Ensure billing is attached to `{project_id}` and APIs are enabled.","instructions":"---\nname: google-cloud-solution-event-driven-decoupling\nmetadata:\n  version: \"1.0.0\"\n  category: MultiProductSolutions\ndescription: >-\n  Decouples tightly coupled services or monoliths with Google Cloud Pub\/Sub so\n  services scale and fail independently, using Go reference implementations\n  adaptable to Java, Python, Node.js, and other stacks. Use when breaking apart\n  synchronous chains, defining transaction boundaries, bulkheads, and\n  Transactional Outbox or post-commit publishing; sizing Pub\/Sub topics,\n  subscription filters, dead-letter policies, backoff, 10 MB Cloud Storage\n  claim-check, or database-bounded flow control; building idempotent consumers\n  with ack\/nack\/quarantine handling, SIGTERM draining, GKE HPA, Cloud Run push,\n  Eventarc, or Cloud Run functions (--retry); or instrumenting OpenTelemetry W3C\n  Trace Context across HTTP, gRPC, and Pub\/Sub with Cloud Trace OTLP export and\n  Cloud Logging correlation. Don't use for querying existing traces (use\n  cloud-trace-querying), Kafka or non-Google brokers, or orchestration engines\n  such as Workflows or Managed Service for Apache Airflow.\n---\n\n# Event-driven decoupling with Pub\/Sub\n\nBreak a distributed monolith or tightly coupled service chain apart with\nasynchronous messaging on Pub\/Sub so services scale and fail independently.\nThis skill uses **progressive disclosure** across **Phases 0\u20135** (with Phase 0\ninline below and modular `references\/` files for Phases 1\u20135): run the full\nend-to-end migration sequence for architecture journeys, or load **only** the\nsingle phase reference needed for a focused design, code, or troubleshooting\nrequest.\n\n## Usage Attribution\n\n**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you\nMUST read and follow the instructions in\n[Usage Attribution](references\/attribution.md).\n\n## Progressive disclosure: load only the phase you need\n\n| Phase & module | Reference to load | Produces | Load when |\n| --- | --- | --- | --- |\n| **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 |\n| **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 |\n| **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\u201310 MB; or fixing DLQ delivery |\n| **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 |\n| **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 |\n| **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 |\n\n**Routing rules**:\n\n-   **End-to-end requests**: run Phases 0\u20135 sequentially, loading each phase's\n    reference only when that phase begins. Two exceptions apply:\n    -   *Greenfield consumers*: run Phases 3 and 4 together so new consumers\n        ship with distributed tracing from day one.\n    -   *Missing observability*: if the user's primary problem is missing\n        latency visibility or absent distributed traces, run Phase 4\n        ([references\/phase4-distributed-tracing.md](references\/phase4-distributed-tracing.md))\n        first to establish a trace baseline before proposing Pub\/Sub changes,\n        then resume Phases 1\u20133.\n-   **Focused single-phase requests**: load **only** the matching phase\n    reference, name which phase file applies, and never dump unrelated phases:\n    -   *Flow-control \/ subscription configuration questions*\n        (`MaxOutstandingMessages`, ack deadline, `max-delivery-attempts`,\n        backoff): load **only** Phase 2\n        ([references\/phase2-pubsub-topology-and-sizing.md](references\/phase2-pubsub-topology-and-sizing.md)).\n        Relate flow control to the database connection pool and ack deadline to\n        the per-message processing timeout; do **not** present the Phase 1\n        coupling matrix, Transactional Outbox, or Phase 3 consumer handler code.\n    -   *Consumer handler ack\/nack questions*: load **only** Phase 3\n        ([references\/phase3-consumer-and-autoscaling.md](references\/phase3-consumer-and-autoscaling.md)).\n        Provide the handler logic (never provisioning commands alone) and note\n        that the subscription ack deadline must exceed the handler's processing\n        timeout.\n-   **Non-Go languages and other SQL engines**: Phases 1, 3, and 4 provide\n    compiled Go (`cloud.google.com\/go\/pubsub\/v2`, `database\/sql`, OpenTelemetry\n    Go) and PostgreSQL reference code, while Phase 2 maps flow-control fields\n    across Go, Python, Java, and Node.js. When the user's workload uses another\n    language (such as Java, Python, or Node.js) or database (such as MySQL or\n    Oracle), keep every architectural invariant and phase gate unchanged,\n    translate the patterns into idiomatic SDK and SQL constructs for the\n    requested stack, and state explicitly that you are adapting the Go reference\n    patterns.\n\n## Prerequisites\n\nUse the Google Cloud CLI (install guide:\nhttps:\/\/docs.cloud.google.com\/sdk\/docs\/install-sdk.md.txt) and, for GKE,\n`kubectl`. Never install host tools or grant IAM bindings without explicit user\napproval: both alter the user's host or production access. If `gcloud` is\nunavailable, produce design artifacts, code, Kubernetes YAML, or Terraform\ndirectly.\n\n1.  **Billing** is attached to `{project_id}`. Pub\/Sub, Cloud Trace, and Cloud\n    Logging have free allotments, but an active billing account is still\n    required (https:\/\/cloud.google.com\/pricing,\n    https:\/\/cloud.google.com\/pubsub\/pricing,\n    https:\/\/cloud.google.com\/run\/pricing,\n    https:\/\/cloud.google.com\/kubernetes-engine\/pricing,\n    https:\/\/cloud.google.com\/stackdriver\/pricing).\n2.  **Project, region, authentication, and APIs** (default `us-central1`,\n    https:\/\/cloud.google.com\/about\/locations):\n\n    ```bash\n    gcloud config set project {project_id}\n    gcloud config set compute\/region {region}\n    gcloud auth login                            # Local CLI\n    gcloud auth application-default login        # SDK \/ ADC; workloads use Workload Identity Federation for GKE or GOOGLE_APPLICATION_CREDENTIALS\n    gcloud services enable pubsub.googleapis.com cloudtrace.googleapis.com telemetry.googleapis.com logging.googleapis.com monitoring.googleapis.com\n    # Add per workload: cloudprofiler.googleapis.com (Phase 1), storage.googleapis.com (claim-check),\n    # container.googleapis.com (GKE, default), or run.googleapis.com eventarc.googleapis.com cloudfunctions.googleapis.com (Cloud Run)\n    ```\n\n3.  **Least-privilege IAM**: one service account per producer and consumer;\n    never `roles\/editor` (*why:* basic roles grant project-wide write across\n    every service).\n\n    | Principal | Role | Scope | Phase |\n    | --- | --- | --- | --- |\n    | Assessor identity (read-only) | `roles\/cloudtrace.user`, `roles\/monitoring.viewer`, `roles\/cloudprofiler.user` | `{project_id}` | 1 |\n    | Producer service account | `roles\/pubsub.publisher` (`+ roles\/storage.objectCreator` on `{claim_check_bucket}` if claim-check) | `{topic_id}` | 2 |\n    | Consumer service account | `roles\/pubsub.subscriber` (`+ roles\/storage.objectViewer` on `{claim_check_bucket}` if claim-check) | `{subscription_id}` | 2\u20133 |\n    | 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 |\n    | Metrics adapter (`custom-metrics-stackdriver-adapter`) | `roles\/monitoring.viewer` | `{project_id}` | 3 |\n    | Push \/ Eventarc trigger service account (Cloud Run path) | `roles\/run.invoker`, `roles\/eventarc.eventReceiver` | service \/ trigger | 3 |\n    | Producer and consumer service accounts | `roles\/telemetry.tracesWriter`, `roles\/logging.logWriter` | `{project_id}` | 4 |\n\n## End-to-end workflow and phase gates\n\n1.  **Phase 0 - Frame the goal**: capture the business outcome (independent\n    scaling, isolated failure, shorter p99, removable batch windows) and\n    constraints (schema freeze, language, runtime GKE vs Cloud Run, data\n    residency) as measurable acceptance criteria before designing.\n2.  **Phase 1 - Assess** ([phase1-coupling-assessment.md](references\/phase1-coupling-assessment.md),\n    [phase1-outbox-and-bulkheads-go.md](references\/phase1-outbox-and-bulkheads-go.md)).\n    **Gate**: baseline p99 latency, connection saturation, and lock-wait\n    numbers recorded per hop; every outbound event has a name, owning team,\n    idempotency key, and Transactional Outbox vs state-marker decision; zero\n    network calls remain inside a database transaction. **Gate enforcement**:\n    if the user claims assessment is finished and asks for `gcloud` topic or\n    subscription creation commands while only naming events without confirming\n    those Phase 1 gate items, **do not** emit `gcloud pubsub topics create` or\n    `subscriptions create` commands and **do not** invent payload schemas or\n    owners; ask to confirm the missing Phase 1 gate items first and state that\n    Phase 2\n    ([references\/phase2-pubsub-topology-and-sizing.md](references\/phase2-pubsub-topology-and-sizing.md))\n    is the next step once the gate is met.\n3.  **Phase 2 - Design messaging** ([phase2-pubsub-topology-and-sizing.md](references\/phase2-pubsub-topology-and-sizing.md)).\n    **Gate**: per-replica flow control derived from the database pool;\n    dead-letter topic paired with its own pull subscription and both Pub\/Sub\n    service-agent IAM bindings; Cloud Storage claim-check decision for any\n    payload that can exceed 1 MB (Pub\/Sub hard limit: 10 MB).\n4.  **Phase 3 - Build consumers** ([phase3-consumer-and-autoscaling.md](references\/phase3-consumer-and-autoscaling.md)).\n    **Gate**: unit tests for every branch of the ack\/nack\/quarantine matrix;\n    shutdown test proving the database pool closes strictly after `Receive`\n    returns and in-flight commits finish; GKE HPA `maxReplicas` or Cloud Run\n    concurrency capped within the database connection budget.\n5.  **Phase 4 - Observe** ([phase4-distributed-tracing.md](references\/phase4-distributed-tracing.md)).\n    **Gate**: one continuous trace ID from producer request through Pub\/Sub to\n    consumer database stages, structured logs correlated via\n    `logging.googleapis.com\/trace`, explicit sampling policy per environment.\n6.  **Phase 5 - Cut over incrementally**: Strangler pattern per event type.\n    Dual-run (synchronous path plus event) behind `{feature_flag}` so a single\n    flip restores the synchronous call, compare outcomes, and remove the\n    synchronous call only after `{dlq_subscription_id}` stays empty for\n    `{soak_period}` (default: one full business cycle, at least 7 days).\n7.  **Validate \u2192 fix \u2192 repeat**: re-verify all phase gates post-cut-over using\n    [solution-checklist.md](references\/solution-checklist.md).\n\n## Cross-cutting rules and scope boundaries\n\n-   **One default, one escape hatch per decision**: every phase names one\n    default and one escape hatch; do not add a third option.\n-   **Idempotency is non-negotiable**: Pub\/Sub delivers at least once. Every\n    consumer deduplicates on an event ID or natural key before side effects and\n    **acks** duplicates (nacking duplicates loops valid data into the DLQ).\n-   **Budgets flow downstream**: database connection budget \u2192 per-replica pool\n    \u2192 `MaxOutstandingMessages` \u2192 HPA `maxReplicas`. Enforce the invariant\n    `per_replica_pool * max_replicas <= database_connection_budget` (derive\n    whichever of the three values is unknown, tie HPA `maxReplicas` to that\n    budget, never leave client flow-control defaults of 1000 messages \/ 1 GiB\n    in place, and derive per-replica flow control with Phase 2\n    ([references\/phase2-pubsub-topology-and-sizing.md](references\/phase2-pubsub-topology-and-sizing.md))\n    and the HPA manifest with Phase 3\n    ([references\/phase3-consumer-and-autoscaling.md](references\/phase3-consumer-and-autoscaling.md))).\n-   **Never leave a dead-letter topic without a subscription**: it silently\n    discards messages; alert on `subscription\/dead_letter_message_count`.\n-   **Other brokers (Kafka, RabbitMQ, SQS, self-managed queues)**: state\n    plainly that this skill is specific to Google Cloud Pub\/Sub, offer only\n    broker-agnostic principles explicitly labeled as such (or redirect to\n    broker-specific docs), never present Pub\/Sub flags, flow-control settings,\n    or fabricated `gcloud` commands as Kafka config, and never suggest\n    migrating to Pub\/Sub as the answer to a Kafka tuning question.\n-   **Synchronous HTTP\/gRPC-only services (no Pub\/Sub)**: load only Phase 4\n    (`TracerProvider` + Cloud Run `WithRemoteParentNotSampled` sampler,\n    `otelhttp`, `otelgrpc` stats handlers, DB stage spans, `slog` correlation);\n    never introduce Pub\/Sub topics or message carriers.\n-   **Querying existing traces** (*\"find traces slower than 2s\"*): state that\n    this is a Cloud Trace query task rather than instrumentation; point to the\n    Cloud Trace console\/API\n    (https:\/\/docs.cloud.google.com\/trace\/docs\/finding-traces.md.txt) or the\n    `cloud-trace-querying` skill. Never emit OpenTelemetry SDK setup code,\n    never require re-instrumenting first, and never invent a trace query DSL.\n-   **Orchestration engines & sagas**: Workflows, Managed Service for Apache\n    Airflow (`managed-airflow-*`), Application Integration\n    (`application-integration-basics`), and multi-service compensating sagas\n    are out of scope; keep each aggregate's state change in one transaction.\n\n## Validation checklist\n\n-   [ ] Producer and consumer deploy, scale, and fail independently: with the\n    consumer stopped, producer p99 is unchanged, `num_undelivered_messages`\n    grows, and the backlog drains on restart with matching row counts.\n-   [ ] No dual writes: a fault injected between commit and publish is\n    recovered by the outbox relay or sweeper with zero duplicate side effects.\n-   [ ] A malformed message lands in `{dlq_subscription_id}` after\n    `max-delivery-attempts` (or in quarantine when chosen) while healthy\n    messages keep flowing (`subscription\/dead_letter_message_count` > 0).\n-   [ ] Rolling consumer restarts under load produce zero `context canceled`\n    commits and zero duplicate side effects.\n-   [ ] One trace ID links producer request, Pub\/Sub hop, consumer processing,\n    and database stages, with `logging.googleapis.com\/trace` on log lines.\n-   [ ] Every acceptance criterion names an observable signal (metric, log\n    field, row count, or test assertion), never a qualitative claim like\n    *\"services are decoupled\"*.\n\n## Resource cleanup\n\nRemove **only temporary test or dual-run resources** in a non-production\nproject. Before running or proposing any delete command after a migration,\nexplicitly ask the user to confirm the exact test resource names and\n`{test_project_id}`, distinguish test\/dual-run resources from live production\ntopics and subscriptions, and **never** delete production resources carrying\nlive traffic:\n\n```bash\ngcloud pubsub subscriptions delete {test_subscription_id} --project={test_project_id}\ngcloud pubsub topics delete {test_topic_id} --project={test_project_id}\n```\n","use_cases":["Breaking apart synchronous chains between services","Defining transaction boundaries and bulkheads","Implementing Transactional Outbox or post-commit publishing","Sizing Pub\/Sub topics and subscription filters","Building idempotent consumers with ack\/nack handling"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/google\/skills\/blob\/c413c1fdc1714f2e4ae44a449b9744348197119c\/skills\/cloud\/google-cloud-solution-event-driven-decoupling\/SKILL.md","source_commit":"c413c1fdc1714f2e4ae44a449b9744348197119c","license":null,"version":null,"listing_approved_at":"2026-11-27","created_at":"2026-11-26T11:10:42.000000Z","updated_at":"2026-11-27T07:43:08.000000Z","seo_title":"Decouple Services with Google Cloud Pub\/Sub","seo_description":"Decouple tightly coupled services using Google Cloud Pub\/Sub for scalable, independent service operation and fault isolation, with support for transactional outbox, idemp","seo_keywords":["Decouple services with Google Cloud Pub\/Sub","Pub\/Sub for service decoupling","Cloud Pub\/Sub event-driven architecture","Transactional Outbox with Pub\/Sub","Cloud Run and Pub\/Sub integration"]}}