Skip to content

Architecture

go-zero is a cloud-native microservices framework built around a layered design that separates concerns while keeping each layer thin and replaceable.

go-zero System Architecture

Every incoming HTTP request flows through a fixed pipeline before reaching your business logic:

HTTP Request Lifecycle

What each layer does:

LayerComponentPurpose
TimeoutTimeoutHandlerEnforce per-request deadline (config: Timeout)
Load sheddingSheddingHandlerReject requests when CPU > threshold
Rate limitingRateLimitHandlerToken-bucket rate limiter per route
MiddlewareYour codeAuth, logging, CORS, etc.
HandlerGeneratedUnmarshal request → call Logic
LogicYour codeBusiness rules, DB/RPC calls

Middleware Chain Execution Order

Server-wide middleware is registered via server.Use(...) and runs for every request. Per-route middleware is declared in the .api file’s @server block and generated into ServiceContext. Built-in safety handlers always run last before your handler code.

goctl generates the full wiring between the HTTP layer and RPC clients:

API Gateway to RPC Wiring

ServiceContext is the dependency injection container. It holds all RPC clients, DB connections, cache references, and config. Both handler and logic layers share it via a pointer.

5. Resilience: Rate Limiting & Circuit Breaking

Section titled “5. Resilience: Rate Limiting & Circuit Breaking”

Resilience: Rate Limiting and Circuit Breaking

go-zero’s circuit breaker uses a sliding-window failure counter. The breaker opens when the error ratio in the past 10 seconds exceeds the configured threshold (default: 50%). In half-open state it lets one probe request through.

Configuration:

# Automatically applied to every zrpc call and every outbound HTTP call
# No explicit config needed — go-zero enables it by default

go-zero instruments every layer automatically:

Observability Pipeline

Enabling:

etc/app.yaml
# Structured logging (always on)
Log:
ServiceName: order-api
Mode: file # console | file
Level: info
Encoding: json
# Metrics
Prometheus:
Host: 0.0.0.0
Port: 9101
Path: /metrics
# Distributed tracing
Telemetry:
Name: order-api
Endpoint: http://jaeger:14268/api/traces
Sampler: 1.0 # 1.0 = 100% sampling
Batcher: jaeger

All logs carry a trace_id and span_id field that correlate with Jaeger traces — no manual instrumentation required.