Golang E-Commerce Architecture Design: Clean Architecture + Multi-Service
The complete architecture design of Santekno Shop with Claude. Monolith vs microservice decision, service decomposition, dependency graph, and a blueprint for implementation.
Multi-Service Architecture Design with Claude
Designing a proper Golang e-commerce architecture with clean architecture starts from structural decisions, not from code. This article is an architecture session — we design the Santekno Shop architecture from the top down, with Claude as a sparring partner. Before there is a single line of code, we need to make sure the structural decisions are right: monolith or microservice? What are the service boundaries? What is the dependency graph?
A wrong architecture decision at the start is far more expensive to fix than an ordinary bug. That is why we invest time to analyze the trade-offs explicitly — and document them so they can be traced back.
02.01 Monolith vs Microservice: The Decision for Santekno Shop
The most fundamental architecture question must be answered first. The trade-off analysis below weighs microservice versus monolith for the specific context of our team and scale.
1CONTEXT: Team of 8 developers, growth-phase startup, 100K MAU target
2
3ANALYSIS:
4
5Microservice pros:
6 + Independent scaling per service
7 + Independent deployment
8 + Technology flexibility
9 + Fault isolation
10
11Microservice cons:
12 - Network overhead between services
13 - Distributed transaction complexity
14 - Operational overhead (many deployment units)
15 - Harder debugging
16 - Needs a large team to manage
17
18Monolith pros:
19 + Simple development workflow
20 + Easy debugging (one process)
21 + Easy to refactor
22 + Lower latency (in-process call)
23 + One deployment unit
24
25Monolith cons:
26 - Scaling must be the whole application
27 - Coupling that creeps in over time
28
29DECISION: Modular Monolith
30 → One binary, but with strict bounded contexts
31 → Each domain in a separate, isolated package
32 → Communication between domains via interface or event (Kafka)
33 → Easy to extract into microservices if needed
34
35Rationale:
36 For a team of 8 and a scale of 100K MAU, microservice overhead
37 is not worth the benefit. A modular monolith gives development
38 speed while still keeping good isolation.The modular monolith decision is not a lazy compromise — it is a conscious choice that defers microservice complexity until the scale truly demands it, while keeping domain boundaries clean so a later migration is easy.
02.02 Using Claude for Architecture Review
Claude can act as an architecture sparring partner. The review-session transcript below shows how to give full context and sharp questions to get useful feedback.
1Prompt used with Claude Code:
2
3"We are designing the architecture for Santekno Shop — a B2C e-commerce
4platform in Indonesia with Go 1.22, Echo v4, PostgreSQL, Redis, Kafka.
5Team: 8 developers. Scale target: 100K MAU, 10K orders/day.
6
7We have identified 5 bounded contexts:
81. User Management (auth, profile)
92. Product Catalog (catalog, search, inventory)
103. Order Management (cart, checkout, order lifecycle)
114. Payment (gateway integration)
125. Notification (email, push)
13
14Please review:
151. Are these boundaries correct?
162. What could go wrong with this design?
173. Which dependencies should we watch out for?
184. What inter-domain communication pattern do you recommend?"
19
20Claude's response (summary):
21→ Boundaries are correct, but watch out for Order-Payment coupling
22→ Risk: Payment tightly coupled to Order — needs event-driven decoupling
23→ Notification must be fully event-driven, no direct calls allowed
24→ Product Catalog needs attention on consistency during stock updates
25→ Recommendation: User Management as an auth provider, not a business domainThe value of this session is not a “yes/no” answer, but the subtle risks found early — such as the Order-Payment coupling — which are far cheaper to fix on the whiteboard than in production code.
02.03 Directory Structure: Modular Monolith
The modular monolith decision needs to be translated into a concrete folder structure. The directory layout below maps every clean architecture layer to its physical location.
1santekno-shop/
2├── cmd/
3│ └── server/
4│ └── main.go ← main entry point
5│
6├── internal/
7│ ├── domain/ ← domain types and interfaces
8│ │ ├── user/
9│ │ │ ├── entity.go ← User, Address entity
10│ │ │ ├── repository.go ← UserRepository interface
11│ │ │ └── errors.go ← domain-specific errors
12│ │ ├── order/
13│ │ │ ├── entity.go ← Order, OrderItem entity
14│ │ │ ├── repository.go ← OrderRepository interface
15│ │ │ └── errors.go
16│ │ ├── product/
17│ │ │ ├── entity.go
18│ │ │ ├── repository.go
19│ │ │ └── errors.go
20│ │ └── payment/
21│ │ ├── entity.go
22│ │ └── repository.go
23│ │
24│ ├── usecase/ ← business logic per domain
25│ │ ├── auth/
26│ │ │ ├── register.go
27│ │ │ ├── login.go
28│ │ │ └── refresh_token.go
29│ │ ├── order/
30│ │ │ ├── place_order.go
31│ │ │ ├── cancel_order.go
32│ │ │ └── get_orders.go
33│ │ ├── product/
34│ │ │ ├── list_products.go
35│ │ │ └── get_product.go
36│ │ └── payment/
37│ │ └── handle_webhook.go
38│ │
39│ ├── repository/ ← data access implementations
40│ │ ├── postgres/
41│ │ │ ├── user_repository.go
42│ │ │ ├── order_repository.go
43│ │ │ ├── product_repository.go
44│ │ │ └── payment_repository.go
45│ │ └── redis/
46│ │ └── session_repository.go
47│ │
48│ └── event/ ← event publishing
49│ ├── kafka/
50│ │ └── publisher.go
51│ └── outbox/
52│ └── worker.go
53│
54├── delivery/
55│ └── http/
56│ ├── handler/
57│ │ ├── auth_handler.go
58│ │ ├── order_handler.go
59│ │ ├── product_handler.go
60│ │ └── webhook_handler.go
61│ ├── middleware/
62│ │ ├── auth.go
63│ │ ├── rate_limit.go
64│ │ └── request_id.go
65│ └── router.go
66│
67├── pkg/ ← shared utilities
68│ ├── money/ ← monetary value helpers
69│ ├── token/ ← JWT utilities
70│ ├── validator/ ← custom validators
71│ └── pagination/ ← pagination helpers
72│
73├── migrations/ ← database migrations
74├── config/ ← configuration
75├── CLAUDE.md
76├── .golangci.yml
77├── go.mod
78└── docker-compose.ymlThis structure is not just aesthetically tidy: the separation of domain, usecase, repository, and delivery is exactly what CI will later enforce. A misplaced directory is immediately detected as an architecture violation.
02.04 Clean Architecture Layer Rules
The folder structure alone is not enough — we need strict dependency rules. The list of rules below establishes the direction of dependencies between layers, enforced by CI.
1LAYER DEPENDENCIES (one direction only):
2
3delivery (HTTP handler)
4 ↓ depends on
5usecase (business logic)
6 ↓ depends on
7domain (entities + interfaces)
8 ↑ implemented by
9repository (data access)
10
11RULES enforced by CI (from the previous topic):
12
131. A handler MUST NOT import a repository implementation directly
14 Handler → usecase interface ONLY
15
162. A usecase MUST NOT import a framework
17 No: import echo, gin, chi in a usecase
18
193. A usecase MUST NOT import a database driver directly
20 No: import pgx, redis in a usecase
21 Usecase → domain.Repository interface ONLY
22
234. A domain MUST NOT import external packages
24 Only: stdlib + github.com/google/uuid (exception)
25
265. A repository MAY import a database driver
27 Repository implements the domain.Repository interfaceThis one-direction rule is the core of clean architecture: the domain knows nothing about HTTP or the database. As a consequence, business logic can be tested without a server or a DB, and swapping the framework never touches the domain.
02.05 Dependency Graph
So that the layer rules are visible, we draw the dependency graph. The diagram below shows how each layer depends on the layer below it, with dashed arrows marking interface implementations.
graph TD
subgraph Delivery["Delivery Layer"]
H[HTTP Handler]
MW[Middleware]
R[Router]
end
subgraph UseCase["UseCase Layer"]
UC_Auth[auth.UseCase]
UC_Order[order.UseCase]
UC_Product[product.UseCase]
UC_Payment[payment.UseCase]
end
subgraph Domain["Domain Layer"]
D_User[domain/user]
D_Order[domain/order]
D_Product[domain/product]
D_Payment[domain/payment]
end
subgraph Infra["Infrastructure Layer"]
REPO_PG[postgres.Repository]
REPO_REDIS[redis.Repository]
KAFKA[kafka.Publisher]
OUTBOX[outbox.Worker]
end
H --> UC_Auth
H --> UC_Order
H --> UC_Product
H --> UC_Payment
UC_Auth --> D_User
UC_Order --> D_Order
UC_Order --> D_Product
UC_Payment --> D_Payment
D_User -.->|interface| REPO_PG
D_Order -.->|interface| REPO_PG
D_Product -.->|interface| REPO_PG
REPO_PG --> D_User
REPO_PG --> D_Order
OUTBOX --> KAFKA
Note that the interface arrows (dashed) point from domain to repository, while the repository implements the domain types — this is the dependency inversion that makes infrastructure depend on the domain, not the other way around.
02.06 Inter-Domain Communication Pattern
In a modular monolith, domains still need to talk to each other. The Go snippet below shows three communication patterns: direct interface, Kafka event, and outbox.
1// Pattern 1: Direct Interface Call (for synchronous operations)
2// UseCase to UseCase via interface — not via HTTP
3
4// Example: OrderUseCase needs to check product stock
5// WRONG: HTTP call to the product service (distributed)
6// RIGHT: inject the ProductRepository interface into OrderUseCase
7
8type PlaceOrderUseCase struct {
9 orderRepo domain.OrderRepository
10 productRepo domain.ProductRepository // direct, because modular monolith
11 eventPub event.Publisher
12}
13
14// Pattern 2: Event via Kafka (for asynchronous operations)
15// OrderPlaced → Notification consumes the event and sends a notif
16
17// Pattern 3: Outbox (for guaranteed delivery)
18// The event is written to the DB in the same transaction
19// A background worker publishes to KafkaThe key design idea here: synchronous operations (checking stock during place order) use a fast in-process interface, while asynchronous operations (notifications) use events. The pattern choice depends on whether the caller needs an immediate result.
02.07 Database Schema Design
The domain needs to be materialized into tables. The SQL migrations below define the schema for user, product, and the full-text search trigger while also preparing the embedding column for AI.
1-- migrations/20260701000001_create_users.up.sql
2CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
3CREATE EXTENSION IF NOT EXISTS "pg_trgm"; -- for full-text search
4CREATE EXTENSION IF NOT EXISTS "vector"; -- for AI embeddings (later topic)
5
6CREATE TABLE users (
7 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
8 email VARCHAR(255) NOT NULL UNIQUE,
9 password_hash VARCHAR(255) NOT NULL,
10 name VARCHAR(100) NOT NULL,
11 is_active BOOLEAN NOT NULL DEFAULT true,
12 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
13 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
14);
15
16CREATE INDEX idx_users_email ON users(email);
17
18-- migrations/20260701000002_create_refresh_tokens.up.sql
19CREATE TABLE refresh_tokens (
20 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
21 user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
22 token_hash VARCHAR(255) NOT NULL UNIQUE,
23 expires_at TIMESTAMPTZ NOT NULL,
24 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
25);
26
27CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id);
28CREATE INDEX idx_refresh_tokens_token_hash ON refresh_tokens(token_hash);
29
30-- migrations/20260701000003_create_products.up.sql
31CREATE TABLE categories (
32 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
33 name VARCHAR(100) NOT NULL,
34 slug VARCHAR(100) NOT NULL UNIQUE,
35 parent_id UUID REFERENCES categories(id),
36 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
37);
38
39CREATE TABLE products (
40 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
41 category_id UUID REFERENCES categories(id),
42 name VARCHAR(255) NOT NULL,
43 description TEXT,
44 price_idr BIGINT NOT NULL CHECK (price_idr > 0), -- cents
45 stock INT NOT NULL DEFAULT 0 CHECK (stock >= 0),
46 reserved_stock INT NOT NULL DEFAULT 0 CHECK (reserved_stock >= 0),
47 is_active BOOLEAN NOT NULL DEFAULT true,
48
49 -- Full-text search
50 search_vector TSVECTOR,
51
52 -- AI embedding (filled in a later topic)
53 embedding VECTOR(1536),
54
55 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
56 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
57);
58
59CREATE INDEX idx_products_category_id ON products(category_id);
60CREATE INDEX idx_products_search_vector ON products USING GIN(search_vector);
61
62-- Auto-update search_vector
63CREATE OR REPLACE FUNCTION products_update_search_vector() RETURNS TRIGGER AS $$
64BEGIN
65 NEW.search_vector = to_tsvector('indonesian',
66 COALESCE(NEW.name, '') || ' ' || COALESCE(NEW.description, ''));
67 RETURN NEW;
68END;
69$$ LANGUAGE plpgsql;
70
71CREATE TRIGGER products_search_vector_trigger
72 BEFORE INSERT OR UPDATE OF name, description ON products
73 FOR EACH ROW EXECUTE FUNCTION products_update_search_vector();Two important details: price_idr BIGINT enforces the int64 cents ADR at the database level, and the embedding VECTOR(1536) column already exists even though it is only filled later — exactly the AI-ready principle with no future migration cost.
02.08 Order Tables Schema
The core part of e-commerce is the order and payment tables. The migrations below define the status enums, order, order_items, payments, and the outbox table for events.
1-- migrations/20260701000004_create_orders.up.sql
2CREATE TYPE order_status AS ENUM (
3 'PENDING', 'CONFIRMED', 'SHIPPED', 'DELIVERED', 'CANCELLED'
4);
5
6CREATE TYPE payment_method AS ENUM (
7 'BANK_TRANSFER', 'QRIS', 'CREDIT_CARD'
8);
9
10CREATE TABLE orders (
11 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
12 user_id UUID NOT NULL REFERENCES users(id),
13 status order_status NOT NULL DEFAULT 'PENDING',
14 total_amount_idr BIGINT NOT NULL CHECK (total_amount_idr > 0),
15 payment_method payment_method NOT NULL,
16 shipping_address JSONB NOT NULL, -- snapshot at order time
17 payment_url TEXT,
18 payment_expires_at TIMESTAMPTZ,
19 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
20 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
21);
22
23CREATE INDEX idx_orders_user_id ON orders(user_id);
24CREATE INDEX idx_orders_status ON orders(status);
25CREATE INDEX idx_orders_created_at ON orders(created_at DESC);
26
27CREATE TABLE order_items (
28 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
29 order_id UUID NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
30 product_id UUID NOT NULL REFERENCES products(id),
31 product_name VARCHAR(255) NOT NULL, -- snapshot
32 unit_price_idr BIGINT NOT NULL, -- snapshot cents
33 quantity INT NOT NULL CHECK (quantity > 0),
34 subtotal_idr BIGINT NOT NULL -- quantity * unit_price_idr
35);
36
37CREATE INDEX idx_order_items_order_id ON order_items(order_id);
38
39-- migrations/20260701000005_create_payments.up.sql
40CREATE TYPE payment_status AS ENUM (
41 'PENDING', 'COMPLETED', 'FAILED', 'REFUNDED'
42);
43
44CREATE TABLE payments (
45 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
46 order_id UUID NOT NULL REFERENCES orders(id),
47 external_payment_id VARCHAR(255), -- from the payment gateway
48 status payment_status NOT NULL DEFAULT 'PENDING',
49 amount_idr BIGINT NOT NULL,
50 method payment_method NOT NULL,
51 webhook_received_at TIMESTAMPTZ,
52 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
53 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
54 UNIQUE(external_payment_id) -- idempotency
55);
56
57-- migrations/20260701000006_create_outbox.up.sql
58CREATE TABLE outbox_events (
59 id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
60 event_type VARCHAR(100) NOT NULL, -- e.g., "order.placed"
61 topic VARCHAR(100) NOT NULL, -- Kafka topic
62 payload JSONB NOT NULL,
63 published BOOLEAN NOT NULL DEFAULT false,
64 published_at TIMESTAMPTZ,
65 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
66);
67
68CREATE INDEX idx_outbox_unpublished ON outbox_events(published, created_at)
69 WHERE published = false;Note the UNIQUE(external_payment_id) that enforces idempotency at the DB level, and the product_name/unit_price_idr snapshots in order_items so that order history does not change even if the product is updated later. This detailed schema directly reflects the business rules from the spec.
02.09 CLAUDE.md for Santekno Shop
So that Claude always understands the project conventions, we summarize all the architecture rules into CLAUDE.md. The contents of the file below become persistent memory that the AI reads in every session.
1# CLAUDE.md — Santekno Shop
2
3## Project Overview
4B2C E-commerce platform Indonesia.
5Go 1.22, Echo v4, pgx/v5, Redis, Kafka.
6Architecture: Modular Monolith → Clean Architecture.
7
8## Architecture Rules (CRITICAL)
9
10### Layer Boundaries
11handler → usecase (interface only, never impl)
12usecase → domain.Repository (interface only)
13usecase → event.Publisher (interface only)
14repository → domain types (implements interface)
15domain → stdlib + uuid only (zero external deps)
16
17### Monetary Values (CRITICAL)
18ALL monetary values: int64 (IDR cents)
191 IDR = 100 cents → Rp 50.000 = 5_000_000
20Field naming: price_idr, total_amount_idr, unit_price_idr
21NEVER use float64, float32 for money
22
23### Error Handling (CRITICAL)
24Repository not-found: return nil, nil
25Error wrap: fmt.Errorf("packageName.MethodName: %w", err)
26HTTP error format: {"error": "UPPERCASE_CODE", "detail": "..."}
27
28### Domain Error Codes
29See: internal/domain/errors.go for all error codes
30Example: ErrCodeOrderNotCancellable = "ORDER_NOT_CANCELLABLE"
31
32### Testing Requirements
33testify/suite + gomock
34Every AC from spec → minimum 1 test
35Test function naming: TestUseCaseName_Scenario_Expected
36
37### Database Conventions
38UUID for all primary keys (uuid_generate_v4())
39TIMESTAMPTZ for all timestamps (not TIMESTAMP)
40Monetary: BIGINT (cents), never DECIMAL or FLOAT
41Soft delete: use is_active boolean OR deleted_at column
42Enum: PostgreSQL ENUM types
43
44### Go Version: 1.22
45Do not use 1.23+ features.
46Generics: ok when appropriateBy writing “CRITICAL” rules such as int64 cents explicitly, we drastically reduce manual corrections to AI-generated code — Claude already knows the constraints before writing the first line.
02.10 Configuration Design
The application needs configuration that is safe and fail-fast. The Go code below loads all config from environment variables with mandatory validation for important secrets.
1// config/config.go
2
3package config
4
5import (
6 "os"
7 "strconv"
8 "time"
9)
10
11type Config struct {
12 App AppConfig
13 Database DatabaseConfig
14 Redis RedisConfig
15 Kafka KafkaConfig
16 JWT JWTConfig
17 Payment PaymentConfig
18}
19
20type AppConfig struct {
21 Port string
22 Environment string // development, staging, production
23 LogLevel string
24}
25
26type DatabaseConfig struct {
27 URL string
28 MaxOpenConns int
29 MaxIdleConns int
30 ConnMaxLifetime time.Duration
31}
32
33type JWTConfig struct {
34 AccessSecret string
35 RefreshSecret string
36 AccessExpiry time.Duration // 1 hour
37 RefreshExpiry time.Duration // 7 days
38}
39
40type PaymentConfig struct {
41 WebhookSecret string
42 GatewayURL string
43 TimeoutSeconds int
44}
45
46func Load() (*Config, error) {
47 return &Config{
48 App: AppConfig{
49 Port: getEnv("PORT", "8080"),
50 Environment: getEnv("ENV", "development"),
51 LogLevel: getEnv("LOG_LEVEL", "info"),
52 },
53 Database: DatabaseConfig{
54 URL: mustEnv("DATABASE_URL"),
55 MaxOpenConns: getEnvInt("DB_MAX_OPEN_CONNS", 25),
56 MaxIdleConns: getEnvInt("DB_MAX_IDLE_CONNS", 5),
57 ConnMaxLifetime: time.Duration(getEnvInt("DB_CONN_MAX_LIFETIME_MIN", 5)) * time.Minute,
58 },
59 JWT: JWTConfig{
60 AccessSecret: mustEnv("JWT_ACCESS_SECRET"),
61 RefreshSecret: mustEnv("JWT_REFRESH_SECRET"),
62 AccessExpiry: time.Hour,
63 RefreshExpiry: 7 * 24 * time.Hour,
64 },
65 Payment: PaymentConfig{
66 WebhookSecret: mustEnv("PAYMENT_WEBHOOK_SECRET"),
67 GatewayURL: getEnv("PAYMENT_GATEWAY_URL", "https://payment.dev.local"),
68 TimeoutSeconds: getEnvInt("PAYMENT_TIMEOUT_SECONDS", 30),
69 },
70 }, nil
71}
72
73func mustEnv(key string) string {
74 val := os.Getenv(key)
75 if val == "" {
76 panic("required environment variable not set: " + key)
77 }
78 return val
79}
80
81func getEnv(key, defaultVal string) string {
82 if val := os.Getenv(key); val != "" {
83 return val
84 }
85 return defaultVal
86}
87
88func getEnvInt(key string, defaultVal int) int {
89 val := os.Getenv(key)
90 if val == "" {
91 return defaultVal
92 }
93 i, _ := strconv.Atoi(val)
94 return i
95}The mustEnv pattern that panics when a secret is missing is a deliberate fail-fast: it is better for the application to refuse to start at boot than to run without a JWT secret and quietly open a security hole.
02.11 Dependency Injection Container
All components need to be assembled in one place. The Go code below shows manual dependency injection via BuildContainer — without any DI framework.
1// cmd/server/wire.go (manual DI — not using the wire.go tool)
2
3package main
4
5import (
6 "github.com/jackc/pgx/v5/pgxpool"
7 "github.com/redis/go-redis/v9"
8
9 "github.com/santekno/santekno-shop/config"
10 "github.com/santekno/santekno-shop/delivery/http/handler"
11 "github.com/santekno/santekno-shop/internal/event/kafka"
12 "github.com/santekno/santekno-shop/internal/repository/postgres"
13 "github.com/santekno/santekno-shop/internal/usecase/auth"
14 "github.com/santekno/santekno-shop/internal/usecase/order"
15 "github.com/santekno/santekno-shop/internal/usecase/product"
16)
17
18type Container struct {
19 AuthHandler *handler.AuthHandler
20 OrderHandler *handler.OrderHandler
21 ProductHandler *handler.ProductHandler
22 WebhookHandler *handler.WebhookHandler
23}
24
25func BuildContainer(cfg *config.Config, db *pgxpool.Pool, rdb *redis.Client) *Container {
26 // Repositories
27 userRepo := postgres.NewUserRepository(db)
28 orderRepo := postgres.NewOrderRepository(db)
29 productRepo := postgres.NewProductRepository(db)
30 paymentRepo := postgres.NewPaymentRepository(db)
31
32 // Event publisher
33 publisher := kafka.NewPublisher(cfg.Kafka)
34
35 // Use cases
36 registerUC := auth.NewRegisterUserUseCase(userRepo)
37 loginUC := auth.NewLoginUserUseCase(userRepo, rdb, cfg.JWT)
38 placeOrderUC := order.NewPlaceOrderUseCase(orderRepo, productRepo, publisher)
39 cancelOrderUC := order.NewCancelOrderUseCase(orderRepo, publisher)
40 getOrdersUC := order.NewGetOrdersUseCase(orderRepo)
41 listProductsUC := product.NewListProductsUseCase(productRepo)
42 getProductUC := product.NewGetProductUseCase(productRepo)
43
44 // Handlers
45 return &Container{
46 AuthHandler: handler.NewAuthHandler(registerUC, loginUC),
47 OrderHandler: handler.NewOrderHandler(placeOrderUC, cancelOrderUC, getOrdersUC),
48 ProductHandler: handler.NewProductHandler(listProductsUC, getProductUC),
49 }
50}Manual DI is indeed more verbose than a framework, but the wiring is explicit and easy to trace: from here we can read the dependencies of each use case directly without any magic reflection.
02.12 Middleware Stack
An HTTP request needs to pass through layers of middleware before reaching the handler. The Go code below assembles the Echo router with a separation of public, JWT-protected, and webhook routes.
1// delivery/http/router.go
2
3package http
4
5import (
6 "github.com/labstack/echo/v4"
7 echomid "github.com/labstack/echo/v4/middleware"
8 "github.com/santekno/santekno-shop/delivery/http/middleware"
9)
10
11func SetupRouter(c *Container, cfg *config.Config) *echo.Echo {
12 e := echo.New()
13
14 // Global middleware
15 e.Use(echomid.Recover())
16 e.Use(echomid.RequestID())
17 e.Use(middleware.Logger())
18 e.Use(echomid.CORS())
19 e.Use(echomid.Gzip())
20
21 // Health check (no auth)
22 e.GET("/health", healthHandler)
23
24 // API v1
25 api := e.Group("/api/v1")
26
27 // Public routes (no auth)
28 authG := api.Group("/auth")
29 authG.POST("/register", c.AuthHandler.Register)
30 authG.POST("/login", c.AuthHandler.Login)
31 authG.POST("/refresh", c.AuthHandler.RefreshToken)
32
33 // Product routes (no auth for read)
34 productG := api.Group("/products")
35 productG.GET("", c.ProductHandler.List)
36 productG.GET("/:id", c.ProductHandler.Get)
37
38 // Protected routes (require JWT)
39 protected := api.Group("")
40 protected.Use(middleware.JWT(cfg.JWT.AccessSecret))
41
42 protected.POST("/orders", c.OrderHandler.PlaceOrder)
43 protected.DELETE("/orders/:id", c.OrderHandler.CancelOrder)
44 protected.GET("/orders", c.OrderHandler.GetOrders)
45
46 // Webhook (signature verification, not JWT)
47 webhookG := api.Group("/webhooks")
48 webhookG.POST("/payment", c.WebhookHandler.HandlePayment)
49
50 return e
51}The route-group separation directly reflects the auth rules from the spec: products can be read without login, orders require a JWT, and the webhook is verified via signature — not JWT. The router structure becomes living security documentation.
02.13 Event System Design
Asynchronous communication needs a clear event contract. The Go code below defines the Publisher interface, event types, and the domain-agnostic Kafka topic constants.
1// internal/event/publisher.go
2// Interface for event publishing (domain-agnostic)
3
4package event
5
6import "context"
7
8type Publisher interface {
9 Publish(ctx context.Context, event Event) error
10}
11
12type Event struct {
13 Topic string // Kafka topic: "santekno.orders.placed"
14 Key string // Partition key (e.g., order_id)
15 Payload interface{} // Event payload (will be marshalled to JSON)
16}
17
18// Defined events
19type OrderPlacedEvent struct {
20 OrderID string `json:"order_id"`
21 UserID string `json:"user_id"`
22 TotalIDR int64 `json:"total_amount_idr"`
23 ItemCount int `json:"item_count"`
24}
25
26type OrderCancelledEvent struct {
27 OrderID string `json:"order_id"`
28 UserID string `json:"user_id"`
29 Reason string `json:"reason"` // "user_cancelled" | "payment_failed"
30}
31
32type PaymentCompletedEvent struct {
33 PaymentID string `json:"payment_id"`
34 OrderID string `json:"order_id"`
35 AmountIDR int64 `json:"amount_idr"`
36}
37
38// Kafka topics
39const (
40 TopicOrderPlaced = "santekno.orders.placed"
41 TopicOrderConfirmed = "santekno.orders.confirmed"
42 TopicOrderCancelled = "santekno.orders.cancelled"
43 TopicPaymentCompleted = "santekno.payments.completed"
44 TopicPaymentFailed = "santekno.payments.failed"
45)The domain-agnostic Publisher interface lets a use case publish events without knowing the Kafka details. When testing, we simply mock this interface; in production, the Kafka implementation is used.
02.14 Error Handling Strategy
Domain errors must be mapped consistently to HTTP responses. The Go code below shows the sentinel errors in the domain and a mapper that translates them to HTTP status codes in the handler.
1// internal/domain/errors.go
2// Domain errors returned by use cases
3
4package domain
5
6import "errors"
7
8// Sentinel errors — check with errors.Is()
9var (
10 ErrEmailAlreadyRegistered = errors.New("email already registered")
11 ErrWeakPassword = errors.New("weak password")
12 ErrInvalidCredentials = errors.New("invalid credentials")
13 ErrOrderNotFound = errors.New("order not found")
14 ErrOrderNotCancellable = errors.New("order cannot be cancelled")
15 ErrCancelWindowExpired = errors.New("cancel window expired")
16 ErrInsufficientStock = errors.New("insufficient stock")
17 ErrProductNotFound = errors.New("product not found")
18 ErrInvalidSignature = errors.New("invalid signature")
19)
20
21// pkg/apierror/mapper.go
22// Map domain errors to HTTP responses
23
24package apierror
25
26import (
27 "errors"
28 "net/http"
29
30 "github.com/labstack/echo/v4"
31 "github.com/santekno/santekno-shop/internal/domain"
32)
33
34func Handle(c echo.Context, err error) error {
35 switch {
36 case errors.Is(err, domain.ErrEmailAlreadyRegistered):
37 return c.JSON(http.StatusConflict, ErrorBody("EMAIL_ALREADY_REGISTERED"))
38 case errors.Is(err, domain.ErrInvalidCredentials):
39 return c.JSON(http.StatusUnauthorized, ErrorBody("INVALID_CREDENTIALS"))
40 case errors.Is(err, domain.ErrOrderNotFound):
41 return c.JSON(http.StatusNotFound, ErrorBody("ORDER_NOT_FOUND"))
42 case errors.Is(err, domain.ErrOrderNotCancellable):
43 return c.JSON(http.StatusConflict, ErrorBody("ORDER_NOT_CANCELLABLE"))
44 case errors.Is(err, domain.ErrCancelWindowExpired):
45 return c.JSON(http.StatusConflict, ErrorBody("CANCEL_WINDOW_EXPIRED"))
46 case errors.Is(err, domain.ErrInsufficientStock):
47 return c.JSON(http.StatusUnprocessableEntity, ErrorBody("INSUFFICIENT_STOCK"))
48 default:
49 c.Logger().Errorf("unhandled error: %v", err)
50 return c.JSON(http.StatusInternalServerError, ErrorBody("INTERNAL_ERROR"))
51 }
52}
53
54type errorResponse struct {
55 Error string `json:"error"`
56 Detail string `json:"detail,omitempty"`
57}
58
59func ErrorBody(code string, details ...string) errorResponse {
60 resp := errorResponse{Error: code}
61 if len(details) > 0 {
62 resp.Detail = details[0]
63 }
64 return resp
65}This pattern centralizes the error-to-HTTP mapping in a single function. The use case simply returns a domain sentinel error, and Handle decides the status code — so the handler stays thin and consistent with the status codes in the spec.
02.15 Using Claude for Architecture Code Review
Claude is also useful for reviewing design decisions during implementation. The terminal session below shows how to ask Claude to evaluate potential issues in an architecture that has already been designed.
1# How to use Claude to review architecture decisions
2
3# In the terminal with Claude Code:
4> I have designed a modular monolith for Santekno Shop.
5 Please review whether there are potential issues with this design:
6
7 1. Handler → UseCase via interface injection
8 2. UseCase → ProductRepository and OrderRepository (both)
9 Does this violate SRP?
10 3. Outbox pattern for Kafka events
11 4. User-scoped query at the repository level
12
13 Stack: Go 1.22, Echo v4, pgx/v5, Redis, Kafka
14
15# Claude response (key points):
16# → A UseCase that injects two repositories: acceptable if the domain flow
17# genuinely needs both (place order needs to check product & create order)
18# → Consider: is ProductRepository in OrderUseCase scoped
19# only for queries (not mutations)?
20# → Outbox pattern: make sure the background worker has a retry mechanism
21# → User-scoped in the repository: good, but make sure there's a proper indexA review like this catches details that are easy to miss, such as the need for a retry on the outbox worker or ensuring ProductRepository in OrderUseCase only reads. This is cheap validation before code is written.
02.16 Docker Compose for Development
Developers need consistent local dependencies. The Docker Compose configuration below spins up PostgreSQL (pgvector), Redis, and Kafka for the development environment.
1# docker-compose.yml
2
3version: '3.8'
4
5services:
6 postgres:
7 image: pgvector/pgvector:pg15
8 environment:
9 POSTGRES_DB: santekno_shop
10 POSTGRES_USER: postgres
11 POSTGRES_PASSWORD: postgres
12 ports:
13 - "5432:5432"
14 volumes:
15 - postgres_data:/var/lib/postgresql/data
16 healthcheck:
17 test: ["CMD-SHELL", "pg_isready -U postgres"]
18 interval: 5s
19 timeout: 5s
20 retries: 5
21
22 redis:
23 image: redis:7-alpine
24 ports:
25 - "6379:6379"
26 healthcheck:
27 test: ["CMD", "redis-cli", "ping"]
28 interval: 5s
29
30 kafka:
31 image: confluentinc/cp-kafka:7.5.0
32 environment:
33 KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
34 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
35 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
36 ports:
37 - "9092:9092"
38 depends_on:
39 - zookeeper
40
41 zookeeper:
42 image: confluentinc/cp-zookeeper:7.5.0
43 environment:
44 ZOOKEEPER_CLIENT_PORT: 2181
45
46volumes:
47 postgres_data:Using the pgvector/pgvector:pg15 image from the start means the vector extension is already available — when the AI topic arrives, we just enable it with a single SQL command without swapping the database image.
02.17 Package Naming Conventions
Consistent naming makes code easy to navigate. The Go snippet below establishes the conventions for package, interface, struct, and constructor names across the whole project.
1// Conventions used across the whole project
2
3// Package names: lowercase, one word
4package user // domain
5package order // domain
6package auth // usecase
7package postgres // repository implementation
8package kafka // event publisher
9
10// Interface names: no -er suffix unless it really is an action
11type OrderRepository interface{ /* ... */ } // not OrderRepositorier
12type Publisher interface{ /* ... */ } // not EventPublisher (too verbose)
13
14// Concrete struct names: descriptive but concise
15type postgresOrderRepository struct{ /* ... */ } // lowercase = package-private
16type PlaceOrderUseCase struct{ /* ... */ } // exported
17
18// Constructor pattern: NewXxx
19func NewOrderRepository(db *pgxpool.Pool) domain.OrderRepository { /* ... */ }
20func NewPlaceOrderUseCase( /* ... */ ) *PlaceOrderUseCase { /* ... */ }These conventions eliminate style debates in code review. The NewXxx constructor returning an interface, for example, ensures consumers always depend on the abstraction, not the concrete implementation.
02.18 Architecture Review Checklist
Before writing code, we need to verify the architecture is ready. The checklist below summarizes the points that must be satisfied at each layer.
1Before starting implementation, verify:
2
3Domain layer:
4□ Each domain has entity.go, repository.go, errors.go
5□ No external imports in the domain (other than uuid)
6□ Monetary values are all int64
7□ Repository interface is complete (CRUD + domain queries)
8
9UseCase layer:
10□ Each usecase in a separate file
11□ No framework imports (echo, chi, gin)
12□ No database driver imports (pgx, redis)
13□ All business rules in the usecase, not in the handler
14□ Error handling: return domain errors, not http errors
15
16Repository layer:
17□ Implements the domain.Repository interface
18□ return nil, nil for not-found
19□ Errors are wrapped: fmt.Errorf("postgresOrderRepo.GetByID: %w", err)
20□ SQL queries use parameterized queries
21□ Monetary values stored as BIGINT cents
22
23Handler layer:
24□ Only inject usecase interfaces (not impl)
25□ Request parsing → usecase call → response formatting
26□ Error handling via apierror.Handle()
27□ No business logic in the handler
28□ Validation in the handler (before the usecase)This checklist becomes a manual quality gate before the automatic CI gate. If even one box is unchecked, implementation is deferred — preventing technical debt from entering from the very first line.
02.19 Next Steps: Implementation Begins
The architecture foundation is complete; now we know where to step. The roadmap below summarizes what will be covered in the following articles.
1The next articles will cover:
2
3Article 03: OpenAPI Contract
4 → Documenting the API contract before implementation
5 → Generating a mock server for the frontend team
6 → Swagger/OpenAPI spec from the Article 01 spec
7
8Article 04: Setup CLAUDE.md + CI Pipeline
9 → A comprehensive CLAUDE.md
10 → .golangci.yml with rules from clean architecture
11 → GitHub Actions pipeline from the previous topic
12 → Pre-commit hooks
13
14Article 05+: Implementation domain by domain
15 → Auth, Product, Order, Payment
16 → Each domain has its own article with complete codeThis roadmap shows that we are still finishing the “contract and setup” phase before touching domain implementation — the spec-first discipline that keeps every line of code grounded in a clear basis.
02.20 Architecture Summary
The Santekno Shop architecture we designed:
Modular Monolith — one binary, strict bounded contexts.
Clean Architecture — 4 layers with dependency rules enforced by CI.
Event-driven — Kafka + outbox pattern for reliable async communication.
AI-ready — pgvector from day one, schema ready for the upcoming AI topics.
Everything-as-code — architecture decisions in CLAUDE.md, database schema in migrations, API contract in the OpenAPI spec.
With this blueprint, the team can start implementation without needing any more big structural decisions in the middle of the road. Next, we turn the spec into a formal API contract via OpenAPI.