Backend Development 18 min read

Overview and Architecture of Kratos v2 Go Microservice Framework

Kratos v2 is a lightweight, highly pluggable Go microservice framework that replaces the monolithic v1 design with a toolbox of interchangeable components—such as transport, middleware, logging, configuration, and service discovery—organized in a DDD‑inspired layout and extensible via protobuf‑defined plugins.

Bilibili Tech
Bilibili Tech
Bilibili Tech
Overview and Architecture of Kratos v2 Go Microservice Framework

Kratos is a lightweight Go microservice framework that provides a rich set of features and tools for building microservices. The name comes from the game "God of War".

Since the first commit of kratos v2 on GitHub in February 2021, the project has evolved from version 2.0.0 alpha1 to 2.2.1 , now offering a complete microservice framework capability.

Overview

kratos v1 was designed with limited extensibility, tightly coupling framework modules and implementations, which made it difficult to replace components without forking the code. In contrast, kratos v2 acts as a toolbox for Go microservices, allowing developers to assemble services like building blocks. It does not bind to any specific infrastructure, enabling easy integration of arbitrary libraries.

The design of kratos v2 emphasizes high customizability: the framework defines interfaces and implements functionality through plugins, achieving a highly pluggable architecture. Core capabilities such as API definition, gRPC/HTTP services, request validation, error handling, Swagger JSON, and configuration templates are all built on Protobuf IDL.

Project Ecosystem

kratos : core framework providing CLI tools, HTTP/gRPC transport, lifecycle management, logging, error handling, configuration, monitoring, serialization, service discovery, metadata, transport, and middleware.

contrib : adapters for configuration files, logging systems, service discovery, monitoring, etc., ready to be integrated into Kratos projects.

aegis : algorithms for service availability (rate limiting, circuit breaking) with minimal external dependencies.

layout : project template inspired by DDD and clean architecture, including Makefile and Dockerfile, fully customizable.

gateway : an upcoming Go‑based API gateway for microservice governance.

Architecture Design

The framework’s design considerations include package‑oriented design, HTTP/gRPC transport, application lifecycle management, configuration conventions, business error design, logging interface design, metadata transmission, middleware usage, and a simplified DDD layout implementation.

Package‑Oriented Design

/cmd : command‑line tools installable via go install or go get .

/errors : unified business error definitions with codes and messages.

/config : multi‑source configuration with merging, hot‑update via atomic operations.

/transport : abstraction of HTTP/gRPC transport layer.

/middleware : abstract interfaces bridging transport and service.

/metadata : cross‑service metadata handling.

/registry : abstract service registry supporting etcd, Consul, Nacos, etc.

Transport HTTP/gRPC

The framework abstracts the transport layer, providing default implementations for both gRPC and HTTP. Key interfaces include Server , Endpointer , Header , and Transporter (see code snippet below).

// service start/stop for lifecycle management
 type Server interface {
   Start(context.Context) error
   Stop(context.Context) error
 }

// endpoint registration for service discovery
 type Endpointer interface {
   Endpoint() (*url.URL, error)
 }

// request header metadata
 type Header interface {
   Get(key string) string
   Set(key string, value string)
   Keys() []string
 }

// transport context value
 type Transporter interface {
   Kind() Kind
   Endpoint() string
   Operation() string
   RequestHeader() Header
   ReplyHeader() Header
 }

Application Lifecycle Management

Implement transport.Server and use kratos.New to manage service lifecycle, handling server lifecycle and registry management. The AppInfo interface provides ID, name, version, metadata, and endpoints.

type AppInfo interface {
   ID() string
   Name() string
   Version() string
   Metadata() map[string]string
   Endpoint() []string
 }

Configuration Convention

Configuration sources can be combined and merged into key/value pairs. The framework supports local file sources, custom plugins (e.g., Nacos, Consul, Apollo), hot‑update (watch), custom decode, placeholder substitution, and second‑level assignment.

message Bootstrap {
  Server server = 1;
  Data data = 2;
}

message Server {
  message HTTP {
    string network = 1;
    string addr = 2;
    google.protobuf.Duration timeout = 3;
  }
  message GRPC {
    string network = 1;
    string addr = 2;
    google.protobuf.Duration timeout = 3;
  }
  HTTP http = 1;
  GRPC grpc = 2;
}

message Data {
  message Database {
    string driver = 1;
    string source = 2;
  }
  message Redis {
    string network = 1;
    string addr = 2;
    google.protobuf.Duration read_timeout = 3;
    google.protobuf.Duration write_timeout = 4;
  }
  Database database = 1;
  Redis redis = 2;
}

Business Error Handling

Errors are defined via protobuf enums and exposed through the errors package with HTTP and gRPC status mapping. Functions such as StatusCode() and GRPCStatus() provide unified error handling.

Logging Interface Design

The logging module defines a simple Logger interface and provides helpers, filters, and valuers for extensibility. Example usage shows creating a standard logger, applying level and key filters, and adding contextual fields.

type Logger interface {
   Log(level Level, keyvals ...interface{}) error
 }

logger := log.NewStdLogger(os.Stdout)
logger = log.NewFilter(logger, log.FilterLevel(log.LevelInfo))
logger = log.With(logger, "app", "helloworld", "ts", log.DefaultTimestamp, "caller", log.DefaultCaller, "trace_id", log.TraceID(), "span_id", log.SpanID())
helper := log.NewHelper(logger)
helper.WithContext(ctx).Info("info log")

Metadata Transmission

Metadata is transmitted via HTTP/gRPC headers, encapsulated as key/value pairs. Global metadata uses the x-md-global-xxx prefix, while local metadata uses x-md-local-xxx . The metadata package provides functions to append and retrieve metadata in client and server contexts.

// server setup
grpcSrv := grpc.NewServer(
    grpc.Address(":9000"),
    grpc.Middleware(metadata.Server()),
)

// client setup
conn, err := grpc.DialInsecure(
    context.Background(),
    grpc.WithEndpoint("127.0.0.1:9000"),
    grpc.WithMiddleware(metadata.Client()),
)

Middleware Usage

Kratos ships with built‑in middleware for recovery, tracing, logging, metrics, validation, and metadata propagation. Users can implement custom middleware for cross‑cutting concerns such as authentication.

Simplified DDD Layout

The project layout follows a DDD‑inspired structure with separate directories for API definitions, command entry points, internal business logic, configuration, data access, server setup, and service implementation. This layout promotes clean separation of concerns and easy scalability.

Future Plans

The roadmap focuses on developing the kratos gateway , expanding the Kratos API interface, and building a service governance platform ( Kratos UI ). The community is encouraged to contribute to the ecosystem.

Related Resources

Official site: go-kratos.dev

GitHub: https://github.com/go-kratos/kratos

Gateway: https://github.com/go-kratos/gateway

Contrib: https://github.com/go-kratos/kratos/tree/main/contrib

Aegis: https://github.com/go-kratos/aegis

middlewareConfigurationGomicroservicesAPIframeworkKratos
Bilibili Tech
Written by

Bilibili Tech

Provides introductions and tutorials on Bilibili-related technologies.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.