Architecture¶
This document describes the design of GinBlade: the process model, the layering rules, dependency management, request/task lifecycles, and how to extend the skeleton with new business modules. It is intended for anyone who picks this repository up as the starting point of a real service.
Design Principles¶
- Separate processes, not one monolith. The API, the async worker, and the migration runner are independent binaries. They can be deployed, scaled, and released independently.
- Explicit layering. Application flow is
handler -> service -> repository. Dependencies point inward: outer layers depend on interfaces defined by the layer they call. - Hand-written dependency injection. No DI framework. Resources are
assembled in
bootstrapand passed down explicitly as structs. This keeps the dependency graph visible in one place and avoids magic. - Centralized lifecycle. Every shared resource (DB pool, Redis client,
queue client) is owned by a
bootstrap.Registryand released in one place on shutdown. - Optional infrastructure. Redis and JWT are optional. When they are not
configured, the corresponding routes are not registered, the health check
reports
not_configured, and the rest of the service keeps working. - Framework is an implementation detail. Only the HTTP shell depends on
Gin. Everything below
handleris plain Go, so the HTTP layer can be swapped if the standard library (or another router) ever becomes a better fit.
Process Model¶
┌──────────────────────────────────────────────┐
│ Registry │
│ Cfg · DBManager · Cache · JWT · Queue │
└───────┬──────────────┬──────────┬────────────┘
│ │ │
┌───────────────▼───┐ ┌──────▼───────┐ │
│ cmd/api │ │ cmd/worker │ │
│ HTTP server │ │ Asynq worker │ │
│ (Gin) │ │ │ │
└───────────────┬───┘ └──────┬───────┘ │
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────────┐
│ Postgres │ │ Redis │ │ migrations │
│ │ │ (queue + │ │ (cmd/migrate)│
└──────────┘ │ cache) │ └──────────────┘
└──────────┘
cmd/api— serves HTTP. Requires Postgres; Redis and JWT are optional.cmd/worker— consumes Asynq tasks. Requires Redis; Postgres is optional (only needed by handlers that touch the database).cmd/migrate— runs GORMAutoMigratefor the example table. In the Compose stack it runs once and exits beforeapi/workerstart.
Each process follows the same startup sequence:
config.LoadEnv → config.Load → bootstrap.InitRuntime → bootstrap.Init<Process>
→ app.New<Server|Worker> → run with signal-based graceful shutdown
Layering¶
HTTP shell (Gin-coupled)
handler parse/validate request, call service, write response
middleware trace, recovery, timeout, CORS, auth, rate limit
router route registration (skips optional modules when unconfigured)
───────────────────────────────────────────────────────────────
Application core (framework-free)
service business rules; declares the repository/queue interfaces it needs
repository persistence (GORM); context-scoped transactions (InTx/WithTx)
model GORM table models
task async task types and payloads
worker Asynq server, handlers, trace middleware
taskqueue queue boundary wrapper
errcode business error codes
───────────────────────────────────────────────────────────────
Infrastructure (pkg/, reusable)
auth · cache · database · log · response · validator
Rules:
handlernever touches the database or the queue directly. It only calls the service and maps errors to the response envelope.servicedefines the interfaces it consumes (ExampleRepository,ExampleQueue). The concrete implementations are injected bybootstrap. This is the consumer-defines-interface pattern and it is what makes the service layer unit-testable without a database.repositoryknows GORM, nothing else. Transaction support is carried through the context:InTxstarts a transaction (or joins an existing one from the context),dbFromContexttransparently uses the active transaction inside repositories.workerhandlers receiveDeps(DB, cache, Redis client, queue) as a struct, mirroring the handler-layer injection style.
Dependency Injection & Lifecycle¶
internal/bootstrap is the composition root:
InitAPI/InitWorkerbuild the shared resources and return a*Registry.- Optional resources return
nilwhen their configuration is absent (initCachereturns nil without Redis addr,initAuthwithout JWT secret). Registry.Close()releases everything it owns and aggregates errors witherrors.Join, so a partial failure still closes the rest.
The HTTP handlers and the worker deps are then assembled in
internal/server.go and internal/worker.go respectively.
HTTP Request Lifecycle¶
client
│ X-Request-ID (optional)
▼
TraceLogger generate/forward trace id; audit log on completion
Recovery panic → errcode.InternalError response
Timeout attach context deadline (REQUEST_TIMEOUT)
CORS allow-list check, OPTIONS short-circuit
RateLimit in-memory per-IP token bucket (when enabled)
▼
router → handler → service → repository → Postgres
▼
response envelope { code, msg, reason, data, metadata{trace_id} }
Conventions:
- Success:
code = 0, HTTP 200. - Business errors:
{ code, msg, reason, metadata }, HTTP 200 by convention (the code in the envelope is the source of truth). /healthis the exception: it uses real HTTP status codes and returns 503 when a required dependency is unavailable.
Async Task Lifecycle¶
- Publish —
servicebuilds a task withtask.NewExampleTask(name, traceID)and callsqueue.Enqueue(ctx, task). Thetrace_idfrom the request context is embedded in the payload. - Consume — the worker's
ServeMuxroutes by task type to the handler. ATraceMiddlewarerestores thetrace_idfrom the payload (or creates one scoped to the task), and logs start/finish/failure events with task id, queue name, and retry count. - Retry —
MaxRetry(5)with exponential backoff5s × 2^ncapped at 1h; anErrorHandlerrecords failures.
Three queues with priorities: critical:6 / default:3 / low:1, concurrency
10.
Configuration¶
All configuration comes from environment variables, read once in
config.Load() with sensible defaults. config.LoadEnv loads
cmd/<process>/.env and falls back to the repository-root .env. See
README.md for the full variable table.
Extending: Add a New Business Module¶
Copy the Example flow. For a synchronous feature:
internal/model/— GORM model.internal/repository/— repository with the methods your service needs; useInTx/dbFromContextif the flow needs transactions.internal/service/— business logic; declare the repository interface here; expose typed request/response structs with validation tags.internal/handler/— bind/validate, call service, write response.internal/router/— register routes.internal/server.go— wire repository → service → handler.
For an asynchronous feature, additionally:
internal/task/— task type constant, payload struct, constructor.internal/worker/handler.go— the handler; register it inRegisterHandlers.internal/service/— enqueue the task (respectqueue.Available()).
Framework Coupling (why swapping Gin is cheap)¶
The framework boundary is deliberate. These packages reference gin:
These do not:
internal/service internal/repository internal/model
internal/task internal/taskqueue internal/worker
internal/bootstrap
pkg/auth pkg/cache pkg/database pkg/log pkg/validator
Business rules, persistence, task processing, and infrastructure helpers are
framework-free. If the standard library router (Go 1.22+ http.ServeMux
already supports method matching and path wildcards) or another framework
ever becomes the better choice, migrating means rewriting the HTTP shell —
handlers, middleware, router, and pkg/response — while the application core
stays untouched.