← Previous Chapter: Part 2: Rush Monorepo for 21 Go & Next.js Apps | Series Hub | Next Chapter: Part 4: gRPC Internal + REST Gateway →


Answer-first: The enterprise-grade Go microservice architecture on this platform is built on Kratos v2 with a strict 5-layer model, Google Wire dependency injection, parallel HTTP/REST and gRPC transports, and a shared library that standardizes logging and middleware.


For engineers coming over from Magento PHP, the shift to Go microservices is not just a change of programming language — it is a fundamentally different way of organizing code. Magento has controllers, models, blocks, helpers, and plugins. Go with Kratos v3 (fully optimized for Go 1.25) has exactly 5 layers, each with a crisply defined responsibility.

Answer-first: A production-grade Go microservice on this platform follows the Kratos v3 folder convention (api/ → cmd/ → internal/biz/ → internal/data/ → internal/server/), uses Google Wire for compile-time dependency injection, exposes both HTTP and gRPC simultaneously on different ports (8xxx/9xxx), and imports a shared common library (currently at version v1.9.5) that provides outbox, caching, worker, metrics, and logging — standardized across all 21 services.

1. The 5-Layer Folder Structure

Each of the 21 services follows the same layout:

order-service/
├── api/
│   └── order/
│       └── v1/
│           ├── order.proto           ← gRPC + HTTP API definition
│           ├── order_types.proto     ← Shared enums (OrderStatus, etc.)
│           └── order_errors.proto    ← Error codes
│
├── cmd/
│   └── order-service/
│       ├── main.go                   ← Entry point
│       ├── wire.go                   ← Wire dependency injection declaration (with build tag)
│       └── wire_gen.go               ← Auto-generated by the wire command
│
├── internal/
│   ├── biz/                          ← Business logic (use cases, domain entities)
│   │   ├── order.go                  ← The Order entity + business rules
│   │   ├── order_usecase.go          ← Use cases: CreateOrder, CancelOrder...
│   │   └── order_repo.go             ← Repository interface (definition only, no implementation)
│   │
│   ├── data/                         ← Data access (repository implementations)
│   │   ├── order_repo.go             ← The PostgreSQL implementation
│   │   ├── order_cache.go            ← The Redis cache layer
│   │   └── data.go                   ← DB connection setup, Redis clients
│   │
│   ├── service/                      ← gRPC/HTTP handlers
│   │   └── order.go                  ← Maps proto requests → biz use cases
│   │
│   └── server/
│       ├── grpc.go                   ← gRPC server (port 9001)
│       └── http.go                   ← HTTP server (port 8001)
│
├── migrations/
│   └── 00001_create_orders.sql       ← Goose migration file
│
└── go.mod                            ← Module: gitlab.com/ta-microservices/order-service

The role of each layer:

  • api/: The contract. Define your protos here first — before writing any Go code. This layer contains no Go source, only .proto files.
  • cmd/: The entry point and the root where Wire performs injection. main.go is typically under 20 lines. All initialization is delegated to Wire.
  • internal/biz/: Pure business logic. No database calls and no HTTP handlers live here. Packages in biz import only domain types and repository interfaces.
  • internal/data/: The actual repository implementations. Database queries live here. This is where interactions with PostgreSQL and Redis happen, and where events are published through Dapr.
  • internal/service/: The bridge between the transport layer and the business logic layer. It receives a proto request, calls the biz use cases, and returns a proto response.
  • internal/server/: Where the HTTP and gRPC servers are assembled with their middleware, and started.

This separation is not cosmetic. It is meaningful: the biz layer never knows it is running behind gRPC. You can plug in a CLI transport, a queue consumer, or a test harness that calls biz directly — without changing a single line of business logic.

2. Wire: Compile-Time Dependency Injection

In Magento, the dependency injection container operates at runtime — Magento builds the DI graph when the application boots, resolving dependencies from XML configuration files. This is slow, error-prone, and breeds bugs that only surface at runtime.

Go Wire solves this at compile time. The dependency graph is code-generated before the binary is even built. If a dependency is missing, the build fails immediately — instead of throwing a runtime error.

Here is how it works for the Order Service:

// cmd/order-service/wire.go
//go:build wireinject
// +build wireinject

package main

import (
    "github.com/go-kratos/kratos/v2"
    "github.com/google/wire"

    "gitlab.com/ta-microservices/order-service/internal/biz"
    "gitlab.com/ta-microservices/order-service/internal/data"
    "gitlab.com/ta-microservices/order-service/internal/server"
    "gitlab.com/ta-microservices/order-service/internal/service"
)

func initApp(logger log.Logger, conf *conf.Bootstrap) (*kratos.App, func(), error) {
    wire.Build(
        data.ProviderSet,    // DB connections, Redis, repository implementations
        biz.ProviderSet,     // Use cases
        service.ProviderSet, // gRPC/HTTP service handlers
        server.ProviderSet,  // HTTP + gRPC servers
        newApp,
    )
    return nil, nil, nil
}

Running wire ./cmd/order-service/ generates the wire_gen.go file:

// cmd/order-service/wire_gen.go — AUTO-GENERATED CODE, DO NOT EDIT BY HAND

func initApp(logger log.Logger, conf *conf.Bootstrap) (*kratos.App, func(), error) {
    db, cleanup, err := data.NewDatabase(conf.Data)
    if err != nil { return nil, nil, err }

    redisClient := data.NewRedisClient(conf.Data)
    orderRepo := data.NewOrderRepository(db, redisClient)

    orderUseCase := biz.NewOrderUseCase(orderRepo)

    orderService := service.NewOrderService(orderUseCase)

    grpcServer := server.NewGRPCServer(conf.Server, orderService, logger)
    httpServer := server.NewHTTPServer(conf.Server, orderService, logger)

    app, cleanup2, err := newApp(logger, grpcServer, httpServer)
    // ...
    return app, func() { cleanup2(); cleanup() }, nil
}

No reflection. No runtime DI container. The initialization sequence is decided at compile time, and Go’s type system guarantees that every dependency is satisfied. If you add a new dependency to OrderUseCase but forget to provide it in the ProviderSet, go build fails immediately.

3. Dual Transport: HTTP + gRPC on Separate Ports

Every service exposes two ports running concurrently:

// internal/server/grpc.go
func NewGRPCServer(c *conf.Server, os *service.OrderService, logger log.Logger) *grpc.Server {
    srv := grpc.NewServer(
        grpc.Address(c.Grpc.Addr),              // Port :9001
        grpc.Timeout(c.Grpc.Timeout.AsDuration()),
        grpc.Middleware(
            recovery.Recovery(),
            tracing.Server(),
            logging.Server(logger),
            validate.Validator(),               // Proto-level field validation
        ),
    )
    orderv1.RegisterOrderServiceServer(srv, os)
    return srv
}

// internal/server/http.go
func NewHTTPServer(c *conf.Server, os *service.OrderService, logger log.Logger) *http.Server {
    srv := http.NewServer(
        http.Address(c.Http.Addr),              // Port :8001
        http.Timeout(c.Http.Timeout.AsDuration()),
        http.Middleware(
            recovery.Recovery(),
            tracing.Server(),
            logging.Server(logger),
            jwt.Server(keyFunc),                // JWT validation (HTTP only)
        ),
    )
    orderv1.RegisterOrderServiceHTTPServer(srv, os)
    return srv
}

The proto annotations automatically take care of generating the HTTP routes:

// cmd/order-service/main.go
func newApp(logger log.Logger, gs *grpc.Server, hs *http.Server) (*kratos.App, func(), error) {
    app := kratos.New(
        kratos.Name("order-service"),
        kratos.Version("v1.0.0"),
        kratos.Logger(logger),
        kratos.Server(gs, hs),  // Both servers are registered to start
    )
    return app, app.Stop, nil
}

The port convention (consistent across all 21 services):

  • HTTP: 8xxx (e.g., Order = 8001, Payment = 8003, Catalog = 8005)
  • gRPC: 9xxx (e.g., Order = 9001, Payment = 9003, Catalog = 9005)

This convention was not chosen at random — it is about discoverability. Any engineer who knows a service’s HTTP port instantly knows its gRPC port by adding 1000.

4. The biz Layer: Where Business Logic Lives

This is where the real domain work happens. In Magento terms, biz is the combination of your Service Layer (service contracts), your Models (domain entities), and the business rule enforcement engine — except it is isolated with extreme rigor, with zero exposure to I/O.

// internal/biz/order.go

// Domain entity — no ORM annotations, no proto types
type Order struct {
    ID         string
    CustomerID string
    Status     OrderStatus
    Items       []OrderItem
    Total      money.Money
    CreatedAt  time.Time
    UpdatedAt  time.Time
}

type OrderStatus string
const (
    OrderStatusPending   OrderStatus = "PENDING"
    OrderStatusConfirmed OrderStatus = "CONFIRMED"
    OrderStatusCancelled OrderStatus = "CANCELLED"
    // ... 5 more statuses
)

// Repository interface — biz defines the contract, data writes the implementation
type OrderRepository interface {
    Create(ctx context.Context, order *Order) (*Order, error)
    FindByID(ctx context.Context, id string) (*Order, error)
    UpdateStatus(ctx context.Context, id string, status OrderStatus) error
    // ...
}
// internal/biz/order_usecase.go

type OrderUseCase struct {
    repo     OrderRepository    // Points to the interface — not the PostgreSQL implementation
    events   events.Publisher   // From the common library
    log      *log.Helper
}

func (uc *OrderUseCase) CreateOrder(ctx context.Context, order *Order) (*Order, error) {
    // Business rule: do not create an order if the customer has more than 3 unpaid orders
    count, err := uc.repo.CountUnpaidByCustomer(ctx, order.CustomerID)
    if err != nil { return nil, err }
    if count >= 3 {
        return nil, errors.BadRequest("TOO_MANY_UNPAID_ORDERS",
            "customer %s already has %d unpaid orders", order.CustomerID, count)
    }

    // Create in the database (through the repository interface)
    created, err := uc.repo.Create(ctx, order)
    if err != nil { return nil, err }

    // Publish the domain event (through common/events)
    uc.events.Publish(ctx, "orders.order.created", &events.OrderCreated{
        OrderID:    created.ID,
        CustomerID: created.CustomerID,
        Items:      created.Items,
    })

    return created, nil
}

Note: biz has zero imports of database/sql, pgxpool, or any PostgreSQL library. It depends on interfaces alone. That is why you can test the biz layer with a mock repository — without ever wiring up a real database.

5. The common (Shared) Library: v1.9.5

With 21 services, every design pattern you introduce in one service has to be duplicated in the other 20. The platform solves this with a shared Go module:

// The go.mod file of any service
require gitlab.com/ta-microservices/common v1.9.5

ADR-023 records that common v1.9.5 eliminated 4,150 lines of repeated boilerplate across 19 services compared to v1.0.0. Here is what is inside it:

common/
├── cache/        ← Cache-aside with single-flight stampede protection
├── config/       ← Config utilities for go-kratos
├── database/     ← PostgreSQL connection setup, Goose migration helpers
├── events/       ← Event publishing via Dapr + outbox flow integration
├── middleware/   ← gRPC/HTTP middleware for auth, logging, tracing
├── auth/         ← JWT validation
├── logging/      ← Structured logging with correlation IDs attached
├── metrics/      ← Prometheus metrics: request counts, latency, error rates
├── errors/       ← Standardized error codes
├── validation/   ← Input validation utilities
├── worker/       ← Outbox processor + distributed cron (using RedLock)
└── utils/        ← Miscellaneous helpers

The package worth its price: common/cache

import "gitlab.com/ta-microservices/common/cache"

// Cache-aside with single-flight protection (prevents cache stampede)
product, err := cache.GetOrFetch(ctx, cache.Key("product", productID), func() (*Product, error) {
    return repo.FindByID(ctx, productID)
}, cache.TTL(1*time.Hour))

This single-flight primitive guarantees that if 1,000 requests arrive simultaneously for the same cache key (just expired), only exactly one PostgreSQL query is allowed to run. The other 999 requests wait and receive the result of that first query. Without this shield, every cache expiry in the middle of a flash sale would create a thundering herd that takes the database down.

The package worth its price: common/worker

import "gitlab.com/ta-microservices/common/worker"

// Outbox processor: scans the outbox_events table and publishes to Dapr
processor := worker.NewOutboxProcessor(db, daprClient, worker.Config{
    PollInterval: 500 * time.Millisecond,
    BatchSize:    100,
    MaxRetries:   5,
})
processor.Start(ctx)

// Distributed cron (RedLock): runs a cron job on exactly ONE instance
cron := worker.NewDistributedCron(redisClient)
cron.Schedule("0 * * * *", "cleanup-expired-carts", func(ctx context.Context) error {
    return cartRepo.DeleteExpired(ctx, 24*time.Hour)
})

6. Error Handling in Kratos: More Than HTTP Status Codes

Magento’s error system throws PHP exceptions, then catches them and converts them into HTTP responses. Kratos’s error system is far more precise:

import "github.com/go-kratos/kratos/v2/errors"

// Each error carries: an HTTP status code, a machine-readable code, and a human-readable message
errors.NotFound("ORDER_NOT_FOUND", "order %s not found", orderID)
// → Returns: HTTP 404, grpc.Code = NOT_FOUND
// → JSON: {"code": 404, "reason": "ORDER_NOT_FOUND", "message": "order xyz not found"}

errors.BadRequest("INVALID_CUSTOMER_ID", "customer_id is required")
// → Returns: HTTP 400, grpc.Code = INVALID_ARGUMENT

errors.Forbidden("PERMISSION_DENIED", "requires the orders:delete permission")
// → Returns: HTTP 403, grpc.Code = PERMISSION_DENIED

errors.InternalServer("DB_ERROR", "database is temporarily unresponsive")
// → Returns: HTTP 500, grpc.Code = INTERNAL

The reason field (ORDER_NOT_FOUND) is the machine-readable code. Frontend code pattern-matches on reason to decide how to behave (for example, automatically redirecting to the cart page when it sees CART_EXPIRED), while the message field is what gets displayed to the user.

7. Configuration: go-kratos Config

Each service reads configuration from:

  1. configs/config.yaml (the base configuration, committed to the repository)
  2. Environment variables (from Kubernetes ConfigMaps / Secrets)
  3. The Dapr Configuration store (used for runtime feature flags)
# configs/config.yaml
server:
  http:
    addr: ":8001"
    timeout: 30s
  grpc:
    addr: ":9001"
    timeout: 10s

data:
  database:
    source: "postgres://order_svc:${DB_PASS}@${DB_HOST}:5432/order_db?sslmode=require"
    max_open_conns: 20
    max_idle_conns: 10

  redis:
    addr: "${REDIS_ADDR}"
    db: 1  # Each service uses a different Redis DB number
// cmd/order-service/main.go
func main() {
    c := config.New(
        config.WithSource(
            file.NewSource("configs/config.yaml"),
            env.NewSource("APP_"),  // Scans APP_DB_PASS, APP_REDIS_ADDR, etc.
        ),
    )
    var bc conf.Bootstrap
    c.Scan(&bc)
    // ...
}

What Magento Engineers Have to Unlearn

Coming from the Magento ecosystem, four mental models must change:

Magento architectureKratos v3 architecture
DI container configured in di.xmlWire generates DI code at compile time
Controllers handle HTTP + business logicThe service/ layer handles HTTP; the biz/ layer holds logic — the two never overlap
Models may hit the database directlybiz/ entities have no database imports — that is data/’s job
Runtime plugin system (Plugins/Interceptors)No runtime monkey-patching; all wiring happens when Wire performs the injection

Kratos’s structure is far more rigid than Magento’s flexibility — and that is the whole point. Rigidity brings predictability. Whenever a new engineer joins the team, they know exactly where to find the business logic (internal/biz/), the database queries (internal/data/), and the API boundary (internal/service/). They no longer have to dig through Model/ResourceModel/, Block/, Helper/, and Plugin/ folders to debug.

Next Steps

With the internals of a service laid bare, we can turn to the API layer: how services talk to each other over gRPC, and how the Gateway Service exposes REST endpoints to external clients. Part 4: gRPC Internal + REST Gateway Architecture walks through protobuf conventions, the Money type, cursor pagination, and the full lifecycle of an API from .proto file to HTTP response.

Frequently Asked Questions (FAQ)

go-kratos vs. Gin — which one is faster?

Gin edges out Kratos slightly in raw HTTP throughput benchmarks (roughly 15–20% lower latency in synthetic tests). But for real-world microservices, this difference is negligible — database and network latency dominate, not framework overhead. go-kratos’s decisive advantage over Gin is dual transport: Kratos serves both HTTP and gRPC from a single proto definition file. Gin forces you to write separate HTTP handlers and separate gRPC server code — doubling the boilerplate per endpoint.

How does Wire’s dependency injection differ from Spring’s or Magento’s runtime DI?

Wire generates Go code at compile time — no reflection, no XML configuration files, and no DI container running at runtime. If you drop a dependency (say, you add a new parameter to a constructor but forget to update the provider set), go build fails immediately. In Spring or Magento, the exact same mistake only surfaces as a runtime exception — and it usually blows up in production. Wire’s compile-time guarantee is the core reason go-kratos chose it over alternatives like dig (a runtime DI solution).

Can a single kratos service serve both REST and gRPC without running two separate server processes?

Yes — that is exactly what kratos.Server(gs, hs) does. Both the gRPC server (port :9001) and the HTTP server (port :8001) run as goroutines inside a single process. They share the same biz layer and the same database connection pool. The proto annotations (google.api.http) automatically handle the HTTP↔gRPC cross-routing, so you write your handler logic exactly once.


This article is part of the Composable Commerce Migration Series. Check out the full table of contents for the complete architectural context.

Need help assessing the risks of an upcoming platform migration? → Book a 1:1 Architecture Consultation




← Previous Chapter: Part 2: Rush Monorepo for 21 Go & Next.js Apps | Series Hub | Next Chapter: Part 4: gRPC Internal + REST Gateway →