The user wants a "service template" design.
This template needs to include four specific features by default:
Health Checks
Circuit Breakers
Telemetry (Metrics/Tracing)
Structured Logging
The goal is to create a boilerplate or architectural pattern that developers can use to start building a new microservice or application with these production-ready features already integrated.
1. Choice of Technology Stack:
To make this concrete, I need to select a language and a framework.
Go (Golang) is the industry standard for cloud-native microservices. It has excellent libraries for all these components (grpc, zap, opentelemetry, halt).
Python (FastAPI) or Node.js (NestJS) are also good, but Go usually wins on performance and compiled safety for infrastructure-level templates.
Java (Spring Boot) has all this built-in, but it's heavy.
Decision: I will design this primarily as a Go template using standard cloud-native libraries (OpenTelemetry, Zap, GRPC/HTTP). I will also provide a high-level architectural diagram description so it applies to any language.
2. Architectural Layers:
A good service template needs distinct layers:
Config Layer: Environment variables, secrets.
Server Layer: HTTP/gRPC initialization.
Middleware/Interceptor Layer: Where the logic (Auth, Logging, Metrics) lives.
Must standardize fields (service name, version, environment).
Health Checks:
Need a standard endpoint (e.g., /health, /ready).
Kubernetes probes (Liveness vs. Readiness).
Dependency checking (DB connected? Cache up?).
Telemetry (Observability):
Tracing: OpenTelemetry (OTel) is the standard. Need context propagation.
Metrics: Prometheus format is standard. Need standard metrics (latency, error rate, traffic).
Circuit Breakers:
Where do they go? On outbound connections (Clients).
Library: sony/gobreaker or afex/hystrix-go (though Hystrix is old, gobreaker is cleaner).
Configuration: Thresholds, timeouts, half-open states.
4. Structuring the Design:
I will present this in a few ways:
Directory Structure: How the files should look.
Core Components (Code snippets): A "wrapper" or "skeleton" main file and specific setup functions.
The Middleware Stack: How they chain together.
Configuration: How to make it tunable.
Drafting the Go Implementation Details:
Main: Initialize Logger -> Initialize Telemetry -> Initialize DB (with Health check) -> Initialize HTTP Server (with Middleware) -> Initialize Clients (with Circuit Breakers).
Logging Middleware: Interceptor that logs request start/end and injects TraceID.
Circuit Breaker: Wrap the HTTP Client or gRPC Client.
Refining the "Design" aspect:
It's not just code; it's how it works.
The "Wrapper" Pattern: Don't make the dev write if err != nil { log.Error() } every time. Wrap the external calls.
The "Factory" Pattern: A function NewDefaultServer() that returns a server fully loaded with middleware.
Self-Correction/Review during drafting:
Initial thought: Just paste a main.go.
Correction: Too messy. Better to show a modular structure. Define an internal package structure.
Health Check: Distinguish between "I am alive" (Liveness) and "I can serve traffic" (Readiness). This is crucial for K8s.
Let's build the output structure:
Philosophy: Convention over configuration.
Tech Stack: Go + standard libraries (OpenTelemetry, Zap).
Architecture Diagram (Textual): Request flow.
Project Layout: Folder tree.
Key Implementations (The "Meat"):
Logging (Context-aware).
Telemetry (OTel setup).
Circuit Breaker (Client wrapper).
Health (Composite checker).
Usage Example: How a developer actually uses it.
Detailed Code Thoughts:
Logging: Use uber-go/zap. Create a helper to extract TraceID from context.
CB: Use sony/gobreaker. Create a wrapper around http.Client.
Health: Use a simple struct with a map of checkers (db, redis).
Final Polish:
Make sure to emphasize why this is a template. The idea is that a developer copies this repo, changes the business logic folder, and everything else works.
Let's write it out.
Step 1: Standard Library choices.
Logging: Zap
Config: Viper (or just Env vars)
Router: Chi (lightweight, std lib compatible) or standard mux.
Tracing: OTel.
Metrics: Prometheus client.
Step 2: The Integration Logic.
How do we inject the logger? Middleware.
How do we ensure CBs are used? Custom Client factory.
Let's assemble the response. Focus on a Go-based implementation as it is the most common language for this type of infrastructure-heavy template, but keep the concepts general enough to apply to Rust or Java.
Structure:
High-Level Architecture: The flow of data.
Project Structure: The folder layout.
Component Deep Dives:
Telemetry & Logging (The Eyes).
Resilience (Circuit Breakers - The Shield).
Health (The Pulse).
The "Glue" Code: A main.go example wiring it all up.
(Self-Correction on Health Checks): Make sure to implement distinct /live and /ready endpoints as per K8s best practices.
(Self-Correction on Circuit Breakers): Apply them at the Client level, not the server entry point.
Okay, ready to generate.
This design defines a "Batteries-Included" Microservice Template. It creates a standardized baseline where operational concerns are handled at the infrastructure/middleware layer, ensuring business logic developers cannot accidentally bypass safety or observability features.
We will use Go (Golang) for this design, as its standard library and concurrency model are ideal for building such frameworks.
1. Architectural Philosophy
The template follows the "Decorator Pattern".
Inner Core: Pure business logic (Input → Output).
Middleware Shell: Wraps the core to provide logging, metrics, and tracing.
Client Wrapper: Wraps external calls to enforce circuit breakers and retries.
2. The Project Structure
A clean separation between the "framework" and the "business logic."
text
/cmd
/server/main.go // Entry point, wires dependencies
/internal
/app // Your specific business logic
/platform // Reusable platform code
/config // Environment config loader
/http // HTTP Server setup & Middleware
/logger // Structured Zap/Logrus setup
/resilience // Circuit Breaker & Retry factories
/telemetry // OpenTelemetry setup
/pkg
/health // Health check aggregators
3. Component Implementations
A. Structured Logging (The Eyes)
We use Zap or Zerolog for zero-allocation JSON logging. The logger is injected into the context, allowing request-scoped values (like trace_id) to be attached automatically.
go
// internal/platform/logger/logger.go
package logger
import (
"context"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// LoggerKey is the context key for the logger
type LoggerKey struct{}
// Init returns a sugared logger with JSON encoding
func Init(serviceName string) *zap.SugaredLogger {
cfg := zap.Config{
Level: zap.NewAtomicLevelAt(zapcore.InfoLevel),
Development: false,
Encoding: "json",
EncoderConfig: zap.NewProductionEncoderConfig(),
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
InitialFields: map[string]interface{}{"service": serviceName},
}
logger, _ := cfg.Build()
return logger.Sugar()
}
// FromContext retrieves the logger from context or returns a new one
func FromContext(ctx context.Context) *zap.SugaredLogger {
if l, ok := ctx.Value(LoggerKey{}).(*zap.SugaredLogger); ok {
return l
}
return Init("fallback")
}
B. Telemetry & Tracing (The Nervous System)
We use OpenTelemetry. We ensure every request generates a Trace ID which is automatically injected into logs and headers.