# Go Microservice Architecture

> Use when designing, reviewing, or explaining a new product's Go backend or microservice architecture using Kitex or similar RPC, Hertz or similar HTTP gateway, protobuf IDL, MySQL/GORM-style relational storage, Redis cache/locks/rate limiting, service discovery, dynamic config, message queues, observability, DI, and code generation. Product-agnostic; do not depend on existing codebase paths, serv…

- **Type:** Skill
- **Install:** `agentstack add skill-ccoalm-ccl-skills-go-microservice-architecture`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [ccoalm](https://agentstack.voostack.com/s/ccoalm)
- **Installs:** 0
- **Category:** [Databases](https://agentstack.voostack.com/c/databases)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [ccoalm](https://github.com/ccoalm)
- **Source:** https://github.com/ccoalm/ccl-skills/tree/main/skills/go-microservice-architecture

## Install

```sh
agentstack add skill-ccoalm-ccl-skills-go-microservice-architecture
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Go Microservice Architecture

Use this for new product/server architecture work. It distills proven backend patterns but must not assume any existing repository, service identifier, package path, database, or legacy service layout.

## Skill Routing

- Use this skill for architecture decisions, service decomposition, API/RPC contract shape, storage ownership, async workflow design, observability, reliability, and launch readiness.
- Use `product-rd-workflow` first when the request spans product shaping, architecture, implementation, review, release, and learning loops rather than architecture alone.
- Use `go-microservice-dev` when the user asks to implement, modify, debug, test, scaffold, or generate code. A localized refactor (某文件/某类) also belongs to `go-microservice-dev`; only service-wide layering/boundary redesign stays here, and a multi-stage / cross-module refactor delivery must re-enter `product-rd-workflow`. An unqualified whole-service "Go 服务重构" enters here by default, mirroring the Python pair — do not let the unqualified form fall to the implementation skill.
- Use `python-service-architecture` for Python services. Do not load Python rules for Go work unless the task is explicitly cross-language contract design.
- Use `platform-observability` for logs/metrics/traces/log-id propagation/dashboards/alerts/SLI-SLO design. This skill owns only the service-side observability surface (Kitex/Hertz middleware that emits structured logs, OTel SDK use, baseline labels attached by metrics client, health endpoints); the cross-cutting evidence stack belongs there.
- Use `platform-service-connectivity` for service mesh, service discovery (Nacos/Consul/equivalent), mTLS, multi-environment lane routing, retry/timeout/circuit-breaker policy, and the canonical RPC base struct shape. This skill defines what the service exposes (framework default options usage, request-metadata propagation conformance via the platform's chosen carrier — in-message `base` or transport metadata, scenario-driven per the connectivity Carrier decision — graceful shutdown); mesh policy and routing rules live there.
- Use `platform-release-engineering` for environment/lane matrix, canary/blue-green, promotion gates, rollback playbook, secret distribution, dynamic-config (config-center) vs static-config split, image build pipeline. This skill owns the service-side contracts (config schema, secret consumption interface, registration metadata); release flow lives there.
- Use codebase-specific skills only when the task is explicitly about an existing legacy/workspace repository.
- Architecture references should define decision criteria, invariants, ownership boundaries, and acceptance checks. Put concrete code patterns, helper APIs, and test mechanics in `go-microservice-dev`.
- When changing an architecture rule that implementation must obey, name the downstream execution owner before landing: `go-microservice-dev` for code mechanics, `testing-strategy` for proof layer, platform skills for runtime contracts, and `product-rd-workflow` for cross-stage gates. If the rule also applies outside Go, route through `skill-extraction-workflow` and mirror or explicitly skip sibling architecture/dev skills.
- For money, billing, quota, permission, tenant/user data isolation, privacy, high-impact AI, repeated writes, async finality, or incident-explanation risk, start from `product-rd-workflow` and its high-risk resilience gate before choosing service boundaries or fallback behavior.

## Platform Boundary

This skill owns the **service-internal** view: layer separation (transport/application/domain/infra), protobuf IDL design, DAL boundaries, MQ consumer shape, error-code contract, DI/Wire generation. It exposes a fixed contract to the platform layer:

| Service exposes (this skill owns) | Platform owns (route to platform-* skill) |
|---|---|
| `/healthz`, `/readyz`, `/ping` endpoints (via framework default) | Orchestrator probes; registry healthcheck contract |
| Use of framework default server suite + client suite (e.g. Kitex/Hertz `Default*Options`, or equivalent) | What that middleware chain must include — see `platform-observability` and `platform-service-connectivity` |
| Conformance to the platform's request-metadata envelope (request id / correlation id / lane / caller identity), populated by client middleware | Cross-language contract on the envelope shape |
| `context.Context` carrying correlation id, trace context, lane/env, deadline through every hop; helper to clone-without-cancel for spawned goroutines | How those fields propagate across mesh / queue / async boundaries |
| Structured logger interface that emits JSON with the platform field schema (trace context extracted from ctx automatically) | Log shipping pipeline, search index |
| Stable error-code enum + framework error mapping (timeouts, panics, permission errors → typed codes) | Cross-service error contract evolution |
| Graceful shutdown: deregister from SD → drain → close clients → exit | Orchestrator pre-stop hook and termination grace |
| Secret consumption via platform secret-store SDK; never read from committed files | Secret rotation pipeline, secret-store deployment |
| Static config in per-environment files bundled in the image; dynamic config via config-center SDK | Config-center deployment, audit, rollout |
| Service registration metadata: platform service identifier, lane tag, region/cluster tags, version, weight | Registry deployment, federation, healthcheck propagation |
| Metric emission via framework metrics client with baseline labels auto-attached | Metric storage, cardinality budget, SLI definition |

A Go service author works against this contract. Platform-level questions ("which mesh policy?", "which collector?", "which canary weight?") route to the platform skills. Cross-language uniformity is what makes the platform layer reusable.

## Generalization Discipline

- Keep only reusable server-side mechanics: contracts, layers, storage ownership, config, reliability, observability, security boundaries, code generation, and delivery workflow.
- Do not copy product nouns, service names, package paths, provider names, environment names, IDs, dashboards, callback types, or organization-specific operating habits into the architecture.
- When source code shows a domain-specific concept, generalize it to `domain object`, `resource`, `authorization scope`, `integration scope`, or `workflow` only if the mechanic is reusable; otherwise discard it.
- When patterns conflict, choose deliberately:
  - Prefer current contracts and requirements over historical code habits.
  - Prefer relational durable truth over Redis-only truth for auditable state.
  - Prefer explicit protobuf/config/schema contracts over reflection, hidden globals, or stringly conventions.
  - Prefer idempotency and durable acceptance over retry-only designs.
  - Prefer fail-closed for auth, permission, critical state transitions, and data-integrity paths; fail-open only for non-critical cache/telemetry paths when availability requires it.
  - Fuse patterns only when both are generic and complementary; otherwise keep the simpler product-agnostic rule.
- Example: if one codebase stores workflow state only in Redis and another persists it in a relational table, keep the relational source-of-truth rule and optionally use Redis as cache, lock, rate limit, or scheduling aid.

## Core Workflow

Before changing architecture guidance, contracts, service boundaries, diagrams, plans, or implementation-driving recommendations, complete enough analysis and planning for the decision to be reviewable. Scale the plan to risk: a simple low-risk explanation can use a short inline plan; multi-service, contract-visible, data-ownership, release, high-risk, branch/MR, or unclear-risk architecture work needs explicit assumptions, alternatives, tradeoffs, acceptance checks, verification evidence, rollback or migration path, and named handoffs to implementation, testing, platform, or product workflow skills before edits or approval.

1. Define the product boundary.
   - Identify user workflows, domain objects, external integrations, and lifecycle events.
   - Decide which capabilities must be synchronous APIs, internal RPCs, async jobs, or scheduled tasks.
   - Internal microservice calls use RPC/gRPC by default and may use HTTP when the service contract chooses it. Internal HTTP must meet the same service discovery, auth, timeout, retry, observability, and contract-test standards as RPC.
   - Avoid splitting into microservices until ownership, scaling, data boundary, or deployment cadence justifies it.

2. Define service contracts before implementation.
   - Use protobuf IDL as the default contract format.
   - Service identity is decided before IDL and implementation. For new services, define the globally unique service name first, then IDL, then generated contract artifacts, then business implementation.
   - Treat IDL and idlgen outputs as a stable boundary between service contracts and business repositories. Prefer centralized IDL ownership plus versioned generated artifacts that business services import. When the platform uses shared IDL and IDLGen repositories, Go, Python, web, mobile, and mini-program consumers must derive from the same contract source; do not fork IDL or generated artifacts per service repository or per language unless it is a deliberate compatibility branch with owner, version, and deprecation plan. Service repository layout (single service, multi-service, API/RPC split) does not change contract ownership.
   - Protobuf may be the contract source for HTTP as well as RPC. For protobuf-backed or cross-language HTTP gateways, decide separately: contract source (protobuf/OpenAPI), generated route/client artifacts, and wire format (JSON vs binary protobuf). Classify protobuf-backed HTTP using the canonical wire-format gate in `../platform-service-connectivity/references/protobuf-http-contract-signals.md`; do not restate or widen that predicate locally.
   - API contracts must define request messages, the response envelope, and shared public fields in the shared contract source before implementation, per the canonical `code`/`message`/`data` envelope contract in `../platform-service-connectivity/references/http-response-envelope-contract.md` (adoption, migration, non-JSON surfaces, and anti-patterns live there — do not restate them here).
   - Internal RPC contracts carry the platform's shared request/response metadata field when the platform defines one; `platform-service-connectivity` owns the canonical base-struct shape and named-framework examples. Do not inherit a framework's reserved envelope/base field number as a cross-product convention (per `references/protobuf-contract-architecture.md`); if a shared metadata field must be part of the protobuf contract (rather than carried via middleware metadata), a new product picks an explicit field and documents it. Within a platform that has already standardized such a field, its field number, name, and message type are compatibility surfaces — do not renumber, rename, or replace them locally.
   - Internal service data models need the same contract discipline: shared cross-service DTOs, enums, status values, metadata fields, and request/response models live in the contract or generated artifact boundary; service-private domain and persistence models stay inside the owning service and convert at transport/application boundaries.
   - Separate public HTTP API models from internal RPC models when external clients have different stability needs.
   - Prefer additive contract evolution: new fields, new methods, new enum values; avoid breaking field numbers or response semantics.
   - **Inventory the service's exposed surfaces and review new ones at the boundary.** Keep a machine-checkable inventory of every externally reachable surface appropriate to the stack — HTTP routes, RPC services and methods, and async subscriptions (MQ / event / webhook consumers); a surface absent from it should not reach production unreviewed. Drive it from a deterministic discovery profile (routes/subscriptions-as-code, or a generated manifest plus a checked-in snapshot, are two common patterns) with explicit allowlisted carve-outs for framework / health / debug, generated, plugin, and env-conditional surfaces, so the gate flags genuinely new exposure instead of churning on false positives; also flag inventory entries no longer present in code so the snapshot stays trustworthy. Scale enforcement to risk: hard-fail CI for production, externally reachable services; a lighter manifest + review checklist suffices for prototypes, internal scripts, or repos without CI. The inventory proves *every surface was seen and reviewed*, **not** that it is authorized — it is not an authn/authz gate; auth, tenant isolation, and safe exposure remain separate evidence the boundary review must still demand. An unregistered new route or consumer is a *shadow surface* (unreviewed; async consumers are a commonly missed class). Distinct from breaking-change detection (`buf breaking` / `kitex check`, which guards *changes to existing* surfaces) and from agent-contract directory coverage (whether a directory carries an `AGENTS.md`); it guards *new runtime exposure*. `product-rd-workflow`'s spec/repo-contract sync gate owns the human discipline; this is its mechanical enforcement. Mirror any change to this rule in `../python-service-architecture/SKILL.md`.
   - For finite values that cross service, storage, client, analytics, or generated-code boundaries, architecture must name the canonical owner, shared package or contract location, conversion boundaries, unknown/default behavior, and migration/debt exit path before implementation. If no shared location exists, approve the local-slice fallback and require every `finite-value-debt` marker to carry task reference, owner, deadline, and reason.

3. Design data ownership.
   - Each service owns its write model and schema.
   - Cross-service reads should go through RPC/API or explicit read models, not shared table writes.
   - Use relational DB as source of truth for transactional domain state.
   - Use GORM as the default MySQL DAL choice for new Go services unless the repo already standardizes or conventionally uses another query layer, or the architecture records a deliberate alternative.
   - Decide schema, indexes, unique constraints, migration path, and sharding keys before writing DAL code.
   - Keep GORM, sqlx, and raw SQL behind DAL or repository boundaries; transport and application layers must not build database queries directly.
   - Use Redis for cache, locks, counters, idempotency windows, rate limits, and ephemeral coordination, not durable truth.
   - Define Redis key scope, TTL policy, lock lease, rate-limit window, and idempotency lifetime as part of the architecture.

4. Design runtime platform contracts.
   - Config: local file + dynamic config, with environment/lane separation.
   - High-risk feature flags and runtime config default fail-closed in production. Local stubs, test defaults, and developer-safe switches must be visibly scoped and cannot become implicit production enablement.
   - Secrets: never stored in code or config files; resolve through a secret provider.
   - Service discovery: all internal RPC clients use discovery/resolver abstraction.
   - Service identity: internal RPC/HTTP trust should be based on workload identity, mTLS, signed service tokens, or an equivalent zero-trust control, not only network location.
   - Runtime wrappers should provide service identity, registration/discovery, context propagation, trace/log id, metrics, timeout/circuit behavior, and safe debug exposure consistently across HTTP, RPC, and workers.
   - A capability requirement is not a framework-adoption decision. When a requirement names a capability (service discovery, mTLS, graceful drain), first define its minimal closure — the small

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [ccoalm](https://github.com/ccoalm)
- **Source:** [ccoalm/ccl-skills](https://github.com/ccoalm/ccl-skills)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-ccoalm-ccl-skills-go-microservice-architecture
- Seller: https://agentstack.voostack.com/s/ccoalm
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
