scaffold-health-checks
Scaffold FastAPI/gRPC liveness, readiness, and startup health checks, graceful shutdown, and optional Kubernetes probes. Use for "health endpoint", "readiness/liveness probe", or "k8s probes".
- License 许可
- MIT
- 最近更新
- 2026-11-07
- Stars
- ★ 3
- Forks
- 1
01 前言 Front Matter
- name
- scaffold-health-checks
- description
- Scaffold FastAPI/gRPC liveness, readiness, and startup health checks, graceful shutdown, and optional Kubernetes probes. Use for "health endpoint", "readiness/liveness probe", or "k8s probes".
02 资源文件 2
- 参考文档reference/k8s-probes-grpc.yaml458 B
- 参考文档reference/k8s-probes-http.yaml467 B
03 SKILL.md 正文
Scaffold ArchiPy Health Checks
Read first
Read these plugin rules in full before generating files (paths relative to this skill directory; Claude Code: ${CLAUDE_SKILL_DIR}/../../rules/):
../../rules/using-archipy-services.mdc
Before writing files
- Inspect package/config, current transports, app lifecycle, dependency adapters, DI wiring, deployment manifests, and existing health endpoints.
- Infer package name, transport, ports, and readiness dependencies from the repository.
- Ask only for unresolved choices: dependencies to include, heartbeat deadlock detection, or Kubernetes YAML.
- Preserve existing health routes and manifests; merge compatible additions instead of overwriting.
Prefer ArchiPy
Health checks are app code. ArchiPy does not ship stock HTTP routes or a stock gRPC Health servicer.
Probe semantics (liveness vs readiness vs startup, K8s notes, common mistakes, FastAPI sketches): keep
../archipy-docs/reference/health-checks.md § Health checks as the source of truth — do not invent alternate probe meanings or
duplicate endpoint sketches here. Resolve ../... paths relative to this SKILL.md's directory in the plugin
installation — not the app workspace.
uv add "archipy[fastapi]" # HTTP probes
uv add "archipy[grpc]" # gRPC server + grpcio-health-checking
Prefer existing app bootstrap:
from archipy.helpers.utils.app_utils import AppUtils
from archipy.configs.base_config import BaseConfig
# FastAPI
app = AppUtils.create_fastapi_app()
app.include_router(create_health_v1_router(container))
# gRPC (sync)
server = AppUtils.create_grpc_app(BaseConfig.global_config())
# register domain servicers, then health:
register_health_servicer(server, container)
# gRPC (async)
server = AppUtils.create_async_grpc_app(BaseConfig.global_config())
Do not hand-roll bare FastAPI() / grpc.server() when AppUtils is in use. Do not mix sync and async gRPC servicer
styles on one server.
Generate
Resolve files under reference/ relative to this SKILL.md in the plugin installation
($PLUGIN_ROOT/skills/scaffold-health-checks/, $CURSOR_PLUGIN_ROOT/skills/scaffold-health-checks/, or
${CLAUDE_SKILL_DIR}/). These are plugin templates, not app-relative paths. Copy
and adapt them into the app; never edit the plugin copies.
<package>/services/health/v1/
├── health_checks.py # shared readiness helpers (deps, warm-up, shutdown)
├── health_service.py # FastAPI — when HTTP requested
└── health_grpc_service.py # gRPC HealthServicer wiring — when gRPC requested
deploy/
└── k8s-probes.yaml # optional (httpGet and/or grpc probes)
Share readiness helpers across transports. Keep business rules out of transport files.
FastAPI (health_service.py)
- Export a thin router for
GET /health/liveandGET /health/ready. - Return
200healthy,503not ready / unhealthy, with empty bodies: no dependency names, versions, or error text. - Wire with
include_routerintomanage.py/ app factory. - Liveness: process-only, no deps. Readiness: deps + warm-up + shutdown, timeouts; per-check detail goes to logs only.
- Probes live in
repositories/health_check/(one adapter file per dependency raisingUnavailableError); the logic never drives adapters or raw SQL. - Optional heartbeat mode for deadlock detection only when user asks.
- Code sketches and payload shapes:
../archipy-docs/reference/health-checks.md§ Health checks → FastAPI endpoints.
gRPC (health_grpc_service.py)
Use the standard gRPC Health Checking Protocol (grpc.health.v1.Health) via grpcio-health-checking.
Register at least "" (overall), "readiness", and "liveness". Map ready/alive → SERVING, not ready →
NOT_SERVING. Full service-name table and update rules: ../archipy-docs/reference/health-checks.md § Health checks → gRPC Health
protocol.
Wire sketch
"" and "readiness" start NOT_SERVING until warm-up + deps are healthy:
from grpc_health.v1 import health, health_pb2, health_pb2_grpc
def register_health_servicer(server, container) -> health.HealthServicer:
"""Attach standard Health servicer; return handle for status updates."""
health_servicer = health.HealthServicer()
health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server)
health_servicer.set("liveness", health_pb2.HealthCheckResponse.SERVING)
health_servicer.set("readiness", health_pb2.HealthCheckResponse.NOT_SERVING)
health_servicer.set("", health_pb2.HealthCheckResponse.NOT_SERVING)
return health_servicer
Status update rules (summary)
- Warm-up complete + deps healthy → set
""and"readiness"toSERVING. - Dep failure →
""/"readiness"toNOT_SERVING; never flip"liveness"for dep failures. - Prefer background updater calling
set()over slow checks inside everyCheck. - On
SIGTERM: set readiness/""toNOT_SERVING, thenhealth_servicer.enter_graceful_shutdown(). - Async gRPC: same protocol/names; register on
AppUtils.create_async_grpc_app; keep updates task-safe.
Startup probes
- HTTP: point startup at
/health/live. - gRPC: point startup at service
"liveness"(prefer over"").
Kubernetes probe YAML
When requested, emit deploy/k8s-probes.yaml matching the chosen transport (s).
Copy templates from reference/, adapt ports to config:
| Transport | Template |
|---|---|
| HTTP | reference/k8s-probes-http.yaml |
| gRPC | reference/k8s-probes-grpc.yaml |
Use config.GRPC.SERVE_PORT / config.FASTAPI.SERVE_PORT — never hardcode ports in app code; YAML may show
placeholders matching config.
Rules: readinessProbe.successThreshold: 2, failureThreshold: 3 default, timeoutSeconds ≥ slowest readiness check
timeout, preStop sleep for short drain window.
Graceful shutdown
- On
SIGTERM, fail readiness immediately (HTTP503/ gRPCNOT_SERVING). - Give Kubernetes a short window to stop routing, then exit after in-flight requests finish.
- Details:
../archipy-docs/reference/health-checks.md§ Health checks → Graceful shutdown.
Common mistakes
See ../archipy-docs/reference/health-checks.md § Health checks → Common mistakes. Also avoid:
- No warm-up or shutdown awareness in readiness helpers
- Mixing sync and async gRPC health / domain servicers on one server
- Not testing failure behavior by taking down dependencies
Do not
- Double quotes, Google-style docstrings,
X | Ytyping - Keep services thin; no business rules in health transport
- No secrets in code; list env keys separately when needed
- Prefer FastAPI
JSONResponsefor HTTP probes; prefergrpcio-health-checkingfor gRPC - Suggest
/docs-health-checksfor explanation and/docs-observabilityfor metrics / tracing follow-up - Never hardcode ports in app code (YAML may show placeholders matching config).
- No warm-up/shutdown-blind readiness; no dependency checks in liveness; no custom gRPC health RPCs — use the standard protocol.
- No secrets in code; double quotes, Google-style docstrings,
X | Ytyping.
Verify
- Run formatter/linter, then Behave scenarios that call the health endpoints/RPCs through the BDD harness with the
dependencies'
@needs-*containers. - Cover healthy, dependency failure (stop or pause the container), timeout, warm-up, and shutdown states.
- Validate generated Kubernetes YAML and confirm probe ports/paths/service names match app config.
- Run the
archipy-reviewersubagent on the changes and fix every Must fix finding it reports. - Report files, dependencies, and commands run.
Beyond Kubernetes
Same pattern applies to ALB, Consul, Nginx, or gRPC load balancers: expose health (HTTP and/or grpc.health.v1), define
healthy clearly, and let infrastructure stop routing to unhealthy instances.
04 同仓库更多 Skills
scaffold-utils
Add or wire pure helpers/utils, preferring ArchiPy utils (datetime, JWT, password, file, string). Use for "add a helper/util function", "format dates", "hash passwords", or "generate tokens".
scaffold-service
Scaffold a thin FastAPI router or gRPC servicer under services/{domain}/v{n}/ with AppUtils bootstrap. Use for "add an endpoint/route/API", "expose via REST/gRPC", or "new API version".
scaffold-observability
Configure ArchiPy 5.x OpenTelemetry traces, metrics, logs, and instrumentation. Use for "add tracing/metrics/OTel", "Prometheus/Pushgateway", or migrating off Sentry, Elastic APM, or old Prometheus.
scaffold-models
Scaffold ArchiPy models under models/: domain/repository DTOs, errors, optional entities and types. Use for "add DTO/schema/request/response model", "new error type", or "SQLAlchemy entity".
scaffold-logic
Scaffold an ArchiPy logic (use case) under logics/{domain}/ with a unit-of-work decorator and DTO I/O. Use for "add business logic", "new use case", "transactional operation", or "service layer method".
scaffold-interceptor
Add or wire cross-cutting FastAPI/gRPC interceptors or middleware, preferring ArchiPy's. Use for "add middleware", "request ID/logging/auth interceptor", or "gRPC interceptor".