What is a domain-first Go project structure, and why do layer-first layouts break down?
A domain-first Go project structure groups code by business capability, such as billing, orders or identity, rather than by technical role. Each domain package owns its handlers, business logic, storage access and types. A modular monolith applies this inside a single deployable binary: domains are separate packages with explicit boundaries, but they ship, scale and deploy together. This guide is for backend and platform engineers running one large service who want those boundaries without the operational cost of microservices.
The common alternative is a layer-first layout with controllers/, services/, repositories/ and models/. It reads cleanly at a few thousand lines and degrades as the service grows:
- Changes scatter. Adding a field to an order touches four packages, so diffs and code review cross every layer.
modelsbecomes a hub. Every layer imports it, so it accumulates every type in the system. Changing it recompiles and potentially breaks everything.- Import cycles force workarounds. The Go compiler rejects cyclic imports. When
services/ordersneedsservices/billingand billing needs orders back, teams extract interface-only packages or merge the two packages, which blurs ownership further.
| Concern | Layer-first | Domain-first |
|---|---|---|
| Scope of one feature change | Many packages across layers | Mostly one domain package |
| Shared types | One central models package |
Owned by each domain |
| Cycle pressure | High, because layers cross-reference | Lower, because dependencies follow domain relationships |
| Ownership | Split by layer | One team or person per domain |
Who should use a domain-first modular monolith?
This structure fits teams in the following situations:
- One Go service, several owners. Two or more teams, or several engineers with distinct areas, change the same codebase. Domain packages give each group a directory it owns and a public surface it controls.
- A service that has outgrown its layer-first layout. Feature changes routinely touch
controllers,services,repositoriesandmodelsat once, themodelspackage keeps growing, or the team keeps adding interface-only packages to break import cycles. - Teams weighing microservices but not ready for them. If the main goal is clearer ownership and fewer accidental dependencies, rather than independent scaling or deployment, a modular monolith gets most of the structural benefit without network calls, versioned APIs or more deployables to operate. It also leaves the option to extract a domain later, because clean facades are the first thing an extraction needs.
- Platform engineers who own CI and repository conventions. The boundary checks, code-owner rules and per-domain test scoping described below are mostly their work, and they benefit from a layout that makes those rules easy to express.
It is a poor fit for small services that one person can hold in their head, for prototypes, and for products whose business domains are still changing quickly. The last section covers those cases in more detail.
How does a Go modular monolith work?
At runtime, a modular monolith is an ordinary Go program: one module, one main package, one binary, one process. Calls between domains are plain in-process function calls, not network requests. All of the modularity lives in how the source is organised and checked:
- Packages are the modules. Each domain is a Go package (or a small tree of packages) under
internal/. Go's exported-identifier rule, capitalised names only, already limits what other packages can see. Each domain uses it to expose a small facade and keep everything else unexported. - The
internaldirectory rule hides implementation packages. Nestinginternal/inside a domain, for exampleinternal/billing/internal/ledger, makes the compiler reject imports of that package from other domains. - Dependencies point inward through consumer-side interfaces. A domain declares the small interface it needs from another domain or from storage. It never imports transport or database packages, and concrete implementations are injected at startup.
mainwires everything. The entry point builds the database connection, the storage adapters, each domain's service and the HTTP handlers, then passes dependencies into constructors. It is the only package that imports every domain.- CI enforces the rules the compiler cannot. A dependency check built on
go listrejects forbidden domain-to-domain imports, and code-owner rules route changes to the owning team.
A request flows like this: the HTTP handler in internal/billing/http.go decodes the request and calls the billing service. The service applies business rules, calls the accounts domain through the AccountLookup interface it declared, and persists results through its own storage code. The handler then encodes the response. Every hop is a function call in the same process, so a single database transaction can span the whole operation if needed. The sections below cover each of these mechanisms in turn.
How should you lay out a modular monolith in Go?
Start with one binary entry point and a flat set of domain packages under internal/:
cmd/api/main.goreads config, opens the database, builds each domain's services and handlers, and starts the server. Wiring lives here becausemainis the only place that should know about every domain at once.internal/billing/,internal/accounts/,internal/catalog/each own their types, business logic, storage code and transport adapters (HTTP handlers, queue consumers). A reader looking for "how refunds work" opens one directory.internal/platform/holds logging, config loading and database connection setup. Keep it small and free of business rules. It is shared plumbing, and domains import it, never the reverse.
Inside a domain, colocate everything that changes with it. Unit tests sit next to the code they test as _test.go files. SQL migrations go in internal/billing/migrations/, so a schema change and the code that depends on it land in the same review. Generated code, such as protobuf stubs or query bindings, goes in a subpackage like internal/billing/gen/ so regeneration never touches handwritten files.
This layout lets you run go test ./internal/billing/... to test one domain alone. That gives fast feedback for the owning team and makes it easy to scope CI jobs.
Resist deep nesting and splitting a domain into many tiny packages. Paths like internal/billing/service/invoice/handler force readers to jump between directories and create cycle risk inside the domain. Start with one package per domain and split only when a subpackage has a clear, independent purpose.
myapp/
├── go.mod
├── cmd/
│ └── api/
│ └── main.go # wiring only: config, DB, build services, start server
├── internal/
│ ├── platform/ # shared plumbing, no business rules
│ │ ├── config.go
│ │ ├── db.go
│ │ └── log.go
│ ├── billing/ # one package per domain to start
│ │ ├── invoice.go # types and business logic
│ │ ├── invoice_test.go # unit tests next to the code
│ │ ├── store.go # storage code
│ │ ├── http.go # HTTP handlers (transport adapter)
│ │ ├── migrations/ # schema changes reviewed with the code
│ │ │ └── 0001_create_invoices.sql
│ │ └── gen/ # generated code, safe to regenerate
│ ├── accounts/
│ │ ├── account.go
│ │ ├── account_test.go
│ │ ├── store.go
│ │ ├── http.go
│ │ └── migrations/
│ └── catalog/
│ ├── product.go
│ ├── product_test.go
│ ├── store.go
│ ├── http.go
│ └── migrations/
A flat modular monolith layout: wiring in cmd/api, one package per domain under internal/ with its own tests, migrations and generated code, and go test scoped to a single domain.
How does Go's internal directory rule enforce module boundaries?
The Go toolchain treats any directory named internal as a visibility boundary. A package whose import path contains an internal element can only be imported by packages rooted at the parent of that internal directory. example.com/shop/internal/billing is importable from anywhere under example.com/shop/, but not from another module. The check runs at build time and applies to every import, so the boundary holds even when nobody is reviewing the code.
The rule becomes useful for domains when you nest it. Put billing's ledger logic at internal/billing/internal/ledger. Now only internal/billing and packages beneath it can import ledger. If internal/accounts tries to import it, the build fails with an error of the form use of internal package example.com/shop/internal/billing/internal/ledger not allowed. Other domains are forced through billing's root package, which becomes the domain's public API. You can then restructure the ledger freely, because the compiler guarantees nothing outside billing depends on it.
The rule has limits:
- It works only on paths. It checks where an import comes from, not what the imported package exposes. If
internal/billingexports its repository struct, its database row types, and a dozen helper functions, any sibling domain can use all of them. Keeping the root package's API small is still a design decision you have to make. - It cannot express direction.
internal/billingandinternal/accountsshare a parent, so each can import the other. The compiler permits both directions, and Go's ban on import cycles only blocks the case where both happen at once. A rule such as "billing may depend on accounts, never the reverse" needs a different mechanism.
mkdir -p shop && cd shop
go mod init example.com/shop
mkdir -p internal/billing/internal/ledger internal/accounts
cat > internal/billing/internal/ledger/ledger.go <<'EOF'
package ledger
func Post(accountID string, cents int64) error { return nil }
EOF
cat > internal/billing/billing.go <<'EOF'
package billing
import "example.com/shop/internal/billing/internal/ledger"
func Charge(accountID string, cents int64) error {
return ledger.Post(accountID, cents)
}
EOF
cat > internal/accounts/accounts.go <<'EOF'
package accounts
import "example.com/shop/internal/billing/internal/ledger"
func Refund(id string) error { return ledger.Post(id, -100) }
EOF
go build ./internal/billing/... # succeeds: importer is rooted at internal/billing
go build ./... # fails because of internal/accounts
Billing can import its nested internal/ledger package, but the build fails when the accounts domain imports the same package, because accounts is not rooted at internal/billing.
How do you keep dependency direction pointing inward?
Domain packages should not import net/http, database/sql, or a driver package. Once a request struct or a *sql.Tx appears in a domain function signature, every caller must deal with transport or storage concerns. Tests then need a database or an HTTP recorder to exercise business rules. Keeping those types out of the domain makes the arrows point one way: adapters depend on the domain, and the domain depends on nothing outside itself.
Go's implicit interface satisfaction makes this inexpensive. The consuming package declares the interface it needs, using only the methods it calls. In the accompanying example, billing declares an AccountLookup interface with a single method, AccountByID, and its constructor NewService accepts that interface as a parameter. The accounts package never references billing's interface and never needs to know it exists. Its concrete type satisfies the interface because the method set matches.
Assembly happens at the edge. cmd/server/main.go, or an internal/app package if wiring grows large, opens the database, builds the Postgres repository and the accounts service, and passes them into billing.NewService. The wiring package is the only place that imports everything, so it is the only place that knows how the system fits together.
This approach has a cost. Each interface adds an extra hop when navigating with "go to definition," and an interface with one implementation that never changes is noise. Inside a domain, use concrete types freely. Add an interface at a domain boundary, or when you need a test fake, not by default.
// internal/billing/service.go
package billing
import (
"context"
"example.com/shop/internal/accounts"
)
// AccountLookup is declared where it is consumed and lists only the
// method billing actually calls. The accounts package never sees it.
type AccountLookup interface {
AccountByID(ctx context.Context, id string) (accounts.Account, error)
}
type Service struct {
accounts AccountLookup
}
// NewService receives its dependency. Billing never imports net/http or database/sql.
func NewService(a AccountLookup) *Service {
return &Service{accounts: a}
}
// cmd/server/main.go: the only place that knows how the pieces fit (imports omitted)
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
repo := postgres.NewAccountRepo(db) // storage adapter
acct := accounts.NewService(repo) // *accounts.Service has an AccountByID method
bill := billing.NewService(acct) // satisfies billing.AccountLookup implicitly
http.Handle("/invoices", httpapi.NewInvoiceHandler(bill))
log.Fatal(http.ListenAndServe(":8080", nil))
}
This Go example shows billing declaring a one-method consumer-side interface and taking it through its constructor, while main.go builds the concrete Postgres repository and accounts service and injects them.
How should domains communicate and share types without a god package?
Each domain should expose a narrow public surface: one exported service type, or a handful of functions, that accept and return plain data types defined in that domain's API package. Storage structs, with their database tags, nullable columns and lazy-loaded fields, never cross the boundary. If billing imports orders' row type, a schema migration in orders breaks billing's compilation, and the boundary no longer protects anything.
There are three common ways for one domain to call another:
| Option | How it works | Cost |
|---|---|---|
| Direct call | Caller imports the other domain's service and calls it | Compile-time coupling. Simple and traceable, and both sides can share one transaction |
| Consumer-side interface | Caller declares the small interface it needs, and wiring injects the implementation | Some indirection and wiring code. The caller no longer imports the provider |
| In-process events | Producer publishes, subscribers react | No single transaction across handlers. Failures need retries, idempotency or an outbox. Control flow is harder to follow |
Use direct calls or interfaces by default. Reach for events only when the producer genuinely should not know who reacts.
For shared types, resist a models package. It becomes the place every domain depends on, and every change ripples everywhere. Duplicate small types per domain instead. The cost is mapping code at each boundary and the risk that copies drift apart, but that drift is usually the domains legitimately diverging. True value types such as IDs, money and time ranges belong in a tiny package with no dependencies of its own. Treat any package named util, common or helpers as a smell, because its name gives no reason for anything to stay out of it.
// internal/kernel/money.go: tiny value-type package, no imports of its own
package kernel
type OrderID string
type Money struct{ Cents int64; Currency string }
// internal/orders/api.go: the only surface other domains see
package orders
import "example.com/shop/internal/kernel"
// Order is a plain data type. The DB row struct stays unexported in orders.
type Order struct {
ID kernel.OrderID
Total kernel.Money
}
// internal/billing/invoice.go: billing never imports orders
package billing
import (
"context"
"example.com/shop/internal/kernel"
)
// billing's own copy of what it needs; it may drift from orders.Order on purpose.
type OrderSummary struct{ ID kernel.OrderID; Amount kernel.Money }
// Consumer-side interface: declared here, satisfied by an adapter in main.
type OrderReader interface {
OrderSummary(ctx context.Context, id kernel.OrderID) (OrderSummary, error)
}
type Service struct{ orders OrderReader }
func NewService(r OrderReader) *Service { return &Service{orders: r} }
// cmd/shop/main.go wires a small adapter that maps orders.Order to
// billing.OrderSummary. That mapping is the price of no shared models package.
A Go sketch with three packages. A dependency-free kernel package holds the IDs and money types. The orders domain exports plain data types, and billing declares its own interface and its own duplicated summary type, with the mapping between them done in main.
How can you enforce boundaries that internal cannot express?
The internal rule only controls which directories may import a package. It cannot say that billing must never import shipping when both sit under the same internal/ parent. You need a separate check for that rule, and the toolchain gives you what you need to build one.
go list -deps -f '{{.ImportPath}} {{.Imports}}' ./... prints every package in the build together with its direct imports. That output is your actual dependency graph. It is often different from the graph people believe they have. Feed it into a small Go test or CI script that holds a deny list, such as "nothing under internal/billing may import internal/shipping". The script exits non-zero and names the offending edge when a match appears. Keep the rules in the repository so that changing a boundary takes a reviewed commit.
Add code-owner rules for each domain directory as well. A change to internal/billing then requires approval from the billing team, so the people with context see every edit to their public surface.
Automation matters because boundaries rarely fail in one dramatic change. They erode one convenient import at a time. Each import looks harmless in a diff, and reviewers miss it because they are reading logic, not import blocks. A failing check removes that burden from reviewers and records the violation at the moment it is introduced, when it is cheapest to fix.
None of this protects the database. If every domain shares one schema, shipping can still query billing's tables directly, and no import graph will show it. Data ownership has to be enforced by convention and review. Examples are table-name prefixes per domain, a rule that only the owning package writes SQL against its tables, and reviewers who reject cross-domain joins.
How can a modular monolith save engineering time?
The time savings come from shrinking the amount of code a person or a CI job has to deal with for a given change, and from catching mistakes earlier:
- Smaller, more focused reviews. When a feature lives mostly in one domain directory, the diff touches one package instead of four layers. Reviewers read related code together, and code-owner rules send the review to the people who already know that domain.
- Faster local feedback. An engineer working on billing runs
go test ./internal/billing/...instead of the whole suite. Go's test cache also skips packages whose code and dependencies have not changed when you run tests in package-list mode, so repeated runs ofgo test ./...stay fast after a narrow change. - Scoped CI. Because each domain is a directory, CI can choose which domains to test based on changed paths. Remember to include the packages that depend on the changed domain, not just the domain itself. You can derive those reverse dependencies from the same
go listoutput used for boundary checks. - Fewer cycle workarounds. Dependencies follow real domain relationships and consumer-side interfaces, so teams spend less time inventing interface-only packages or untangling cycles created by a central
modelspackage. - Violations caught by machines, not people. The
internalrule and the CI import check fail the build when someone crosses a boundary. Nobody has to find the problem months later during a refactor, when many call sites depend on it. - Faster onboarding and debugging. A new engineer, or someone on call, can open one directory to understand how refunds or invoices work, instead of tracing a feature across controllers, services and repositories.
- No distributed-systems overhead. Compared with splitting into services, you avoid network failure handling between domains, versioned internal APIs, coordinated deploys and cross-service tracing for calls that are really just function calls.
As an illustrative estimate, with assumed inputs: suppose the full test suite takes 20 minutes, it is spread roughly evenly across 10 domains, and a typical billing change affects billing plus two domains that depend on it. A path-scoped CI job would then run about 3 of 10 domains, or roughly 6 minutes instead of 20. Your real numbers depend on how evenly tests are distributed, how much shared setup each package has, and how many domains depend on the one you changed. Measure your own suite before relying on a figure like this.
When should you use or avoid a modular monolith, and how do you migrate to one?
A modular monolith pays off when one team, or a few, share a service that has outgrown anyone's ability to hold it in their head, but splitting it into separately deployed services would add network failures, API versioning and on-call load that nobody needs yet. Defer it for small services and for products whose domains are still moving. Boundaries are guesses. If you draw them too early or too finely, you get chatty cross-domain calls and a facade refactor every sprint. Start with a handful of coarse domains and split them later, once real change patterns show where the seams are.
| Layout | Development cost | Deploy and scaling independence | Refactoring effort |
|---|---|---|---|
| Flat single package | Lowest at first, grows with size | None | Easy moves, but there are no boundaries to protect |
| Layered | Low | None | High, because one feature touches every layer |
| Modular monolith | Moderate | None, since it ships as one binary | Moderate, because cross-domain changes go through facades |
| Microservices | High | Full | High, because boundary changes need versioned APIs and coordinated deploys |
Migrate one domain at a time:
- Move the domain's code under its own
internalsubtree. - Expose an exported facade and point existing callers at it.
- When the move creates an import cycle, invert the dependency. The lower-level package declares an interface, and the other domain implements it.
- Keep the build and tests green after every step, and merge each step on its own.
Expect costs. Package moves produce large diffs, and those diffs conflict with in-flight branches, so announce moves and schedule them between feature merges. The bigger risk is stalling halfway, with two conventions living side by side indefinitely. Track the remaining packages explicitly so the migration has a visible end.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to go project structure domain, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.